feat (wasm): Adds csv/print to wasm iframes, core theme passing, optional unhashed description, scoped invoice status, fiat checkout and browser storage (#4328)
What changed, and why it matters
This commit adds several new features to LNbits' WebAssembly (WASM) extension system. It introduces ways for extensions to: check invoice status, refresh payment status, create fiat checkout invoices, store small amounts of data in the browser, export/print CSV documents, and receive theme information. The changes also strengthen how invoices are tied to the extension that created them, replacing loose dictionary data with a stricter typed structure and adding verification of invoice description hashes. Most changes are defensive in nature and include extensive tests, but they expand the attack surface of the WASM extension bridge and payment APIs.
Review the new WASM host API methods and bridge handlers as part of normal security review. Pay particular attention to: (1) `wallet.refresh_payment` ensuring it cannot be used to probe arbitrary payments or trigger repeated backend queries; (2) `wallet.create_fiat_invoice_public` URL validation and provider allowlist logic in real deployments; (3) `storage.local.*` quota enforcement and scoping under concurrent or malicious iframe contexts; (4) `ui.download_csv` formula-escaping and filename validation; (5) `ui.print_document` sandbox attributes and print iframe cleanup. The commit includes tests, but integration/end-to-end tests of the iframe boundary and shared-wallet scenarios would strengthen assurance.
Security signals we found
Untrusted `extension_context` dictionary replaced by frozen typed model `PaymentExtensionContext` with required `extension_id`, `owner_id`, `wallet_id`, and optional `source_id`.
New `wallet.invoice_status` method enforces strict binding checks (extension, owner, wallet, source) before returning only `paid/pending/failed/amount-msat`; rejects legacy/unbound invoices.
New `wallet.refresh_payment` requires authentication, wallet ownership or shared-wallet VIEW_PAYMENTS permission, and scopes payment lookup by wallet; hides backend error details.
New `wallet.create_fiat_invoice_public` validates source policies, wallet ownership, receive permission, and provider allowlist; sanitizes checkout URL (HTTPS only, no credentials, no control chars, max 4096 chars).
Public invoice creation now optionally verifies BOLT11 `description_hash` against caller-supplied `unhashed_description` to prevent metadata mismatch attacks.
Frontend bridge adds `storage.local.*` with per-extension/account/page scoping, 128-key/64 KiB quotas, 180-day TTL, key/value validation, and permission gating.
Frontend bridge adds `ui.download_csv` and `ui.print_document` with user confirmation, filename validation, formula-escaping, bounded tables, sandboxed print iframe, and no extension HTML/scripts.
Theme bridge exposes only an allowlisted color snapshot and dark flag via `postMessage`; does not allow extension-driven theme mutations.
Pagination `limit=0` added for count-only storage queries under the same permission/owner restrictions.
Evidence from the diff
The commit refactors extension_context from an untyped dict to a frozen Pydantic model PaymentExtensionContext, hardening invoice-to-extension binding validation. It adds new WASM host API methods: wallet.invoice_status (owner-scoped read-only status), wallet.refresh_payment (authenticated reconciliation of pending payments, supports shared wallets with VIEW_PAYMENTS), wallet.create_fiat_invoice_public (owner-scoped fiat checkout creation with source policy validation and HTTPS URL sanitization), and wallet.list_fiat_providers. Frontend bridge additions include ui.download_csv, ui.print_document, storage.local.*, and ui.theme notifications. The public invoice path now optionally verifies BOLT11 description hashes against caller-supplied unhashed_description. Pagination limit=0 is allowed for count-only queries. The commit is accompanied by comprehensive unit tests covering authorization, input validation, URL safety, CSV formula injection, storage isolation/quotas, and theme leakage.
Changed components
lnbits/core/models/payments.pylnbits/core/services/payments.pylnbits/core/wasm_ext/api/host.pylnbits/core/wasm_ext/api/models.pylnbits/core/wasm_ext/api/permissions.pylnbits/core/wasm_ext/api/registry.pylnbits/core/wasm_ext/wasm/events.pylnbits/static/js/wasm-extension-component.jsdocs/wasm-extensions.mdInspect captured patch +1919 / −83
### docs/wasm-extensions.md
@@ -157,6 +157,16 @@ types and wrappers from those methods. It does not replace building a matching
WIT component. Repository-specific `lnbits-sdk.js` wrappers can differ; verify
their behavior rather than treating one copied SDK as the host specification.
+`wallet.refresh_payment` (SDK: `wallet.refreshPayment`) explicitly refreshes a
+payment using `wallet_id` and `checking_id` (`walletId` and `checkingId` in the SDK).
+It requires `wallet.payments.refresh` and an authenticated user who owns the
+requested wallet, including a shared wallet with permission to view payments.
+The lookup also accepts a payment hash in `checking_id`. Pending payments are
+reconciled with the funding source, or marked failed if an incoming invoice has
+expired. Changes are persisted and can trigger settlement processing and
+notifications. Completed payments return their stored status without refreshing.
+The response contains identifiers, status, amount, fee, and pending/success flags.
+
Unknown config fields are currently ignored. In particular, copying a
`wasm.resource_limits` or `wasm.host_api` field does not configure the runtime.
Unknown requested permission IDs are rejected. See the
@@ -231,13 +241,35 @@ remain in the parent. Supported actions include:
| ---------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| `context`, `api` | Obtain UI context and call this extension's registered API routes |
| `ui.notify` | Display a browser notification/toast; separate from delivery to a user's notification channels |
+| `ui.download_csv` | Download a bounded CSV table after parent confirmation; validate filenames and escape formulas |
+| `ui.print_document` | Print bounded text and table cells after parent confirmation; no extension HTML or scripts |
| `navigation.replace`, `navigation.open_new_tab` | Parent-mediated navigation; opening an external tab requires confirmation |
| `storage.session.get`, `storage.session.set` | Transient session state |
| `ui.scan_qr` | Parent camera UI, with `ui.camera.scan_qr` and user approval |
| `permissions.request*` | User permission dialogs, including background-payment and wallet-watch grants |
| `payment.subscribe`, `payment.unsubscribe` | Payment updates for hashes accepted by the parent, including hashes returned by approved API calls |
| `websocket.subscribe`, `websocket.unsubscribe`, `websocket.send` | Parent-managed extension channels |
+Persistent receipts can use `storage.local.get`, `storage.local.set` and
+`storage.local.remove` with the `ui.storage.local` permission. Keys are limited
+to 128 ASCII letters, digits or `._:-`; values are strings of at most 1024 UTF-8
+bytes. The parent scopes entries by extension, account (or anonymous visitor)
+and page path. Each extension/account namespace permits 128 entries and 64 KiB
+of serialized data; entries expire 180 days after their last write. Query strings
+do not change the scope. Storage requires browser Web Crypto and local storage;
+handle unavailable storage as an optional-feature failure. Browser receipts are
+bearer tokens, never proof of payment: recheck settlement on the server before
+revealing paid content. This grants no access to other parent local-storage keys.
+
+The `context` response includes a read-only `theme` snapshot: `name`, the actual
+`dark` boolean, a `gradient` flag, and an allowlisted `colors` map of Quasar CSS
+colors. The parent sends `lnbits-extension:event` messages with `event: "ui.theme"`
+and the same snapshot in `data` when its theme changes. These notifications do
+not require a subscription or expose parent DOM access. Use the allowlisted
+`_lnbits/bundle.min.css` for LNbits theme styles, apply the supplied colors to
+`--q-*` properties, and set Quasar's dark mode from `theme.dark` rather than the
+iframe's OS preference.
+
The bridge is not a generic browser-to-core RPC or an arbitrary URL proxy.
External widgets in some repositories execute on another site's page and have
their own CSP/CORS constraints. They do not relax the LNbits iframe policy;
@@ -259,6 +291,7 @@ Installation approval does not replace per-user wallet grants.
| Private storage reads and writes | `ext.storage.read`, `ext.storage.write`; requires an owner |
| Public reads and public append | `ext.storage.read_public`, `ext.storage.append_public`; explicit table/field/source policies |
| List wallets / read balance | `wallet.list`, `wallet.balance.read`; accessible user wallets |
+| Refresh payment status | `wallet.payments.refresh`; user's wallet with permission to view payments |
| Create invoices | `wallet.create_invoice`; user's wallet |
| Public invoice creation | `wallet.create_invoice_public`; wallet selected through an approved stored source |
| Interactive outgoing payments | `wallet.pay_invoice`; user's wallet |
@@ -318,7 +351,9 @@ save the second user's settings. Generate distinct IDs and locate configuration
through an owner-scoped query.
Private storage supports get, upsert, delete, and pagination. Pages are limited
-to 1,000 rows, with equality filters, search, and one sort key. Pagination is not
+to 1,000 rows, with equality filters, search, and one sort key. A page limit of
+zero returns the scoped total without loading record payloads; the same read
+permission and owner/public-source restrictions apply. Pagination is not
a transactionally consistent snapshot. Large scans must fit the invocation's
storage-call and response budgets.
@@ -377,12 +412,42 @@ instead of the memo, which LNURL-pay (LUD-06) requires: pass the hex-encoded
metadata string as `unhashed_description` so the hash matches the payer's
check. When either field is set, the memo is not stored.
+For public invoices with a nonempty `unhashed_description`, the host verifies
+the returned BOLT11 description hash against the decoded metadata bytes. An
+invalid invoice or a missing or mismatched hash is rejected before the invoice
+is returned to the extension. Components that omit both fields retain ordinary
+memo invoices.
+
Tagged invoice events require the immutable `extension_context` written by the
core WASM invoice APIs. Caller-supplied `extension`, `extra.tag`, or source IDs
cannot authenticate an event. Invoices created before that binding was added
no longer trigger tagged WASM events; recreate outstanding extension invoices.
Explicit wallet-watch grants continue to authorize additional incoming events.
+`wallet.invoice_status` exposes `invoice-status(payment-hash, source-id)` to
+owner-scoped invocations with that permission. The host checks an incoming
+payment's immutable extension, owner, wallet and source binding before returning
+its stored status. It rejects unrelated invoices and legacy invoices without a
+trusted binding. This operation does not query the backend or update payments.
+Pending payments are reconciled by core's background processing; an authenticated
+wallet user can also request reconciliation with `wallet.refresh_payment` and
+the separate `wallet.payments.refresh` permission.
+Only `paid`, `pending`, `failed` and `amount-msat` are returned; no keys, preimages,
+provider identifiers or arbitrary wallet history are exposed.
+
+`wallet.create_fiat_invoice_public` permits `create-fiat-invoice-public` from an
+owner-scoped invocation. Its policies specify `table`, `wallet_field` and
+`provider_field`; both wallet and provider come from that owner's stored source
+row. Core verifies wallet ownership, receive permission and the user's enabled
+provider allowlist. Requests contain only source, amount, ISO currency and memo.
+The host delegates to `create_payment_request`, preserving existing fiat limits,
+fees, provider handling and settlement. Responses contain only payment hash,
+HTTPS checkout URL, millisatoshi amount and provider name. `list-fiat-providers`
+uses the same permission and lists allowed names for an authenticated user.
+No provider credentials/options, spending permission or new authentication mode
+are introduced. Public routes resolve the source owner through their existing
+`ownerContext` policy; they do not accept a caller-supplied owner.
+
For settlement-driven state changes, verify status/pending state, payment hash,
amount, wallet, source, and the extension's stored invoice binding. Store enough
information before invoice creation to cope with settlement arriving before
### lnbits/core/models/__init__.py
@@ -18,6 +18,7 @@
PaymentCountField,
PaymentCountStat,
PaymentDailyStats,
+ PaymentExtensionContext,
PaymentExtra,
PaymentFilters,
PaymentHistoryPoint,
@@ -81,6 +82,7 @@
"PaymentCountField",
"PaymentCountStat",
"PaymentDailyStats",
+ "PaymentExtensionContext",
"PaymentExtra",
"PaymentFilters",
"PaymentHistoryPoint",
### lnbits/core/models/payments.py
@@ -7,7 +7,7 @@
from fastapi import Query
from lnurl import LnurlWithdrawResponse
from loguru import logger
-from pydantic import BaseModel, Field, field_validator, model_validator
+from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
from lnbits.db import FilterModel
from lnbits.fiat.base import (
@@ -80,6 +80,17 @@ class ValidatedPaymentRequest(BaseModel):
is_offer: bool
+class PaymentExtensionContext(BaseModel):
+ """Trusted extension binding captured by the host when creating an invoice."""
+
+ model_config = ConfigDict(frozen=True)
+
+ extension_id: str = Field(min_length=1)
+ owner_id: str = Field(min_length=1)
+ wallet_id: str = Field(min_length=1)
+ source_id: str | None = None
+
+
class CreatePayment(BaseModel):
wallet_id: str
payment_hash: str
@@ -88,7 +99,7 @@ class CreatePayment(BaseModel):
memo: str
extra: dict | None = {}
extension: str | None = None
- extension_context: dict | None = None
+ extension_context: PaymentExtensionContext | None = None
preimage: str | None = None
expiry: datetime | None = None
webhook: str | None = None
@@ -122,7 +133,7 @@ class Payment(BaseModel):
tag: str | None = None
extension: str | None = None
# Trusted host context, kept separate from externally supplied metadata.
- extension_context: dict | None = None
+ extension_context: PaymentExtensionContext | None = None
time: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
### lnbits/core/services/payments.py
@@ -10,7 +10,7 @@
from lnbits.core.crud.payments import get_daily_stats
from lnbits.core.db import db
from lnbits.core.models import PaymentDailyStats, PaymentFilters
-from lnbits.core.models.payments import CreateInvoice
+from lnbits.core.models.payments import CreateInvoice, PaymentExtensionContext
from lnbits.core.models.wallets import WalletType
from lnbits.db import Connection, Filter, Filters
from lnbits.decorators import check_user_extension_access
@@ -152,7 +152,7 @@ async def create_payment_request(
wallet_id: str,
invoice_data: CreateInvoice,
*,
- extension_context: dict | None = None,
+ extension_context: PaymentExtensionContext | None = None,
) -> Payment:
"""
Create a lightning invoice or a fiat payment request.
@@ -174,7 +174,7 @@ async def create_fiat_invoice(
invoice_data: CreateInvoice,
conn: Connection | None = None,
*,
- extension_context: dict | None = None,
+ extension_context: PaymentExtensionContext | None = None,
) -> Payment:
if invoice_data.amount is None:
raise ValueError("Invoice amount is required.")
@@ -249,7 +249,10 @@ async def create_fiat_invoice(
async def create_wallet_invoice(
- wallet_id: str, data: CreateInvoice, *, extension_context: dict | None = None
+ wallet_id: str,
+ data: CreateInvoice,
+ *,
+ extension_context: PaymentExtensionContext | None = None,
) -> Payment:
if data.amount is None:
raise ValueError("Invoice amount is required.")
@@ -330,7 +333,7 @@ async def create_invoice(
internal: bool | None = False,
payment_hash: str | None = None,
extension: str | None = None,
- extension_context: dict | None = None,
+ extension_context: PaymentExtensionContext | None = None,
labels: list[str] | None = None,
external_id: str | None = None,
conn: Connection | None = None,
### lnbits/core/wasm_ext/api/host.py
@@ -4,10 +4,15 @@
import secrets
import time
from collections.abc import Iterable, Mapping
+from hashlib import sha256
from typing import Any, TypeGuard
+from urllib.parse import urlsplit
+from bolt11 import Bolt11Exception
+from bolt11 import decode as bolt11_decode
from loguru import logger
+from lnbits.core.models.payments import Payment, PaymentExtensionContext
from lnbits.core.models.users import Account, UserNotifications
from lnbits.core.models.wallets import Wallet
from lnbits.helpers import sha256s
@@ -31,13 +36,18 @@
invoice_amount_msat,
)
from .models import (
+ CreateFiatInvoicePublicRequest,
+ CreateFiatInvoiceResponse,
CreateInvoicePublicRequest,
CreateInvoiceRequest,
CreateInvoiceResponse,
EmptyRequest,
ExtensionApiRequest,
HttpRequest,
HttpResponse,
+ InvoiceStatusRequest,
+ InvoiceStatusResponse,
+ ListFiatProvidersResponse,
ListUserWalletsResponse,
LogRequest,
LogResponse,
@@ -47,6 +57,8 @@
PayLnurlRequest,
RandomIdRequest,
RandomIdResponse,
+ RefreshPaymentRequest,
+ RefreshPaymentResponse,
SendUserNotificationRequest,
SendUserNotificationResponse,
StorageAppendPublicRequest,
@@ -392,12 +404,12 @@ async def wallet_create_invoice(
extra=request.extra,
extension=self.extension_id,
),
- extension_context={
- "extension_id": self.extension_id,
- "owner_id": sha256s(wallet.user),
- "wallet_id": wallet.source_wallet_id,
- "source_id": (request.extra or {}).get("source_id") or None,
- },
+ extension_context=PaymentExtensionContext(
+ extension_id=self.extension_id,
+ owner_id=sha256s(wallet.user),
+ wallet_id=wallet.source_wallet_id,
+ source_id=(request.extra or {}).get("source_id") or None,
+ ),
)
return CreateInvoiceResponse(
payment_hash=payment.payment_hash,
@@ -444,7 +456,11 @@ async def wallet_create_invoice_public(
wallet = await get_wallet(wallet_id)
owner_id = row.get(OWNER_ID_FIELD)
- if not wallet or owner_id != sha256s(wallet.user):
+ if (
+ not wallet
+ or not isinstance(owner_id, str)
+ or owner_id != sha256s(wallet.user)
+ ):
raise PermissionError("Public invoice source does not own its wallet.")
payment = await create_payment_request(
@@ -462,19 +478,153 @@ async def wallet_create_invoice_public(
},
extension=self.extension_id,
),
- extension_context={
- "extension_id": self.extension_id,
- "owner_id": owner_id,
- "wallet_id": wallet.source_wallet_id,
- "source_id": request.source_id,
- },
+ extension_context=PaymentExtensionContext(
+ extension_id=self.extension_id,
+ owner_id=owner_id,
+ wallet_id=wallet.source_wallet_id,
+ source_id=request.source_id,
+ ),
)
+ if request.unhashed_description:
+ _validate_invoice_description_hash(
+ payment.payment_request or payment.bolt11,
+ request.unhashed_description,
+ )
return CreateInvoiceResponse(
payment_hash=payment.payment_hash,
payment_request=payment.payment_request or payment.bolt11,
checking_id=payment.checking_id,
)
+ @extension_api_method(
+ method_id="wallet.invoice_status",
+ namespace="wallet",
+ name="Check extension invoice",
+ host_name="invoice_status",
+ sdk_name="invoiceStatus",
+ description="Read stored invoice status for this extension, owner and source.",
+ required_permission="wallet.invoice_status",
+ )
+ async def wallet_invoice_status(
+ self, request: InvoiceStatusRequest
+ ) -> InvoiceStatusResponse:
+ from lnbits.core.crud.payments import get_standalone_payment
+
+ owner_id = self._require_owner_id()
+ payment = await get_standalone_payment(request.payment_hash, incoming=True)
+ if not self._can_read_invoice(payment, request, owner_id):
+ raise PermissionError("Invoice is not available to this extension source.")
+ return InvoiceStatusResponse(
+ paid=payment.success,
+ pending=payment.pending,
+ failed=payment.failed,
+ amount_msat=payment.amount,
+ )
+
+ @extension_api_method(
+ method_id="wallet.list_fiat_providers",
+ namespace="wallet",
+ name="List allowed fiat providers",
+ host_name="list_fiat_providers",
+ sdk_name="listFiatProviders",
+ description="List enabled fiat provider names allowed for the current user.",
+ required_permission="wallet.create_fiat_invoice_public",
+ require_auth=True,
+ )
+ async def wallet_list_fiat_providers(
+ self, request: EmptyRequest
+ ) -> ListFiatProvidersResponse:
+ from lnbits.settings import settings
+
+ if not self.user_id:
+ raise PermissionError("Listing providers requires an authenticated user.")
+ return ListFiatProvidersResponse(
+ providers=settings.get_fiat_providers_for_user(self.user_id)
+ )
+
+ @extension_api_method(
+ method_id="wallet.create_fiat_invoice_public",
+ namespace="wallet",
+ name="Create public fiat checkout",
+ host_name="create_fiat_invoice_public",
+ sdk_name="createFiatInvoicePublic",
+ description="Create a checkout using a stored source's wallet and provider.",
+ required_permission="wallet.create_fiat_invoice_public",
+ )
+ async def wallet_create_fiat_invoice_public(
+ self, request: CreateFiatInvoicePublicRequest
+ ) -> CreateFiatInvoiceResponse:
+ from lnbits.core.crud.wallets import get_wallet
+ from lnbits.core.models.payments import CreateInvoice
+ from lnbits.core.services.payments import create_payment_request
+ from lnbits.settings import settings
+
+ from .permissions import _public_fiat_invoice_sources
+
+ owner_id = self._require_owner_id()
+ policies = _public_fiat_invoice_sources(
+ self.permission_policies.get("wallet.create_fiat_invoice_public")
+ )
+ row = None
+ wallet_id = provider = None
+ for table, wallet_field, provider_field in sorted(policies):
+ row = await storage_get_row(
+ self.extension_id, table, request.source_id, owner_id=owner_id
+ )
+ if row:
+ wallet_id, provider = row.get(wallet_field), row.get(provider_field)
+ break
+ if not row:
+ raise PermissionError("Fiat invoice source was not found.")
+ if not isinstance(wallet_id, str) or not wallet_id:
+ raise PermissionError("Fiat invoice source has no valid wallet.")
+ wallet = await get_wallet(wallet_id)
+ if (
+ not wallet
+ or sha256s(wallet.user) != owner_id
+ or not wallet.can_receive_payments
+ or not isinstance(provider, str)
+ or provider not in settings.get_fiat_providers_for_user(wallet.user)
+ ):
+ raise PermissionError("Fiat invoice wallet or provider is not available.")
+ payment = await create_payment_request(
+ wallet.id,
+ CreateInvoice(
+ amount=request.amount,
+ unit=request.currency,
+ memo=request.memo,
+ fiat_provider=provider,
+ extension=self.extension_id,
+ extra={"tag": self.extension_id, "source_id": request.source_id},
+ ),
+ extension_context=PaymentExtensionContext(
+ extension_id=self.extension_id,
+ owner_id=owner_id,
+ wallet_id=wallet.source_wallet_id,
+ source_id=request.source_id,
+ ),
+ )
+ checkout = payment.extra.get("fiat_payment_request")
+ if not isinstance(checkout, str):
+ raise ValueError("Fiat provider returned no checkout URL.")
+ url = urlsplit(checkout)
+ if (
+ len(checkout) > 4096
+ or any(ord(char) < 33 or ord(char) == 127 for char in checkout)
+ or "\\" in checkout
+ or url.scheme != "https"
+ or not url.hostname
+ or url.username is not None
+ or url.password is not None
+ ):
+ raise ValueError("Fiat provider returned an invalid checkout URL.")
+ return CreateFiatInvoiceResponse(
+ payment_hash=payment.payment_hash,
+ payment_request=checkout,
+ amount_msat=payment.amount,
+ fiat_provider=provider,
+ )
+
@extension_api_method(
method_id="wallet.list_user_wallets",
namespace="wallet",
@@ -544,6 +694,54 @@ async def wallet_balance(
can_send_payments=wallet.can_send_payments,
)
+ @extension_api_method(
+ method_id="wallet.refresh_payment",
+ namespace="wallet",
+ name="Refresh payment",
+ host_name="refresh_payment",
+ sdk_name="refreshPayment",
+ description=(
+ "Refresh a pending payment in the user's wallet and persist its status. "
+ "This can trigger settlement processing and notifications."
+ ),
+ required_permission="wallet.payments.refresh",
+ require_auth=True,
+ )
+ async def wallet_refresh_payment(
+ self, request: RefreshPaymentRequest
+ ) -> RefreshPaymentResponse:
+ from lnbits.core.crud.payments import get_standalone_payment
+ from lnbits.core.crud.wallets import get_wallet
+ from lnbits.core.services.payments import update_pending_payment
+
+ if not self.user_id:
+ raise PermissionError(
+ "Refreshing a payment requires an authenticated user context."
+ )
+
+ wallet = await get_wallet(request.wallet_id)
+ if wallet is None or wallet.user != self.user_id:
+ raise PermissionError("Refreshing payments in this wallet is not allowed.")
+
+ payment = await get_standalone_payment(request.checking_id, wallet_id=wallet.id)
+ if payment is None:
+ raise ValueError("Payment was not found in this wallet.")
+ if payment.pending:
+ try:
+ payment = await update_pending_payment(payment)
+ except Exception as exc:
+ raise RuntimeError("Unable to refresh payment status.") from exc
+
+ return RefreshPaymentResponse(
+ checking_id=payment.checking_id,
+ payment_hash=payment.payment_hash,
+ status=payment.status,
+ amount_msat=abs(payment.amount),
+ fee_msat=abs(payment.fee),
+ pending=payment.pending,
+ success=payment.success,
+ )
+
@extension_api_method(
method_id="wallet.pay_invoice",
namespace="wallet",
@@ -1081,6 +1279,26 @@ def _can_pay_from_wallet(self, wallet: Wallet | None) -> TypeGuard[Wallet]:
bool(self.user_id) and wallet.user == self.user_id
)
+ def _can_read_invoice(
+ self,
+ payment: Payment | None,
+ request: InvoiceStatusRequest,
+ owner_id: str,
+ ) -> TypeGuard[Payment]:
+ if payment is None or not payment.is_in:
+ return False
+
+ binding = payment.extension_context
+ return (
+ payment.payment_hash == request.payment_hash
+ and payment.extension == self.extension_id
+ and isinstance(binding, PaymentExtensionContext)
+ and binding.extension_id == self.extension_id
+ and binding.owner_id == owner_id
+ and binding.wallet_id == payment.wallet_id
+ and binding.source_id == request.source_id
+ )
+
def _pay_invoice_response(payment: Any) -> PayInvoiceResponse:
return PayInvoiceResponse(
@@ -1110,3 +1328,15 @@ def _user_notification_preferences(
preferences.telegram_chat_id if notification_type == "telegram" else None
),
)
+
+
+def _validate_invoice_description_hash(
+ payment_request: str, unhashed_description: str
+) -> None:
+ try:
+ invoice = bolt11_decode(payment_request)
+ except (Bolt11Exception, ValueError) as exc:
+ raise ValueError("Funding backend returned an invalid invoice.") from exc
+ expected_hash = sha256(bytes.fromhex(unhashed_description)).hexdigest()
+ if invoice.description_hash != expected_hash:
+ raise ValueError("Funding backend returned an incorrect description hash.")
### lnbits/core/wasm_ext/api/models.py
@@ -111,7 +111,7 @@ class StoragePaginatedRequest(BaseModel):
search_fields: list[str] = Field(default_factory=list)
sort_by: str | None = Field(None, min_length=1, max_length=128)
descending: bool = False
- limit: int = Field(25, ge=1, le=1000)
+ limit: int = Field(25, ge=0, le=1000)
offset: int = Field(0, ge=0)
@model_validator(mode="before")
@@ -255,6 +255,36 @@ class CreateInvoiceResponse(BaseModel):
checking_id: str
+class InvoiceStatusRequest(BaseModel):
+ payment_hash: str = Field(..., pattern=r"^[0-9a-f]{64}$")
+ source_id: str = Field(..., min_length=1, max_length=512)
+
+
+class InvoiceStatusResponse(BaseModel):
+ paid: bool
+ pending: bool
+ failed: bool
+ amount_msat: int
+
+
+class CreateFiatInvoicePublicRequest(BaseModel):
+ source_id: str = Field(..., min_length=1, max_length=512)
+ amount: float = Field(..., gt=0, allow_inf_nan=False)
+ currency: str = Field(..., pattern=r"^[A-Z]{3}$")
+ memo: str = Field(default="", max_length=512)
+
+
+class CreateFiatInvoiceResponse(BaseModel):
+ payment_hash: str
+ payment_request: str
+ amount_msat: int
+ fiat_provider: str
+
+
+class ListFiatProvidersResponse(BaseModel):
+ providers: list[str]
+
+
class UserWalletSummary(BaseModel):
id: str
name: str
@@ -282,6 +312,23 @@ class WalletBalanceResponse(BaseModel):
can_send_payments: bool
+class RefreshPaymentRequest(BaseModel):
+ wallet_id: str = Field(..., min_length=1, max_length=128)
+ checking_id: str = Field(..., min_length=1, max_length=512)
+
+ model_config = ConfigDict(extra="forbid")
+
+
+class RefreshPaymentResponse(BaseModel):
+ checking_id: str
+ payment_hash: str
+ status: str
+ amount_msat: int
+ fee_msat: int
+ pending: bool
+ success: bool
+
+
class PayInvoiceRequest(BaseModel):
wallet_id: str = Field(..., min_length=1, max_length=128)
payment_request: str = Field(..., min_length=1, max_length=8192)
### lnbits/core/wasm_ext/api/permissions.py
@@ -21,6 +21,7 @@
"scheduler.user",
"scheduler.extension",
"wallet.create_invoice_public",
+ "wallet.create_fiat_invoice_public",
"websocket.publish",
}
_OWNER_ID_FIELD = "__lnbits_owner_id__"
@@ -170,6 +171,10 @@ def _permission_grant_is_subset(
user_scope=requested.id == "scheduler.user",
allow_job_limit_override=allow_admin_policy_overrides,
)
+ if requested.id == "wallet.create_fiat_invoice_public":
+ return _public_fiat_invoice_sources(granted.policies).issubset(
+ _public_fiat_invoice_sources(requested.policies)
+ )
checker = {
"http.request": _http_request_grant_is_subset,
"extension.api.request": _extension_api_grant_is_subset,
@@ -185,6 +190,8 @@ def _validate_requested_permission_policies(
event_handlers: set[str],
) -> None:
for permission in permissions:
+ if permission.id == "wallet.create_fiat_invoice_public":
+ _public_fiat_invoice_sources(permission.policies)
if permission.id in {"scheduler.user", "scheduler.extension"}:
try:
policies = SchedulePolicy.parse_policies(
@@ -483,3 +490,25 @@ def _schedule_grant_is_subset(
):
return False
return True
+
+
+def _public_fiat_invoice_sources(
+ policies: list[Any] | None,
+) -> set[tuple[str, str, str]]:
+ if not isinstance(policies, list) or not policies:
+ raise ValueError("Public fiat invoices require source policies.")
+ sources = set()
+ for policy in policies:
+ if not isinstance(policy, dict) or set(policy) != {
+ "table",
+ "wallet_field",
+ "provider_field",
+ }:
+ raise ValueError("Invalid public fiat invoice source policy.")
+ fields = tuple(
+ policy[key] for key in ("table", "wallet_field", "provider_field")
+ )
+ if not all(isinstance(value, str) and value for value in fields):
+ raise ValueError("Invalid public fiat invoice source fields.")
+ sources.add(fields)
+ return sources
### lnbits/core/wasm_ext/api/registry.py
@@ -14,6 +14,7 @@
"scheduler.user",
"scheduler.extension",
"ui.camera.scan_qr",
+ "ui.storage.local",
"wallet.pay_invoice",
"wallet.pay_invoice_background",
"wallet.payments.watch",
### lnbits/core/wasm_ext/wasm/events.py
@@ -7,6 +7,7 @@
from lnbits.core.crud.wallets import get_wallet
from lnbits.core.db import core_app_extra
from lnbits.core.models.extensions import ExtensionWalletPaymentsWatchGrant
+from lnbits.core.models.payments import PaymentExtensionContext
from lnbits.core.wasm_ext.wasm.invoke import invoke_wasm_extension_export
from lnbits.helpers import sha256s
@@ -170,15 +171,14 @@ async def _wasm_invoice_paid_owner_id(extension: Any, payment: Any) -> str | Non
# This column is written with the invoice by the host, not from extra.
# Do not consult mutable source rows for invoices with a trusted binding.
if (
- not isinstance(context, dict)
- or context.get("extension_id") != extension.id
+ not isinstance(context, PaymentExtensionContext)
+ or context.extension_id != extension.id
or payment.extension != extension.id
- or context.get("wallet_id") != payment.wallet_id
- or context.get("source_id") != source_id
+ or context.wallet_id != payment.wallet_id
+ or context.source_id != source_id
):
return None
- owner_id = context.get("owner_id")
- return owner_id if isinstance(owner_id, str) and owner_id else None
+ return context.owner_id
# Public invoice metadata cannot authenticate an extension event.
return None
### lnbits/static/bundle-components.min.js
[binary or diff unavailable]
### lnbits/static/js/wasm-extension-component.js
@@ -190,6 +190,8 @@ window.WasmExtensionComponent = {
routeParams: {}
},
bridgePort: null,
+ themeObserver: null,
+ lastTheme: '',
cameraPrompt: {
extensionName: '',
reject: null,
@@ -248,7 +250,17 @@ window.WasmExtensionComponent = {
this.handleWindowMessage = event => this.onWindowMessage(event)
window.addEventListener('message', this.handleWindowMessage)
},
+ mounted() {
+ this.themeObserver = new MutationObserver(() => this.publishTheme())
+ for (const element of [document.documentElement, document.body]) {
+ this.themeObserver.observe(element, {
+ attributes: true,
+ attributeFilter: ['class', 'style', 'data-theme']
+ })
+ }
+ },
unmounted() {
+ this.themeObserver?.disconnect()
window.removeEventListener('message', this.handleWindowMessage)
this.rejectCameraPrompt('Camera scan cancelled.')
this.rejectBackgroundPaymentPrompt(
@@ -279,10 +291,44 @@ window.WasmExtensionComponent = {
routeParams: {}
}
},
+ currentTheme() {
+ const style = window.getComputedStyle(document.body)
+ const colors = {}
+ for (const name of [
+ 'primary',
+ 'secondary',
+ 'accent',
+ 'positive',
+ 'negative',
+ 'info',
+ 'warning',
+ 'dark',
+ 'dark-page'
+ ]) {
+ const value = style.getPropertyValue(`--q-${name}`).trim()
+ if (value.length <= 128 && CSS.supports('color', value))
+ colors[name] = value
+ }
+ return {
+ dark: Boolean(this.$q.dark.isActive),
+ name: String(document.body.dataset.theme || ''),
+ gradient: document.body.classList.contains('gradient-bg'),
+ colors
+ }
+ },
+ publishTheme() {
+ if (!this.bridgePort) return
+ const theme = this.currentTheme()
+ const signature = JSON.stringify(theme)
+ if (signature === this.lastTheme) return
+ this.lastTheme = signature
+ this.sendBridgeEvent({event: 'ui.theme', data: theme})
+ },
plainBridgeContext() {
return {
extensionId: String(this.bridge.extensionId || ''),
public: Boolean(this.bridge.public),
+ theme: this.currentTheme(),
routeParams: this.plainValue(this.bridge.routeParams || {}),
query: this.plainValue(this.bridge.query || {})
}
@@ -558,6 +604,88 @@ window.WasmExtensionComponent = {
window.sessionStorage.setItem(key, value)
return {ok: true}
},
+ async localBridgeStorage(message) {
+ if (!this.hasBridgePermission('ui.storage.local')) {
+ throw new Error('Persistent extension storage is not permitted.')
+ }
+ const key = message.key
+ if (typeof key !== 'string' || !/^[A-Za-z0-9._:-]{1,128}$/.test(key)) {
+ throw new Error('Invalid extension storage key.')
+ }
+ const scope = () =>
+ JSON.stringify([
+ this.bridge.extensionId,
+ this.g?.user?.id || null,
+ this.$route.path
+ ])
+ const initialScope = scope()
+ const namespace = JSON.stringify([
+ this.bridge.extensionId,
+ this.g?.user?.id || null
+ ])
+ const digest = await window.crypto.subtle.digest(
+ 'SHA-256',
+ new TextEncoder().encode(namespace)
+ )
+ if (
+ scope() !== initialScope ||
+ !this.hasBridgePermission('ui.storage.local')
+ ) {
+ throw new Error('Extension storage context changed.')
+ }
+ const storageKey =
+ 'lnbits.ext.local.' +
+ this.bridge.extensionId +
+ '.' +
+ Array.from(new Uint8Array(digest), b =>
+ b.toString(16).padStart(2, '0')
+ ).join('')
+ const entryKey = JSON.stringify([this.$route.path, key])
+ const now = Date.now()
+ const ttl = 180 * 24 * 60 * 60 * 1000
+ const bytes = value => new TextEncoder().encode(value).length
+ const entries = Object.create(null)
+ const raw = window.localStorage.getItem(storageKey)
+ if (raw && raw.length <= 65536) {
+ try {
+ const stored = JSON.parse(raw)
+ if (stored && typeof stored === 'object' && !Array.isArray(stored)) {
+ for (const [name, record] of Object.entries(stored).slice(0, 128)) {
+ if (
+ record &&
+ typeof record.value === 'string' &&
+ bytes(record.value) <= 1024 &&
+ Number.isSafeInteger(record.expires) &&
+ record.expires > now &&
+ record.expires <= now + ttl
+ ) {
+ entries[name] = record
+ }
+ }
+ }
+ } catch (_) {
+ /* Discard malformed optional browser state. */
+ }
+ }
+ if (message.action === 'storage.local.set') {
+ if (typeof message.value !== 'string' || bytes(message.value) > 1024) {
+ throw new Error('Extension storage value is too large or invalid.')
+ }
+ entries[entryKey] = {value: message.value, expires: now + ttl}
+ } else if (message.action === 'storage.local.remove') {
+ delete entries[entryKey]
+ }
+ const encoded = JSON.stringify(entries)
+ if (Object.keys(entries).length > 128 || bytes(encoded) > 65536) {
+ throw new Error('Extension storage quota exceeded.')
+ }
+ if (Object.keys(entries).length)
+ window.localStorage.setItem(storageKey, encoded)
+ else window.localStorage.removeItem(storageKey)
+ return message.action === 'storage.local.get'
+ ? {value: entries[entryKey]?.value || ''}
+ : {ok: true}
+ },
async callApi(message) {
const method = String(message.method || 'GET').toUpperCase()
const path = String(message.path || '')
@@ -1248,6 +1376,147 @@ window.WasmExtensionComponent = {
: JSON.stringify(message.data ?? {})
subscription.socket.send(data)
},
+ exportTable(message) {
+ const {columns, rows} = message
+ if (
+ !Array.isArray(columns) ||
+ columns.length < 1 ||
+ columns.length > 50 ||
+ !columns.every(
+ value => typeof value === 'string' && value.length <= 200
+ ) ||
+ !Array.isArray(rows) ||
+ rows.length > 10000 ||
+ !rows.every(
+ row =>
+ Array.isArray(row) &&
+ row.length === columns.length &&
+ row.every(value =>
+ ['string', 'number', 'boolean'].includes(typeof value)
+ )
+ )
+ )
+ throw new Error('Invalid export table.')
+ const table = {columns, rows: rows.map(row => row.map(String))}
+ if (new TextEncoder().encode(JSON.stringify(table)).length > 1048576) {
+ throw new Error('Export must not exceed 1 MiB.')
+ }
+ return table
+ },
+ csvDocument(message) {
+ const filename = message.filename
+ if (
+ typeof filename !== 'string' ||
+ !/^[A-Za-z0-9][A-Za-z0-9._-]{0,100}\.csv$/.test(filename)
+ ) {
+ throw new Error('Invalid CSV filename.')
+ }
+ const table = this.exportTable(message)
+ const cell = value => {
+ let text = String(value)
+ // Spreadsheet formula injection also applies after leading whitespace.
+ if (/^[\s\u0000-\u001f]*[=+@-]/.test(text) || /^[\t\r\n]/.test(text))
+ text = "'" + text
+ return '"' + text.replaceAll('"', '""') + '"'
+ }
+ return {
+ filename,
+ text: [table.columns, ...table.rows]
+ .map(row => row.map(cell).join(','))
+ .join('\r\n')
+ }
+ },
+ printDocument(message) {
+ const table = this.exportTable(message)
+ if (
+ typeof message.title !== 'string' ||
+ message.title.length > 200 ||
+ !Array.isArray(message.lines) ||
+ message.lines.length > 50 ||
+ !message.lines.every(
+ line => typeof line === 'string' && line.length <= 2000
+ )
+ ) {
+ throw new Error('Invalid print document.')
+ }
+ return {...table, title: message.title, lines: message.lines}
+ },
+ async confirmDocumentAction(label) {
+ if (this.documentActionPending)
+ throw new Error('An export prompt is already open.')
+ this.documentActionPending = true
+ try {
+ return await new Promise(resolve => {
+ window.Quasar.Dialog.create({
+ title: label,
+ message: `${this.bridge.extensionId} requests this action.`,
+ cancel: true,
+ persistent: true
+ })
+ .onOk(() => resolve(true))
+ .onCancel(() => resolve(false))
+ })
+ } finally {
+ this.documentActionPending = false
+ }
+ },
+ async downloadCsv(message) {
+ const data = this.csvDocument(message)
+ if (!(await this.confirmDocumentAction('Download CSV?')))
+ return {cancelled: true}
+ const url = URL.createObjectURL(
+ new Blob([data.text], {type: 'text/csv;charset=utf-8'})
+ )
+ const link = document.createElement('a')
+ link.href = url
+ link.download = data.filename
+ document.body.appendChild(link)
+ try {
+ link.click()
+ } finally {
+ link.remove()
+ window.setTimeout(() => URL.revokeObjectURL(url), 1000)
+ }
+ return {ok: true}
+ },
+ async printExtensionDocument(message) {
+ const data = this.printDocument(message)
+ if (!(await this.confirmDocumentAction('Print invoice?')))
+ return {cancelled: true}
+ const frame = document.createElement('iframe')
+ // No extension HTML, scripts, URLs, or styles are accepted for printing.
+ frame.setAttribute('sandbox', 'allow-same-origin allow-modals')
+ frame.setAttribute('title', 'Invoice print preview')
+ frame.style.position = 'fixed'
+ frame.style.width = '1px'
+ frame.style.height = '1px'
+ frame.style.opacity = '0'
+ document.body.appendChild(frame)
+ try {
+ const doc = frame.contentDocument
+ doc.title = data.title
+ const add = (tag, text, parent = doc.body) => {
+ const element = doc.createElement(tag)
+ element.textContent = text
+ parent.appendChild(element)
+ return element
+ }
+ add('h1', data.title)
+ data.lines.forEach(line => add('p', line))
+ const table = add('table', '')
+ const header = add('tr', '', table)
+ data.columns.forEach(value => add('th', value, header))
+ data.rows.forEach(row => {
+ const tr = add('tr', '', table)
+ row.forEach(value => add('td', value, tr))
+ })
+ frame.contentWindow.focus()
+ frame.contentWindow.print()
+ } finally {
+ window.setTimeout(() => frame.remove(), 1000)
+ }
+ return {ok: true}
+ },
async handleBridgeRequest(message, reply) {
if (!message || message.type !== 'lnbits-extension:request') return
@@ -1268,6 +1537,18 @@ window.WasmExtensionComponent = {
return
}
+ if (
+ message.action === 'ui.download_csv' ||
+ message.action === 'ui.print_document'
+ ) {
+ const data =
+ message.action === 'ui.download_csv'
+ ? await this.downloadCsv(message)
+ : await this.printExtensionDocument(message)
+ this.sendResponse(reply, message.id, {ok: true, data})
+ return
+ }
+
if (message.action === 'ui.notify') {
this.notify(message)
this.sendResponse(reply, message.id, {
@@ -1294,6 +1575,20 @@ window.WasmExtensionComponent = {
return
}
+ if (
+ [
+ 'storage.local.get',
+ 'storage.local.set',
+ 'storage.local.remove'
+ ].includes(message.action)
+ ) {
+ this.sendResponse(reply, message.id, {
+ ok: true,
+ data: await this.localBridgeStorage(message)
+ })
+ return
+ }
+
if (message.action === 'storage.session.get') {
this.sendResponse(reply, message.id, {
ok: true,
@@ -1405,6 +1700,7 @@ window.WasmExtensionComponent = {
this.closeBridgePort()
this.bridgePort = port
+ this.lastTheme = ''
this.bridgePort.addEventListener('message', portEvent => {
this.handleBridgeRequest(portEvent.data, response => {
port.postMessage(response)
### tests/unit/test_models_payments.py
@@ -1,7 +1,15 @@
+import json
+
import pytest
from pydantic import ValidationError
-from lnbits.core.models import CreateInvoice
+from lnbits.core.models import (
+ CreateInvoice,
+ CreatePayment,
+ Payment,
+ PaymentExtensionContext,
+)
+from lnbits.db import POSTGRES, SQLITE, dict_to_model, model_to_dict
@pytest.mark.parametrize("payment_request", ["lnbc1invoice", "lno1offer"])
@@ -37,3 +45,86 @@ def test_create_invoice_receiving_does_not_require_payment_request():
invoice = CreateInvoice(out=False, amount=21)
assert invoice.payment_request is None
+
+
+@pytest.mark.parametrize("db_type", [SQLITE, POSTGRES])
+@pytest.mark.parametrize("source_id", [None, "row-1"])
+def test_payment_extension_context_preserves_database_and_api_json(
+ monkeypatch, db_type, source_id
+):
+ monkeypatch.setattr("lnbits.db.DB_TYPE", db_type)
+ context = {**_extension_context(), "source_id": source_id}
+ payment = Payment.model_validate({**_payment_data(), "extension_context": context})
+ assert isinstance(payment.extension_context, PaymentExtensionContext)
+ row = model_to_dict(payment)
+ assert json.loads(row["extension_context"]) == context
+
+ restored = dict_to_model(row, Payment)
+ assert restored.extension_context == payment.extension_context
+ assert json.loads(restored.model_dump_json())["extension_context"] == context
+
+
+@pytest.mark.parametrize("stored_context", [None, "null"])
+def test_payment_reads_legacy_null_extension_context(stored_context):
+ row = {**_payment_data(), "extension_context": stored_context}
+ assert dict_to_model(row, Payment).extension_context is None
+
+
+def test_payment_reads_extension_context_without_optional_source():
+ context = _extension_context()
+ row = {**_payment_data(), "extension_context": json.dumps(context)}
+ payment = dict_to_model(row, Payment)
+ assert payment.extension_context == PaymentExtensionContext(**context)
+ assert payment.extension_context is not None
+ assert payment.extension_context.source_id is None
+
+
+@pytest.mark.parametrize("field", ["extension_id", "owner_id", "wallet_id"])
+@pytest.mark.parametrize("invalid", ["missing", "empty", "null", "wrong_type"])
+def test_payment_rejects_invalid_extension_context_on_creation_and_load(field, invalid):
+ context = _extension_context()
+ if invalid == "missing":
+ context.pop(field)
+ else:
+ context[field] = {"empty": "", "null": None, "wrong_type": 123}[invalid]
+
+ with pytest.raises(ValidationError):
+ CreatePayment.model_validate(
+ {
+ "wallet_id": "wallet-1",
+ "payment_hash": "a" * 64,
+ "bolt11": "invoice",
+ "amount_msat": 21000,
+ "memo": "Tip",
+ "extension_context": context,
+ }
+ )
+ with pytest.raises(ValidationError):
+ dict_to_model(
+ {**_payment_data(), "extension_context": json.dumps(context)}, Payment
+ )
+
+
+@pytest.mark.parametrize(
+ "field", ["extension_id", "owner_id", "wallet_id", "source_id"]
+)
+def test_payment_extension_context_is_frozen(field):
+ context = PaymentExtensionContext(**_extension_context())
+ with pytest.raises(ValidationError, match="frozen"):
+ setattr(context, field, "different")
+
+
+def _extension_context():
+ return {"extension_id": "tips", "owner_id": "owner", "wallet_id": "wallet-1"}
+
+
+def _payment_data():
+ return {
+ "checking_id": "checking-id",
+ "payment_hash": "a" * 64,
+ "wallet_id": "wallet-1",
+ "amount": 21000,
+ "fee": 0,
+ "bolt11": "invoice",
+ "extension": "tips",
+ }
### tests/unit/test_wasm_extension_events.py
@@ -7,6 +7,7 @@
from lnbits.core.db import core_app_extra
from lnbits.core.models.extensions import ExtensionPermission
+from lnbits.core.models.payments import PaymentExtensionContext
from lnbits.core.wasm_ext.wasm.config import parse_wasm_extension_config
from lnbits.core.wasm_ext.wasm.events import (
_payment_extension_id,
@@ -48,12 +49,12 @@ async def test_dispatch_wasm_invoice_paid_invokes_registered_event_export_with_o
mocker.AsyncMock(return_value=[]),
)
payment = _payment(ext_id)
- payment.extension_context = {
- "extension_id": ext_id,
- "owner_id": sha256s("user-1"),
- "wallet_id": payment.wallet_id,
- "source_id": "row-1",
- }
+ payment.extension_context = PaymentExtensionContext(
+ extension_id=ext_id,
+ owner_id=sha256s("user-1"),
+ wallet_id=payment.wallet_id,
+ source_id="row-1",
+ )
try:
await dispatch_wasm_invoice_paid(payment)
@@ -212,12 +213,11 @@ async def test_dispatch_wasm_invoice_paid_dedupes_tagged_wallet_watch_grant(
try:
payment = _payment(ext_id, extra={})
- payment.extension_context = {
- "extension_id": ext_id,
- "owner_id": sha256s("user-1"),
- "wallet_id": payment.wallet_id,
- "source_id": None,
- }
+ payment.extension_context = PaymentExtensionContext(
+ extension_id=ext_id,
+ owner_id=sha256s("user-1"),
+ wallet_id=payment.wallet_id,
+ )
await dispatch_wasm_invoice_paid(payment)
finally:
registry._extensions.pop(ext_id, None)
### tests/unit/test_wasm_extension_frontend.py
@@ -1,4 +1,6 @@
import json
+import shutil
+import subprocess
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
@@ -142,3 +144,23 @@ def test_wasm_admin_frontend_calls_runtime_limit_and_invocation_endpoints():
assert "/api/v1/extension/wasm/invocations/stats?" in runtime
assert "/api/v1/extension/wasm/runtime-limits/extensions" in limits
assert "/api/v1/extension/wasm/runtime-limits/${encodeURIComponent(" in limits
+
+
+def test_wasm_frontend_bridge_validation_and_lifecycle():
+ node = shutil.which("node")
+ assert node is not None, "Node is required for frontend bridge tests."
+ # Execute only fixed repository regression files with the installed Node.
+ result = subprocess.run( # noqa: S603
+ [
+ node,
+ "--test",
+ "tests/unit/wasm-document-bridge.test.cjs",
+ "tests/unit/wasm-theme-bridge.test.cjs",
+ "tests/unit/wasm-local-storage.test.cjs",
+ ],
+ cwd=ROOT,
+ capture_output=True,
+ text=True,
+ timeout=30,
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
### tests/unit/test_wasm_extension_host_api.py
@@ -5,6 +5,7 @@
from pytest_mock.plugin import MockerFixture
from lnbits.core.models.extensions import ExtensionPermission
+from lnbits.core.models.payments import PaymentExtensionContext
from lnbits.core.wasm_ext.api.host import ExtensionHostAPI
from lnbits.core.wasm_ext.api.models import (
CreateInvoicePublicRequest,
@@ -753,12 +754,14 @@ async def test_host_api_public_invoice_uses_granted_source_policy(
}
assert invoice.extension == "demoext"
- assert create_mock.await_args.kwargs["extension_context"] == {
- "extension_id": "demoext",
- "owner_id": "owner-1",
- "wallet_id": "wallet-1",
- "source_id": "tip-1",
- }
+ assert create_mock.await_args.kwargs[
+ "extension_context"
+ ] == PaymentExtensionContext(
+ extension_id="demoext",
+ owner_id="owner-1",
+ wallet_id="wallet-1",
+ source_id="tip-1",
+ )
@pytest.mark.anyio
### tests/unit/test_wasm_extension_payment_refresh.py
@@ -0,0 +1,273 @@
+from pathlib import Path
+from runpy import run_path
+from unittest.mock import AsyncMock
+from uuid import uuid4
+
+import pytest
+from pydantic import ValidationError
+from pytest_mock.plugin import MockerFixture
+
+from lnbits.core.crud import create_payment, create_wallet, get_payment
+from lnbits.core.models import CreatePayment, Payment, PaymentState, Wallet
+from lnbits.core.models.extensions import ExtensionPermission
+from lnbits.core.models.wallets import WalletPermission, WalletType
+from lnbits.core.services import create_user_account
+from lnbits.core.wasm_ext.api.host import ExtensionHostAPI
+from lnbits.core.wasm_ext.api.models import RefreshPaymentRequest
+from lnbits.core.wasm_ext.api.permissions import validate_extension_permissions
+from lnbits.core.wasm_ext.api.registry import get_extension_api_method
+from lnbits.core.wasm_ext.api.runtime import ExtensionAPIHost
+from lnbits.wallets.base import PaymentSuccessStatus
+
+METHOD = "wallet.refresh_payment"
+PERMISSION = "wallet.payments.refresh"
+REQUEST = {"wallet_id": "wallet-1", "checking_id": "check-1"}
+
+
+@pytest.fixture
+def payment() -> Payment:
+ return Payment(
+ checking_id="check-1",
+ payment_hash="a" * 64,
+ wallet_id="wallet-1",
+ amount=-21_000,
+ fee=-1_000,
+ bolt11="test-invoice",
+ preimage="private-preimage",
+ extra={"private": "metadata"},
+ )
+
+
+@pytest.fixture
+def wallet() -> Wallet:
+ return Wallet(
+ id="wallet-1",
+ user="user-1",
+ name="Test wallet",
+ adminkey="admin-key",
+ inkey="invoice-key",
+ )
+
+
+@pytest.fixture
+def refresh_mocks(
+ mocker: MockerFixture, wallet: Wallet, payment: Payment
+) -> tuple[AsyncMock, AsyncMock, AsyncMock]:
+ wallet_lookup = mocker.patch(
+ "lnbits.core.crud.wallets.get_wallet", AsyncMock(return_value=wallet)
+ )
+ payment_lookup = mocker.patch(
+ "lnbits.core.crud.payments.get_standalone_payment",
+ AsyncMock(return_value=payment),
+ )
+ refresh = mocker.patch(
+ "lnbits.core.services.payments.update_pending_payment", AsyncMock()
+ )
+ return wallet_lookup, payment_lookup, refresh
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize(
+ ("context", "user_id", "permissions"),
+ [
+ ("user", None, [PERMISSION]),
+ ("event", None, [PERMISSION]),
+ ("schedule", None, [PERMISSION]),
+ ("user", "user-1", []),
+ ("user", "user-1", ["wallet.balance.read", "wallet.payments.watch"]),
+ ],
+)
+async def test_refresh_requires_user_and_permission(
+ context, user_id, permissions, refresh_mocks
+):
+ api = ExtensionHostAPI(
+ "demo", permissions, user_id=user_id, context=context, owner_id="owner"
+ )
+
+ with pytest.raises(PermissionError):
+ await ExtensionAPIHost(api).invoke(METHOD, REQUEST)
+
+ for mock in refresh_mocks:
+ mock.assert_not_awaited()
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("exists", [True, False])
+async def test_refresh_requires_owned_wallet(exists, wallet, refresh_mocks):
+ wallet_lookup, payment_lookup, refresh = refresh_mocks
+ wallet.user = "other-user"
+ wallet_lookup.return_value = wallet if exists else None
+ api = ExtensionHostAPI("demo", [PERMISSION], user_id="user-1")
+
+ with pytest.raises(PermissionError, match="not allowed"):
+ await ExtensionAPIHost(api).invoke(METHOD, REQUEST)
+
+ payment_lookup.assert_not_awaited()
+ refresh.assert_not_awaited()
+
+
+@pytest.mark.anyio
+async def test_refresh_requires_payment_in_wallet(refresh_mocks):
+ _, payment_lookup, refresh = refresh_mocks
+ payment_lookup.return_value = None
+ api = ExtensionHostAPI("demo", [PERMISSION], user_id="user-1")
+
+ with pytest.raises(ValueError, match="not found in this wallet"):
+ await ExtensionAPIHost(api).invoke(METHOD, REQUEST)
+
+ payment_lookup.assert_awaited_once_with("check-1", wallet_id="wallet-1")
+ refresh.assert_not_awaited()
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("status", list(PaymentState))
+async def test_refresh_returns_reconciled_summary(status, payment, refresh_mocks):
+ _, payment_lookup, refresh = refresh_mocks
+ refresh.return_value = payment.model_copy(update={"status": status, "fee": -21})
+ api = ExtensionHostAPI("demo", [PERMISSION], user_id="user-1")
+
+ response = await ExtensionAPIHost(api).invoke(
+ "refreshPayment", {"walletId": "wallet-1", "checkingId": "check-1"}
+ )
+
+ payment_lookup.assert_awaited_once_with("check-1", wallet_id="wallet-1")
+ refresh.assert_awaited_once_with(payment)
+ assert response == {
+ "checkingId": "check-1",
+ "paymentHash": "a" * 64,
+ "status": status.value,
+ "amountMsat": 21_000,
+ "feeMsat": 21,
+ "pending": status == PaymentState.PENDING,
+ "success": status == PaymentState.SUCCESS,
+ }
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("status", [PaymentState.SUCCESS, PaymentState.FAILED])
+async def test_refresh_skips_completed_payments(status, payment, refresh_mocks):
+ payment.status = status
+ api = ExtensionHostAPI("demo", [PERMISSION], user_id="user-1")
+
+ response = await ExtensionAPIHost(api).invoke(METHOD, REQUEST)
+
+ assert response["status"] == status.value
+ refresh_mocks[2].assert_not_awaited()
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("error_type", [RuntimeError, ValueError])
+async def test_refresh_hides_backend_error_details(error_type, refresh_mocks):
+ refresh_mocks[2].side_effect = error_type("Private backend details")
+ api = ExtensionHostAPI("demo", [PERMISSION], user_id="user-1")
+
+ with pytest.raises(RuntimeError, match="^Unable to refresh payment status\\.$"):
+ await ExtensionAPIHost(api).invoke(METHOD, REQUEST)
+
+
+def test_refresh_does_not_accept_caller_supplied_status():
+ with pytest.raises(ValidationError, match="Extra inputs are not permitted"):
+ RefreshPaymentRequest.model_validate({**REQUEST, "status": "success"})
+
+
+def test_refresh_permission_and_sdk_are_discoverable():
+ method = get_extension_api_method(METHOD)
+ assert method.require_auth is True
+ assert method.required_permission == PERMISSION
+ permission = ExtensionPermission(id=PERMISSION)
+ assert validate_extension_permissions("demo", [permission]) == [permission]
+ codegen = run_path(
+ str(
+ Path(__file__).resolve().parents[2]
+ / "tools/codegen/extension_sdk_typescript.py"
+ )
+ )
+ sdk = codegen["generate_typescript_sdk"](method_ids=[METHOD])
+ assert "refreshPayment(input: RefreshPaymentRequest)" in sdk
+ assert "Promise<RefreshPaymentResponse>" in sdk
+ assert "walletId: string" in sdk
+ assert "checkingId: string" in sdk
+ assert "return host.host.refreshPayment(input)" in sdk
+
+
+@pytest.mark.anyio
+async def test_refresh_persists_status_and_scopes_payment_lookup(
+ app, mocker: MockerFixture
+):
+ user = await create_user_account()
+ wallet = await create_wallet(user_id=user.id, wallet_name="Refresh wallet")
+ other_wallet = await create_wallet(user_id=user.id, wallet_name="Other wallet")
+ payment = await create_payment(
+ uuid4().hex,
+ CreatePayment(
+ wallet_id=wallet.id,
+ payment_hash=uuid4().hex,
+ bolt11="",
+ amount_msat=21_000,
+ memo="Refresh test",
+ ),
+ )
+ backend = mocker.patch(
+ "lnbits.core.services.payments.check_payment_status",
+ AsyncMock(return_value=PaymentSuccessStatus(fee_msat=21)),
+ )
+ api = ExtensionAPIHost(ExtensionHostAPI("demo", [PERMISSION], user_id=user.id))
+
+ with pytest.raises(ValueError, match="not found in this wallet"):
+ await api.invoke(
+ METHOD, {"wallet_id": other_wallet.id, "checking_id": payment.checking_id}
+ )
+ backend.assert_not_awaited()
+ assert (await get_payment(payment.checking_id)).pending
+
+ response = await api.invoke(
+ METHOD, {"wallet_id": wallet.id, "checking_id": payment.checking_id}
+ )
+
+ stored = await get_payment(payment.checking_id)
+ assert stored.success
+ assert stored.fee == 21
+ assert response["status"] == "success"
+ assert response["feeMsat"] == 21
+ backend.assert_awaited_once()
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("can_view", [False, True])
+async def test_refresh_respects_shared_wallet_payment_access(
+ app, mocker: MockerFixture, wallet: Wallet, can_view: bool
+):
+ source_user = await create_user_account()
+ source_wallet = await create_wallet(
+ user_id=source_user.id, wallet_name="Source wallet"
+ )
+ payment = await create_payment(
+ uuid4().hex,
+ CreatePayment(
+ wallet_id=source_wallet.id,
+ payment_hash=uuid4().hex,
+ bolt11="",
+ amount_msat=21_000,
+ memo="Shared refresh test",
+ ),
+ )
+ wallet.wallet_type = WalletType.LIGHTNING_SHARED.value
+ wallet.shared_wallet_id = source_wallet.id
+ wallet.share_permissions = [WalletPermission.VIEW_PAYMENTS] if can_view else []
+ mocker.patch("lnbits.core.crud.wallets.get_wallet", AsyncMock(return_value=wallet))
+ mocker.patch("lnbits.core.crud.payments.get_wallet", AsyncMock(return_value=wallet))
+ refresh = mocker.patch(
+ "lnbits.core.services.payments.update_pending_payment",
+ AsyncMock(return_value=payment),
+ )
+ api = ExtensionAPIHost(ExtensionHostAPI("demo", [PERMISSION], user_id=wallet.user))
+ payload = {"wallet_id": wallet.id, "checking_id": payment.checking_id}
+
+ if can_view:
+ response = await api.invoke(METHOD, payload)
+ assert response["paymentHash"] == payment.payment_hash
+ refresh.assert_awaited_once_with(payment)
+ else:
+ with pytest.raises(ValueError, match="not found in this wallet"):
+ await api.invoke(METHOD, payload)
+ refresh.assert_not_awaited()
### tests/unit/test_wasm_extension_storage.py
@@ -18,6 +18,8 @@
m048_add_wasm_runtime_limits_to_installed_extensions,
)
from lnbits.core.models.extensions import ExtensionPermission, WasmInvocation
+from lnbits.core.wasm_ext.api.host import ExtensionHostAPI
+from lnbits.core.wasm_ext.api.models import StoragePaginatedRequest
from lnbits.core.wasm_ext.storage import crud as storage_crud
from lnbits.core.wasm_ext.storage.crud import (
OWNER_ID_FIELD,
@@ -283,6 +285,37 @@ async def test_wasm_storage_migration_and_owner_scoped_crud(
limit=50,
offset=0,
)
+ for owner, published, expected in [
+ ("owner-1", True, 1),
+ ("owner-2", True, 0),
+ ("owner-1", False, 0),
+ ]:
+ api = ExtensionHostAPI(
+ ext_id, ["ext.storage.read"], context="event", owner_id=owner
+ )
+ count_page = await api.storage_get_paginated(
+ StoragePaginatedRequest(
+ table="notes",
+ filters={"published": published},
+ limit=0,
+ search=None,
+ sort_by=None,
+ offset=0,
+ )
+ )
+ assert count_page.total == expected
+ assert json.loads(count_page.rows_json) == []
+ with pytest.raises(ValueError):
+ StoragePaginatedRequest(
+ table="notes", limit=-1, search=None, sort_by=None, offset=0
+ )
+ without_owner = ExtensionHostAPI(ext_id, ["ext.storage.read"], context="event")
+ with pytest.raises(PermissionError, match="owner context"):
+ await without_owner.storage_get_paginated(
+ StoragePaginatedRequest(
+ table="notes", limit=0, search=None, sort_by=None, offset=0
+ )
+ )
await storage_delete_row(ext_id, "notes", "note-1", "owner-2")
still_owned = await storage_get_row(ext_id, "notes", "note-1", "owner-1")
await storage_delete_row(ext_id, "notes", "note-1", "owner-1")
### tests/unit/test_wasm_invoice_security.py
@@ -1,10 +1,11 @@
from types import SimpleNamespace
import pytest
+from pydantic import ValidationError
from lnbits.core.crud import create_wallet, get_payment, update_payment
from lnbits.core.db import core_app_extra
-from lnbits.core.models import CreateInvoice, PaymentState
+from lnbits.core.models import CreateInvoice, PaymentExtensionContext, PaymentState
from lnbits.core.models.wallets import Wallet, WalletPermission, WalletType
from lnbits.core.services.payments import create_payment_request
from lnbits.core.wasm_ext.api.host import ExtensionHostAPI
@@ -18,13 +19,17 @@
dispatch_wasm_invoice_paid,
)
from lnbits.helpers import sha256s
+from lnbits.wallets.fake import FakeWallet
from tests.unit.test_wasm_extension_events import _payment as _event_payment
from tests.unit.test_wasm_extension_events import _wasm_extension
@pytest.mark.anyio
@pytest.mark.parametrize("shared", [False, True])
-async def test_public_invoice_binds_owner_and_survives_wallet_change(mocker, shared):
+@pytest.mark.parametrize("metadata", [None, "", '[["text/plain","Fortune ⚡"]]'])
+async def test_public_invoice_binds_owner_and_survives_wallet_change(
+ mocker, shared, metadata
+):
wallet = _wallet(shared=shared)
owner = sha256s(wallet.user)
row = {"wallet_id": wallet.id, OWNER_ID_FIELD: owner}
@@ -36,6 +41,11 @@ async def test_public_invoice_binds_owner_and_survives_wallet_change(mocker, sha
"lnbits.core.crud.wallets.get_wallet", mocker.AsyncMock(return_value=wallet)
)
payment = _payment("tips")
+ if metadata:
+ invoice = await FakeWallet().create_invoice(
+ 21, unhashed_description=metadata.encode("utf-8")
+ )
+ payment.payment_request = invoice.payment_request
create = mocker.patch(
"lnbits.core.services.payments.create_payment_request",
mocker.AsyncMock(return_value=payment),
@@ -49,23 +59,26 @@ async def test_public_invoice_binds_owner_and_survives_wallet_change(mocker, sha
}
],
)
+ metadata_hex = metadata.encode("utf-8").hex() if metadata is not None else None
await api.wallet_create_invoice_public(
CreateInvoicePublicRequest(
source_id="row-1",
amount=21,
currency="sat",
memo="Tip",
extra={"owner_id": "victim"},
+ unhashed_description=metadata_hex,
)
)
+ assert create.await_args.args[1].unhashed_description == metadata_hex
payment.extension_context = create.await_args.kwargs["extension_context"]
payment.wallet_id = wallet.source_wallet_id
- assert payment.extension_context == {
- "extension_id": "tips",
- "owner_id": owner,
- "wallet_id": wallet.source_wallet_id,
- "source_id": "row-1",
- }
+ assert payment.extension_context == PaymentExtensionContext(
+ extension_id="tips",
+ owner_id=owner,
+ wallet_id=wallet.source_wallet_id,
+ source_id="row-1",
+ )
# Current records and permissions may change while the invoice is outstanding.
row["wallet_id"] = "replacement-wallet"
source_lookup = mocker.patch(
@@ -83,6 +96,78 @@ async def test_public_invoice_binds_owner_and_survives_wallet_change(mocker, sha
wallet_lookup.assert_not_awaited()
+@pytest.mark.parametrize("metadata", [None, "", "a" * 8192, "⚡" * 2730 + "ab"])
+def test_public_invoice_metadata_accepts_hex_byte_boundary(metadata):
+ metadata_hex = metadata.encode("utf-8").hex() if metadata is not None else None
+ request = CreateInvoicePublicRequest(
+ source_id="row-1",
+ amount=21,
+ currency="sat",
+ memo="",
+ unhashed_description=metadata_hex,
+ )
+ assert request.unhashed_description == metadata_hex
+
+
+@pytest.mark.parametrize("metadata", ["a" * 8193, "⚡" * 2731, "😀" * 2049])
+def test_public_invoice_metadata_rejects_oversize_hex(metadata):
+ with pytest.raises(ValidationError):
+ CreateInvoicePublicRequest(
+ source_id="row-1",
+ amount=21,
+ currency="sat",
+ memo="",
+ unhashed_description=metadata.encode("utf-8").hex(),
+ )
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("backend_metadata", [None, b"different metadata", b"invalid"])
+async def test_public_invoice_rejects_invalid_description_commitment(
+ mocker, backend_metadata
+):
+ wallet = _wallet()
+ mocker.patch(
+ "lnbits.core.wasm_ext.api.host.storage_get_public_row",
+ mocker.AsyncMock(
+ return_value={"wallet_id": wallet.id, OWNER_ID_FIELD: sha256s(wallet.user)}
+ ),
+ )
+ mocker.patch(
+ "lnbits.core.crud.wallets.get_wallet", mocker.AsyncMock(return_value=wallet)
+ )
+ invoice = await FakeWallet().create_invoice(
+ 21, memo="Plain description", unhashed_description=backend_metadata
+ )
+ payment = _payment("tips")
+ payment.payment_request = (
+ "invalid" if backend_metadata == b"invalid" else invoice.payment_request
+ )
+ mocker.patch(
+ "lnbits.core.services.payments.create_payment_request",
+ mocker.AsyncMock(return_value=payment),
+ )
+ api = ExtensionHostAPI(
+ "tips",
+ [
+ {
+ "id": "wallet.create_invoice_public",
+ "policies": [{"table": "jars", "wallet_field": "wallet_id"}],
+ }
+ ],
+ )
+ with pytest.raises(ValueError, match="Funding backend returned"):
+ await api.wallet_create_invoice_public(
+ CreateInvoicePublicRequest(
+ source_id="row-1",
+ amount=21,
+ currency="sat",
+ memo="",
+ unhashed_description='[["text/plain","Fortune ⚡"]]'.encode().hex(),
+ )
+ )
+
+
@pytest.mark.anyio
async def test_public_invoice_rejects_source_using_another_users_wallet(mocker):
mocker.patch(
@@ -142,16 +227,11 @@ async def test_authenticated_shared_wallet_invoice_uses_authenticated_owner(
},
)
)
- assert create.await_args.kwargs["extension_context"]["source_id"] == (
- source_id or None
- )
- assert create.await_args.kwargs["extension_context"]["owner_id"] == sha256s(
- wallet.user
- )
- assert (
- create.await_args.kwargs["extension_context"]["wallet_id"]
- == wallet.source_wallet_id
- )
+ context = create.await_args.kwargs["extension_context"]
+ assert isinstance(context, PaymentExtensionContext)
+ assert context.source_id == (source_id or None)
+ assert context.owner_id == sha256s(wallet.user)
+ assert context.wallet_id == wallet.source_wallet_id
@pytest.mark.anyio
@@ -199,20 +279,21 @@ async def test_unbound_invoices_reject_even_authorised_current_sources(mocker, s
("extension_id", "other"),
("wallet_id", "other"),
("source_id", "other"),
- ("owner_id", ""),
],
)
async def test_invalid_binding_fails_closed_without_legacy_fallback(
mocker, field, value
):
payment = _payment("tips")
- payment.extension_context = {
- "extension_id": "tips",
- "wallet_id": "wallet-1",
- "source_id": "row-1",
- "owner_id": "owner",
- }
- payment.extension_context[field] = value
+ payment.extension_context = PaymentExtensionContext(
+ **{
+ "extension_id": "tips",
+ "wallet_id": "wallet-1",
+ "source_id": "row-1",
+ "owner_id": "owner",
+ field: value,
+ }
+ )
lookup = mocker.patch(
"lnbits.core.wasm_ext.storage.crud.storage_get_public_row", mocker.AsyncMock()
)
@@ -222,6 +303,16 @@ async def test_invalid_binding_fails_closed_without_legacy_fallback(
lookup.assert_not_awaited()
+@pytest.mark.anyio
+@pytest.mark.parametrize("context", [None, {}, {"owner_id": ""}, "invalid", []])
+async def test_untyped_invoice_context_cannot_authorize_an_event(context):
+ payment = _payment("tips")
+ payment.extension_context = context
+ assert (
+ await _wasm_invoice_paid_owner_id(SimpleNamespace(id="tips"), payment) is None
+ )
+
+
@pytest.mark.anyio
@pytest.mark.parametrize("tag_field", ["extension", "extra", "tag"])
@pytest.mark.parametrize("source_id", [None, "row-1"])
@@ -308,12 +399,12 @@ async def test_trusted_context_persists_with_invoice_and_survives_updates(
app, from_user
):
wallet = await create_wallet(user_id=from_user.id)
- context = {
- "extension_id": "tips",
- "owner_id": sha256s(wallet.user),
- "wallet_id": wallet.id,
- "source_id": "row-1",
- }
+ context = PaymentExtensionContext(
+ extension_id="tips",
+ owner_id=sha256s(wallet.user),
+ wallet_id=wallet.id,
+ source_id="row-1",
+ )
payment = await create_payment_request(
wallet.id,
CreateInvoice(amount=1, extension="tips", extra={"source_id": "row-1"}),
@@ -328,11 +419,12 @@ async def test_trusted_context_persists_with_invoice_and_survives_updates(
assert reloaded.extension_context == context
assert (
await _wasm_invoice_paid_owner_id(SimpleNamespace(id="tips"), reloaded)
- == context["owner_id"]
+ == context.owner_id
)
# Ordinary invoices may carry arbitrary metadata but cannot create a binding.
ordinary = await create_payment_request(
- wallet.id, CreateInvoice(amount=1, extra={"extension_context": context})
+ wallet.id,
+ CreateInvoice(amount=1, extra={"extension_context": context.model_dump()}),
)
assert (await get_payment(ordinary.checking_id)).extension_context is None
### tests/unit/test_wasm_payment_checkout.py
@@ -0,0 +1,281 @@
+from unittest.mock import AsyncMock
+
+import pytest
+from pydantic import ValidationError
+
+from lnbits.core.models.extensions import ExtensionPermission
+from lnbits.core.models.payments import Payment, PaymentExtensionContext, PaymentState
+from lnbits.core.models.wallets import WalletPermission
+from lnbits.core.wasm_ext.api.host import ExtensionHostAPI
+from lnbits.core.wasm_ext.api.models import (
+ CreateFiatInvoicePublicRequest,
+ EmptyRequest,
+ InvoiceStatusRequest,
+)
+from lnbits.core.wasm_ext.api.permissions import validate_wasm_extension_permissions
+from lnbits.helpers import sha256s
+from tests.helpers import make_installable_extension
+from tests.unit.test_wasm_extension_permissions import _wasm_config
+from tests.unit.test_wasm_invoice_security import _wallet
+
+STATUS_PERMISSION = "wallet.invoice_status"
+FIAT_PERMISSION = "wallet.create_fiat_invoice_public"
+POLICY = {"table": "attempts", "wallet_field": "wallet", "provider_field": "provider"}
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("state", ["pending", "success", "failed"])
+async def test_status_only_returns_bound_invoice_state(mocker, state):
+ payment = _payment(state)
+ lookup = mocker.patch(
+ "lnbits.core.crud.payments.get_standalone_payment",
+ AsyncMock(return_value=payment),
+ )
+ reconciled = payment.model_copy(update={"status": PaymentState.SUCCESS})
+ update = mocker.patch(
+ "lnbits.core.services.payments.update_pending_payment",
+ AsyncMock(return_value=reconciled),
+ )
+ api = ExtensionHostAPI("paywallwasm", [STATUS_PERMISSION], user_id="source-owner")
+ result = await api.wallet_invoice_status(_status_request())
+ lookup.assert_awaited_once_with("a" * 64, incoming=True)
+ update.assert_not_awaited()
+ assert result.model_dump() == {
+ "paid": state == "success",
+ "pending": state == "pending",
+ "failed": state == "failed",
+ "amount_msat": 21000,
+ }
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize(
+ "invalid",
+ [
+ "missing",
+ "legacy",
+ "untyped_binding",
+ "unbound_source",
+ "owner",
+ "source",
+ "wallet",
+ "extension",
+ "binding_extension",
+ "hash",
+ "outgoing",
+ "forged_extra",
+ "no_owner",
+ "no_permission",
+ "anonymous",
+ ],
+)
+async def test_status_denies_unrelated_payments_before_backend_lookup(mocker, invalid):
+ payment = _payment()
+ if invalid == "legacy":
+ payment.extension_context = None
+ elif invalid == "forged_extra":
+ payment.extra = {"source_id": "attempt", "owner_id": sha256s("source-owner")}
+ payment.extension_context = None
+ elif invalid in {"owner", "source", "wallet", "binding_extension"}:
+ field = "extension" if invalid == "binding_extension" else invalid
+ assert payment.extension_context is not None
+ payment.extension_context = payment.extension_context.model_copy(
+ update={field + "_id": "different"}
+ )
+ elif invalid == "untyped_binding":
+ assert payment.extension_context is not None
+ payment = payment.model_copy(
+ update={"extension_context": payment.extension_context.model_dump()}
+ )
+ elif invalid == "unbound_source":
+ assert payment.extension_context is not None
+ payment.extension_context = payment.extension_context.model_copy(
+ update={"source_id": None}
+ )
+ elif invalid == "extension":
+ payment.extension = "other"
+ elif invalid == "hash":
+ payment.payment_hash = "b" * 64
+ elif invalid == "outgoing":
+ payment.amount = -21000
+ mocker.patch(
+ "lnbits.core.crud.payments.get_standalone_payment",
+ AsyncMock(return_value=None if invalid == "missing" else payment),
+ )
+ update = mocker.patch(
+ "lnbits.core.services.payments.update_pending_payment", AsyncMock()
+ )
+ api = ExtensionHostAPI(
+ "paywallwasm",
+ [] if invalid == "no_permission" else [STATUS_PERMISSION],
+ user_id=None if invalid in {"no_owner", "anonymous"} else "source-owner",
+ context="event" if invalid == "no_owner" else "user",
+ )
+ with pytest.raises(PermissionError):
+ await api.wallet_invoice_status(_status_request())
+ update.assert_not_awaited()
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("shared", [False, True])
+async def test_fiat_delegates_to_core_with_source_bound_provider(
+ mocker, settings, shared
+):
+ wallet, create = _fiat_setup(mocker, settings, shared=shared)
+ result = await _api().wallet_create_fiat_invoice_public(_fiat_request())
+ assert result.model_dump() == {
+ "payment_hash": "a" * 64,
+ "payment_request": "https://checkout.example/pay",
+ "amount_msat": 21000,
+ "fiat_provider": "stripe",
+ }
+ args = create.await_args
+ assert args.args[0] == wallet.id
+ invoice = args.args[1]
+ assert invoice.amount == 2.5 and invoice.unit == "USD"
+ assert invoice.fiat_provider == "stripe"
+ assert invoice.extra == {"tag": "paywallwasm", "source_id": "attempt"}
+ assert args.kwargs["extension_context"] == _payment().extension_context
+ assert (await _api().wallet_list_fiat_providers(EmptyRequest())).providers == [
+ "stripe"
+ ]
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize(
+ "invalid",
+ [
+ "missing_source",
+ "other_owner",
+ "read_only",
+ "provider",
+ "disabled",
+ "no_permission",
+ "no_context",
+ ],
+)
+async def test_fiat_rejects_unapproved_wallets_and_providers(mocker, settings, invalid):
+ wallet, create = _fiat_setup(mocker, settings, shared=True)
+ if invalid == "missing_source":
+ mocker.patch(
+ "lnbits.core.wasm_ext.api.host.storage_get_row",
+ AsyncMock(return_value=None),
+ )
+ elif invalid == "other_owner":
+ wallet.user = "other"
+ elif invalid == "read_only":
+ wallet.share_permissions = [WalletPermission.VIEW_PAYMENTS]
+ elif invalid == "provider":
+ settings.stripe_limits.allowed_users = ["other"]
+ elif invalid == "disabled":
+ settings.stripe_enabled = False
+ api = _api()
+ if invalid == "no_permission":
+ api.permissions.clear()
+ if invalid == "no_context":
+ api.user_id = api.owner_id = None
+ with pytest.raises(PermissionError):
+ await api.wallet_create_fiat_invoice_public(_fiat_request())
+ create.assert_not_awaited()
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize(
+ "url",
+ [
+ "http://checkout.example",
+ "javascript:alert(1)",
+ "https://user:secret@checkout.example",
+ "https://checkout.example/\nsecret",
+ "https://checkout.example\\@evil.example",
+ None,
+ ],
+)
+async def test_fiat_rejects_unsafe_checkout_urls(mocker, settings, url):
+ _, create = _fiat_setup(mocker, settings)
+ create.return_value.extra["fiat_payment_request"] = url
+ with pytest.raises(ValueError, match="checkout URL"):
+ await _api().wallet_create_fiat_invoice_public(_fiat_request())
+
+
+def test_checkout_permissions_cannot_expand_wallet_or_provider_sources():
+ permission = {"id": FIAT_PERMISSION, "policies": [POLICY]}
+ config = _wasm_config("paywallwasm", [permission])
+ extension = make_installable_extension("paywallwasm")
+ grant = ExtensionPermission.model_validate(permission)
+ assert validate_wasm_extension_permissions(extension, [grant], config) == [grant]
+ for field in POLICY:
+ grant.policies = [{**POLICY, field: "other"}]
+ with pytest.raises(ValueError):
+ validate_wasm_extension_permissions(extension, [grant], config)
+ config["permissions"][0]["policies"] = [{"table": "attempts"}]
+ with pytest.raises(ValueError):
+ validate_wasm_extension_permissions(extension, [], config)
+
+
+@pytest.mark.parametrize(
+ "amount,currency",
+ [(float("inf"), "USD"), (float("nan"), "USD"), (0, "USD"), (1, "sat")],
+)
+def test_fiat_request_rejects_invalid_amounts_and_currencies(amount, currency):
+ with pytest.raises(ValidationError):
+ CreateFiatInvoicePublicRequest(
+ source_id="attempt", amount=amount, currency=currency
+ )
+
+
+def _payment(state="pending"):
+ return Payment(
+ checking_id="private",
+ payment_hash="a" * 64,
+ wallet_id="wallet-1",
+ amount=21000,
+ fee=0,
+ bolt11="invoice",
+ status=state,
+ extension="paywallwasm",
+ preimage="private",
+ extra={"fiat_payment_request": "https://checkout.example/pay"},
+ extension_context=PaymentExtensionContext(
+ extension_id="paywallwasm",
+ owner_id=sha256s("source-owner"),
+ wallet_id="wallet-1",
+ source_id="attempt",
+ ),
+ )
+
+
+def _status_request():
+ return InvoiceStatusRequest(payment_hash="a" * 64, source_id="attempt")
+
+
+def _fiat_request():
+ return CreateFiatInvoicePublicRequest(
+ source_id="attempt", amount=2.5, currency="USD"
+ )
+
+
+def _api():
+ return ExtensionHostAPI(
+ "paywallwasm",
+ [{"id": FIAT_PERMISSION, "policies": [POLICY]}],
+ user_id="source-owner",
+ )
+
+
+def _fiat_setup(mocker, settings, shared=False):
+ wallet = _wallet(shared=shared)
+ mocker.patch("lnbits.core.crud.wallets.get_wallet", AsyncMock(return_value=wallet))
+ mocker.patch(
+ "lnbits.core.wasm_ext.api.host.storage_get_row",
+ AsyncMock(return_value={"wallet": wallet.id, "provider": "stripe"}),
+ )
+
+ # The real storage API scopes returned rows to the invocation owner.
+ settings.stripe_enabled = True
+ settings.stripe_limits.allowed_users = ["source-owner"]
+ create = mocker.patch(
+ "lnbits.core.services.payments.create_payment_request",
+ AsyncMock(return_value=_payment()),
+ )
+ return wallet, create
### tests/unit/wasm-document-bridge.test.cjs
@@ -0,0 +1,90 @@
+const assert = require('node:assert/strict')
+const {readFileSync} = require('node:fs')
+const {test} = require('node:test')
+const vm = require('node:vm')
+
+function harness() {
+ const context = {window: {}, TextEncoder}
+ vm.runInNewContext(
+ readFileSync('lnbits/static/js/wasm-extension-component.js', 'utf8'),
+ context
+ )
+ const instance = {bridge: {extensionId: 'invoiceswasm'}}
+ for (const [name, method] of Object.entries(
+ context.window.WasmExtensionComponent.methods
+ ))
+ instance[name] = method.bind(instance)
+ return instance
+}
+
+test('CSV escapes quotes, newlines, formulas, and leading-space formulas', () => {
+ const instance = harness()
+ const result = instance.csvDocument({
+ filename: 'tickets.csv',
+ columns: ['Name', 'Message'],
+ rows: [
+ ['A "quote"', '=HYPERLINK("https://evil")'],
+ ['line\nbreak', ' +SUM(1)']
+ ]
+ })
+ assert.match(result.text, /"A ""quote"""/)
+ assert.match(result.text, /"'=HYPERLINK/)
+ assert.match(result.text, /"' \+SUM/)
+ assert.match(result.text, /"line\nbreak"/)
+})
+
+test('exports reject paths, executable formats, malformed rows and oversized payloads', () => {
+ const instance = harness(),
+ base = {filename: 'export.csv', columns: ['A'], rows: [['value']]}
+ for (const filename of ['../export.csv', 'x.html', '/tmp/x.csv', 'x.csv.exe'])
+ assert.throws(() => instance.csvDocument({...base, filename}))
+ for (const rows of [
+ [[{html: '<script>'}]],
+ [['a', 'b']],
+ [['a'.repeat(1048576)]]
+ ])
+ assert.throws(() => instance.csvDocument({...base, rows}))
+})
+
+test('printing only accepts bounded structured text and tables', () => {
+ const instance = harness(),
+ base = {
+ title: 'Invoice',
+ lines: ['<script>text</script>'],
+ columns: ['Item'],
+ rows: [['<img src=x onerror=alert(1)>']]
+ }
+ const result = instance.printDocument(base)
+ assert.equal(result.lines[0], '<script>text</script>')
+ assert.throws(() =>
+ instance.printDocument({...base, lines: [{html: 'unsafe'}]})
+ )
+ assert.throws(() => instance.printDocument({...base, title: 'x'.repeat(201)}))
+})
+
+test('bridge dispatch sends errors for invalid exports before triggering a browser action', async () => {
+ const instance = harness(),
+ replies = []
+ await instance.handleBridgeRequest(
+ {
+ type: 'lnbits-extension:request',
+ id: '1',
+ action: 'ui.download_csv',
+ filename: 'evil.html'
+ },
+ r => replies.push(r)
+ )
+ assert.equal(replies[0].ok, false)
+ assert.match(replies[0].error, /Invalid CSV filename/)
+})
+
+test('cancelled export never touches the document or creates a download URL', async () => {
+ const instance = harness()
+ instance.confirmDocumentAction = async () => false
+ const result = await instance.downloadCsv({
+ filename: 'export.csv',
+ columns: ['A'],
+ rows: [['value']]
+ })
+ assert.equal(result.cancelled, true)
+})
### tests/unit/wasm-local-storage.test.cjs
@@ -0,0 +1,133 @@
+const assert = require('node:assert/strict')
+const {readFileSync} = require('node:fs')
+const {webcrypto} = require('node:crypto')
+const {test} = require('node:test')
+const vm = require('node:vm')
+
+function harness() {
+ const stored = new Map()
+ let now = 1700000000000
+ const window = {
+ crypto: webcrypto,
+ localStorage: {
+ getItem: key => stored.get(key) ?? null,
+ setItem: (key, value) => stored.set(key, value),
+ removeItem: key => stored.delete(key)
+ }
+ }
+ const context = {window, TextEncoder, Date: {now: () => now}}
+ vm.runInNewContext(
+ readFileSync('lnbits/static/js/wasm-extension-component.js', 'utf8'),
+ context
+ )
+ const component = window.WasmExtensionComponent
+ const instance = {
+ ...component.data(),
+ g: {user: {id: 'alice'}},
+ $route: {path: '/ext/paywallwasm/one'}
+ }
+ for (const [name, method] of Object.entries(component.methods))
+ instance[name] = method.bind(instance)
+ instance.bridge.extensionId = 'paywallwasm'
+ instance.bridge.permissions = ['ui.storage.local']
+ const call = (action, value, key = 'receipt') =>
+ instance.localBridgeStorage({action: 'storage.local.' + action, key, value})
+ return {
+ instance,
+ stored,
+ call,
+ advance: delta => {
+ now += delta
+ }
+ }
+}
+
+test('remembered receipts are isolated by page, extension and account, including anonymous visitors', async () => {
+ const {instance, stored, call} = harness()
+ await call('set', 'opaque-token')
+ assert.equal((await call('get')).value, 'opaque-token')
+ instance.$route.path = '/ext/paywallwasm/two'
+ assert.equal((await call('get')).value, '')
+ instance.$route.path = '/ext/paywallwasm/one'
+ instance.g.user.id = 'bob'
+ assert.equal((await call('get')).value, '')
+ instance.g.user = null
+ assert.equal((await call('get')).value, '')
+ await call('set', 'anonymous-receipt')
+ instance.g.user = {id: 'alice'}
+ assert.equal((await call('get')).value, 'opaque-token')
+ instance.bridge.extensionId = 'other'
+ assert.equal((await call('get')).value, '')
+ instance.bridge.extensionId = 'paywallwasm'
+ await call('remove')
+ assert.equal((await call('get')).value, '')
+ assert.ok([...stored.keys()].every(key => !key.includes('alice')))
+})
+
+test('permission checks, key/value limits and account changes fail closed', async () => {
+ const {instance, stored, call} = harness()
+ instance.bridge.permissions = []
+ await assert.rejects(call('set', 'token'), /not permitted/)
+ instance.bridge.permissions = ['ui.storage.local']
+ for (const key of ['', 'a/b', 'x'.repeat(129)])
+ await assert.rejects(call('get', '', key), /Invalid/)
+ for (const value of ['x'.repeat(1025), {}, null])
+ await assert.rejects(call('set', value), /invalid/)
+ const pending = call('set', 'token')
+ instance.g.user.id = 'bob'
+ await assert.rejects(pending, /context changed/)
+ assert.equal(stored.size, 0)
+})
+
+test('receipts expire without reads extending their life; corrupt cache is discarded', async () => {
+ const {call, stored, advance} = harness()
+ await call('set', 'token')
+ advance(179 * 86400000)
+ assert.equal((await call('get')).value, 'token')
+ advance(86400001)
+ assert.equal((await call('get')).value, '')
+ assert.equal(stored.size, 0)
+ await call('set', 'token')
+ const key = [...stored.keys()][0]
+ stored.set(key, '{bad json')
+ assert.equal((await call('get')).value, '')
+})
+
+test('quotas cover all pages within an extension/account and reject oversized writes atomically', async () => {
+ const {instance, call, stored} = harness()
+ for (let i = 0; i < 128; i++) {
+ instance.$route.path = '/ext/paywallwasm/' + i
+ await call('set', 'token')
+ }
+ const before = [...stored.values()][0]
+ instance.$route.path = '/ext/paywallwasm/overflow'
+ await assert.rejects(call('set', 'token'), /quota/)
+ assert.equal([...stored.values()][0], before)
+ const second = harness()
+ for (let i = 0; i < 50; i++)
+ await second.call('set', 'x'.repeat(1024), 'k' + i)
+ await assert.rejects(async () => {
+ for (let i = 50; i < 80; i++)
+ await second.call('set', 'x'.repeat(1024), 'k' + i)
+ }, /quota/)
+})
+
+test('the bridge routes only the three allowed storage actions', async () => {
+ const {instance} = harness()
+ const replies = []
+ instance.sendResponse = (_, id, result) => replies.push({id, result})
+ for (const [id, action] of ['set', 'get', 'remove'].entries()) {
+ await instance.handleBridgeRequest(
+ {
+ type: 'lnbits-extension:request',
+ id,
+ action: 'storage.local.' + action,
+ key: 'receipt',
+ value: 'token'
+ },
+ {}
+ )
+ }
+ assert.ok(replies.every(reply => reply.result.ok))
+ assert.equal(replies[1].result.data.value, 'token')
+})
### tests/unit/wasm-theme-bridge.test.cjs
@@ -0,0 +1,134 @@
+const assert = require('node:assert/strict')
+const {readFileSync} = require('node:fs')
+const {test} = require('node:test')
+const vm = require('node:vm')
+
+function harness() {
+ const messages = [],
+ observed = []
+ const colors = {
+ '--q-primary': '#ea611d',
+ '--q-secondary': '#e56f35',
+ '--q-dark-page': '#2d293b',
+ '--private-key': 'not-a-theme-value'
+ }
+ const classes = new Set(['gradient-bg'])
+ const document = {
+ body: {
+ dataset: {theme: 'bitcoin'},
+ classList: {contains: key => classes.has(key)}
+ },
+ documentElement: {}
+ }
+ let callback,
+ disconnected = false
+ const window = {
+ getComputedStyle: () => ({getPropertyValue: name => colors[name] || ''}),
+ removeEventListener() {}
+ }
+ const context = {
+ window,
+ document,
+ CSS: {
+ supports: (property, value) =>
+ property === 'color' && /^#[0-9a-f]{6}$/i.test(value)
+ },
+ MutationObserver: class {
+ constructor(handler) {
+ callback = handler
+ }
+ observe(element, options) {
+ observed.push({element, options})
+ }
+ disconnect() {
+ disconnected = true
+ }
+ }
+ }
+ vm.runInNewContext(
+ readFileSync('lnbits/static/js/wasm-extension-component.js', 'utf8'),
+ context
+ )
+ const component = window.WasmExtensionComponent
+ const instance = {...component.data(), $q: {dark: {isActive: true}}}
+ for (const [name, method] of Object.entries(component.methods))
+ instance[name] = method.bind(instance)
+ instance.bridge = {...instance.bridge, extensionId: 'lnticketwasm'}
+ instance.bridgePort = {
+ postMessage: m => messages.push(JSON.parse(JSON.stringify(m))),
+ close() {}
+ }
+ return {
+ instance,
+ component,
+ messages,
+ colors,
+ classes,
+ observed,
+ document,
+ mutate: () => callback(),
+ disconnected: () => disconnected
+ }
+}
+
+test('context supplies only selected theme fields and allowlisted valid colors', () => {
+ const {instance, colors} = harness()
+ colors['--q-negative'] = 'url(https://example.com/image)'
+ colors['--q-info'] = 'x'.repeat(129)
+ const context = instance.plainBridgeContext()
+ assert.deepEqual(JSON.parse(JSON.stringify(context.theme)), {
+ dark: true,
+ name: 'bitcoin',
+ gradient: true,
+ colors: {primary: '#ea611d', secondary: '#e56f35', 'dark-page': '#2d293b'}
+ })
+ assert.equal(context.extensionId, 'lnticketwasm')
+ assert.equal(context.public, false)
+})
+
+test('parent palette and dark-mode changes notify the existing port without duplicates', () => {
+ const f = harness()
+ f.component.mounted.call(f.instance)
+ assert.equal(f.observed.length, 2)
+ assert.deepEqual(Array.from(f.observed[0].options.attributeFilter), [
+ 'class',
+ 'style',
+ 'data-theme'
+ ])
+ f.mutate()
+ f.mutate()
+ assert.equal(f.messages.length, 1)
+ f.colors['--q-primary'] = '#3ab77d'
+ f.document.body.dataset.theme = 'mint'
+ f.instance.$q.dark.isActive = false
+ f.classes.clear()
+ f.mutate()
+ assert.equal(f.messages.length, 2)
+ assert.equal(f.messages[1].type, 'lnbits-extension:event')
+ assert.equal(f.messages[1].event, 'ui.theme')
+ assert.equal(f.messages[1].data.colors.primary, '#3ab77d')
+ assert.equal(f.messages[1].data.dark, false)
+ assert.equal(f.messages[1].data.gradient, false)
+ f.instance.closeBridgePort()
+ f.colors['--q-primary'] = '#ff00ff'
+ f.mutate()
+ assert.equal(f.messages.length, 2)
+ f.component.unmounted.call(f.instance)
+ assert.equal(f.disconnected(), true)
+})
+
+test('the theme bridge does not accept guest theme mutations', async () => {
+ const {instance} = harness(),
+ responses = []
+ await instance.handleBridgeRequest(
+ {
+ type: 'lnbits-extension:request',
+ id: 'theme-change',
+ action: 'ui.theme',
+ data: {dark: false}
+ },
+ r => responses.push(r)
+ )
+ assert.equal(responses[0].ok, false)
+ assert.equal(instance.$q.dark.isActive, true)
+})Why this scored 41/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.