Compare commits

..
Author SHA1 Message Date
Vlad Stan a963b61cc8 fix: lint 2026-05-22 11:52:32 +03:00
Arc d66e22a83e Admin only toggle + remove annoying password browser thing 2026-05-21 14:18:28 +01:00
Arc 882d861f71 coming soon for sbscriptions 2026-05-21 13:56:09 +01:00
Vlad Stan 186aefad22 fix: api test 2026-05-21 14:21:49 +03:00
Vlad Stan 7badf98bb7 fix: unit tests 2026-05-21 14:12:43 +03:00
Vlad Stan 2ee098ddb1 fix: subscription_request_id 2026-05-21 14:12:43 +03:00
Vlad Stan 3723b6510d refactor: better ID check 2026-05-21 14:12:43 +03:00
Vlad Stan 03161f8e9b feat: handle subscriptions 2026-05-21 14:12:43 +03:00
Vlad Stan 5b7f9fa255 fix: remove customer_id 2026-05-21 14:12:43 +03:00
Vlad Stan 0c74adc494 feat: find customer by email 2026-05-21 14:12:43 +03:00
Vlad Stan ea6965905e fix: find customer by email 2026-05-21 14:12:43 +03:00
Vlad Stan ea8228fc84 feat: create customer id from email if missing 2026-05-21 14:12:43 +03:00
Vlad Stan 49adec6488 chore: bundle 2026-05-21 14:12:43 +03:00
ArcandVlad Stan c122bb45f4 Do the separator 🎵 2026-05-21 14:12:43 +03:00
751bd42169 feat: Adds revolut checkout and subscriptions (#3968)
Co-authored-by: alan <alan@lnbits.com>
2026-05-21 14:12:43 +03:00
Vlad Stan c4ee3a7c6b feat: introduce external_id 2026-05-21 14:12:43 +03:00
Vlad Stan 9a4e55f469 refactor: move private method to the bottom 2026-05-21 14:12:43 +03:00
Vlad Stan f45736e70e refactor: extract method 2026-05-21 14:12:43 +03:00
Vlad Stan ef39d02bd2 fix: simplify expected event types 2026-05-21 14:12:43 +03:00
Vlad Stan d66c7f7992 fix: plan 2026-05-21 14:12:43 +03:00
Vlad Stan 2abedccbc8 feat: first subscription 2026-05-21 14:12:43 +03:00
Vlad Stan cc498a7969 fix: webhook url for signature check 2026-05-21 14:12:43 +03:00
Vlad Stan cd57bf66fe fix: lint 2026-05-21 14:12:43 +03:00
Vlad Stan d921af3476 feat: basic square integration 2026-05-21 14:12:43 +03:00
Vlad StanandGitHub 30e0522419 fix: stricter asset upload (#3982) 2026-05-21 12:44:23 +02:00
dni ⚡andGitHub 8f033a6047 fix: OIDC SSO login issues. closes #3970 (#3979) 2026-05-20 09:27:02 +02:00
dni ⚡andGitHub a2c817a56b chore: update python packages (#3977) 2026-05-19 10:58:14 +02:00
555350085e feat: add min-release-age to .npmrc + update packages (#3975)
Co-authored-by: alan <alan@lnbits.com>
2026-05-19 09:41:32 +02:00
dni ⚡andGitHub fc5061a67f chore: remove unused library Chart (#3976) 2026-05-19 09:36:14 +02:00
Tiago VasconcelosandGitHub c9c68bd8d7 Fix: Use default reaction on bootstrap (#3965) 2026-05-14 04:56:41 +02:00
38 changed files with 6548 additions and 26308 deletions
+1
View File
@@ -0,0 +1 @@
min-release-age=7
+127 -3
View File
@@ -1,7 +1,9 @@
import base64
import io
from urllib.parse import quote
from uuid import uuid4
import filetype
from fastapi import UploadFile
from loguru import logger
from PIL import Image
@@ -10,11 +12,48 @@ from lnbits.core.crud.assets import create_asset, get_user_assets_count
from lnbits.core.models.assets import Asset
from lnbits.settings import settings
IMAGE_MIME_TYPE_ALIASES = {
"heic": "image/heic",
"heics": "image/heics",
"heif": "image/heif",
"image/jpg": "image/jpeg",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"png": "image/png",
}
PIL_IMAGE_FORMAT_MIME_TYPES = {
"JPEG": "image/jpeg",
"PNG": "image/png",
}
INLINE_ASSET_MIME_TYPES = {
"image/heic",
"image/heics",
"image/heif",
"image/jpeg",
"image/png",
}
ASSET_SECURITY_HEADERS = {
"X-Content-Type-Options": "nosniff",
"Content-Security-Policy": (
"sandbox; default-src 'none'; script-src 'none'; "
"object-src 'none'; base-uri 'none'"
),
}
THUMBNAIL_FORMAT_MIME_TYPES = {
"jpg": "image/jpeg",
"jpeg": "image/jpeg",
"png": "image/png",
}
async def create_user_asset(user_id: str, file: UploadFile, is_public: bool) -> Asset:
if not file.content_type:
raise ValueError("File must have a content type.")
if file.content_type.lower() not in settings.lnbits_assets_allowed_mime_types:
content_type = normalize_asset_mime_type(file.content_type)
filename = file.filename or "unnamed"
if content_type not in allowed_asset_mime_types():
raise ValueError(f"File type '{file.content_type}' not allowed.")
if not settings.is_unlimited_assets_user(user_id):
@@ -30,14 +69,26 @@ async def create_user_asset(user_id: str, file: UploadFile, is_public: bool) ->
f"File limit of {settings.lnbits_max_asset_size_mb}MB exceeded."
)
stored_mime_type = detect_image_mime_type(contents)
if stored_mime_type != content_type:
logger.warning(
"Image MIME type mismatch: declared={}, detected={}",
content_type,
stored_mime_type,
)
raise ValueError(
"Image file content does not match declared file type. "
f"Declared: '{content_type}', detected: '{stored_mime_type}'."
)
thumb_buffer = thumbnail_from_bytes(contents)
asset = Asset(
id=uuid4().hex,
user_id=user_id,
mime_type=file.content_type,
mime_type=stored_mime_type,
is_public=is_public,
name=file.filename or "unnamed",
name=filename,
size_bytes=len(contents),
thumbnail_base64=(
base64.b64encode(thumb_buffer.getvalue()).decode("utf-8")
@@ -51,6 +102,79 @@ async def create_user_asset(user_id: str, file: UploadFile, is_public: bool) ->
return asset
def normalize_asset_mime_type(content_type: str) -> str:
content_type = content_type.split(";", 1)[0].strip().lower()
return IMAGE_MIME_TYPE_ALIASES.get(content_type, content_type)
def normalize_media_type(media_type: str) -> str:
return media_type.split(";", 1)[0].strip().lower() or "application/octet-stream"
def thumbnail_media_type() -> str:
thumbnail_format = (settings.lnbits_asset_thumbnail_format or "png").strip().lower()
return THUMBNAIL_FORMAT_MIME_TYPES.get(thumbnail_format, "application/octet-stream")
def content_disposition(disposition: str, filename: str) -> str:
safe_filename = filename or "unnamed"
quoted_filename = quote(safe_filename, safe="")
if quoted_filename == safe_filename:
return f'{disposition}; filename="{safe_filename}"'
return f"{disposition}; filename*=utf-8''{quoted_filename}"
def allowed_asset_mime_types() -> set[str]:
return {
mime_type
for mime_type in (
normalize_asset_mime_type(mime_type)
for mime_type in settings.lnbits_assets_allowed_mime_types
)
if mime_type.startswith("image/")
}
def detect_image_mime_type(contents: bytes) -> str:
kind = filetype.guess(contents)
mime_type = normalize_asset_mime_type(kind.mime) if kind else None
if mime_type and mime_type in PIL_IMAGE_FORMAT_MIME_TYPES.values():
verify_pil_image(contents, mime_type)
return mime_type
if mime_type and mime_type.startswith("image/"):
return mime_type
try:
with Image.open(io.BytesIO(contents)) as image:
image.verify()
mime_type = PIL_IMAGE_FORMAT_MIME_TYPES.get(image.format or "")
except Exception as exc:
raise ValueError(
"Image file content does not match declared file type."
) from exc
if not mime_type:
raise ValueError("Image file content does not match declared file type.")
return mime_type
def verify_pil_image(contents: bytes, mime_type: str) -> None:
try:
with Image.open(io.BytesIO(contents)) as image:
image.verify()
detected_mime_type = PIL_IMAGE_FORMAT_MIME_TYPES.get(image.format or "")
except Exception as exc:
raise ValueError(
"Image file content does not match declared file type."
) from exc
if detected_mime_type != mime_type:
raise ValueError("Image file content does not match declared file type.")
def thumbnail_from_bytes(contents: bytes) -> io.BytesIO | None:
try:
image = Image.open(io.BytesIO(contents))
+12 -21
View File
@@ -1,7 +1,6 @@
import hashlib
import hmac
import json
import math
import time
from base64 import b64encode
@@ -220,35 +219,27 @@ def check_revolut_signature(
logger.warning("Revolut webhook signing secret is not set.")
raise ValueError("Revolut webhook cannot be verified.")
timestamp = int(timestamp_header)
timestamp_seconds = timestamp / 1000 if timestamp > 9999999999 else timestamp
if not math.isfinite(timestamp_seconds):
try:
timestamp = int(timestamp_header)
except ValueError as exc:
logger.warning("Invalid Revolut timestamp.")
raise ValueError("Invalid Revolut timestamp.")
raise ValueError("Invalid Revolut timestamp.") from exc
timestamp_seconds = timestamp / 1000 if timestamp > 9999999999 else timestamp
if abs(time.time() - timestamp_seconds) > tolerance_seconds:
logger.warning("Timestamp outside tolerance.")
raise ValueError("Timestamp outside tolerance." f"Timestamp: {timestamp}")
candidates = [
b"v1." + timestamp_header.encode() + b"." + payload,
payload,
f"{timestamp_header}.{payload.decode()}".encode(),
timestamp_header.encode() + b"." + payload,
]
signatures = []
for candidate in candidates:
digest = hmac.new(
key=secret.encode(), msg=candidate, digestmod=hashlib.sha256
).digest()
signatures.extend(
[digest.hex(), f"v1={digest.hex()}", b64encode(digest).decode()]
)
signed_payload = b"v1." + timestamp_header.encode() + b"." + payload
digest = hmac.new(
key=secret.encode(), msg=signed_payload, digestmod=hashlib.sha256
).hexdigest()
expected_signature = f"v1={digest}"
provided_signatures = [sig.strip() for sig in sig_header.split(",") if sig.strip()]
if not any(
hmac.compare_digest(expected, provided)
for expected in signatures
hmac.compare_digest(expected_signature, provided)
for provided in provided_signatures
):
logger.warning("Revolut signature verification failed.")
+4
View File
@@ -133,6 +133,10 @@ async def create_fiat_invoice(
raise ValueError(
f"Fiat provider '{fiat_provider_name}' is not enabled.",
)
if settings.fiat_providers_admin_only:
wallet = await get_wallet(wallet_id, conn=conn)
if not wallet or not settings.is_admin_user(wallet.user):
raise ValueError("Fiat providers are available to admins only.")
if invoice_data.unit == "sat":
raise ValueError("Fiat provider cannot be used with satoshis.")
+25 -9
View File
@@ -16,7 +16,14 @@ from lnbits.core.crud.assets import (
from lnbits.core.models.assets import AssetFilters, AssetInfo, AssetUpdate
from lnbits.core.models.misc import SimpleStatus
from lnbits.core.models.users import AccountId
from lnbits.core.services.assets import create_user_asset
from lnbits.core.services.assets import (
ASSET_SECURITY_HEADERS,
INLINE_ASSET_MIME_TYPES,
content_disposition,
create_user_asset,
normalize_media_type,
thumbnail_media_type,
)
from lnbits.db import Filters, Page
from lnbits.decorators import (
check_account_id_exists,
@@ -75,11 +82,7 @@ async def api_get_asset_data(
if not asset:
raise HTTPException(HTTPStatus.NOT_FOUND, "Asset not found.")
return Response(
content=asset.data,
media_type=asset.mime_type,
headers={"Content-Disposition": f'inline; filename="{asset.name}"'},
)
return asset_response(asset.data, asset.mime_type, asset.name)
@asset_router.get(
@@ -101,14 +104,14 @@ async def api_get_asset_thumbnail(
if not asset_info:
raise HTTPException(HTTPStatus.NOT_FOUND, "Asset not found.")
return Response(
return asset_response(
content=(
base64.b64decode(asset_info.thumbnail_base64)
if asset_info.thumbnail_base64
else b""
),
media_type=asset_info.mime_type,
headers={"Content-Disposition": f'inline; filename="{asset_info.name}"'},
media_type=thumbnail_media_type(),
filename=asset_info.name,
)
@@ -172,3 +175,16 @@ async def api_delete_asset(
await delete_user_asset(account_id.id, asset_id)
return SimpleStatus(success=True, message="Asset deleted successfully.")
def asset_response(content: bytes, media_type: str, filename: str) -> Response:
media_type = normalize_media_type(media_type)
disposition = "inline" if media_type in INLINE_ASSET_MIME_TYPES else "attachment"
return Response(
content=content,
media_type=media_type,
headers={
**ASSET_SECURITY_HEADERS,
"Content-Disposition": content_disposition(disposition, filename),
},
)
+5 -1
View File
@@ -348,7 +348,11 @@ async def handle_oauth_token(request: Request, provider: str) -> RedirectRespons
userinfo = await provider_sso.verify_and_process(request)
if not userinfo:
raise HTTPException(HTTPStatus.UNAUTHORIZED, "Invalid user info.")
user_id = decrypt_internal_message(provider_sso.state)
if provider_sso.state is None or provider_sso.state == "null":
user_id = None
else:
user_id = decrypt_internal_message(provider_sso.state)
request.session.pop("user", None)
return await _handle_sso_login(userinfo, user_id)
+94 -13
View File
@@ -18,7 +18,11 @@ from lnbits.core.services.fiat_providers import (
check_stripe_signature,
verify_paypal_webhook,
)
from lnbits.core.services.payments import create_fiat_invoice
from lnbits.core.services.payments import (
create_fiat_invoice,
create_wallet_invoice,
service_fee_fiat,
)
from lnbits.db import Filter, Filters
from lnbits.fiat import get_fiat_provider
from lnbits.fiat.base import FiatSubscriptionPaymentOptions
@@ -355,6 +359,7 @@ async def handle_revolut_event(event: dict):
payment = await get_standalone_payment(f"fiat_revolut_order_{order_id}")
if not payment:
logger.warning(f"No payment found for Revolut order: '{order_id}'.")
await _handle_revolut_subscription_order_paid(order_id)
return
await check_fiat_status(payment)
@@ -377,16 +382,37 @@ async def handle_revolut_event(event: dict):
async def _handle_revolut_subscription_initiated(event: dict):
subscription_id = event.get("subscription_id")
if not subscription_id:
subscription_id = event.get("id")
if not subscription_id:
logger.warning("Revolut subscription event missing subscription_id.")
return
fiat_provider = await get_fiat_provider("revolut")
if not isinstance(fiat_provider, RevolutWallet):
logger.warning("Revolut fiat provider is not configured.")
fiat_provider = await _get_revolut_provider()
if not fiat_provider:
return
subscription = await fiat_provider.get_subscription(subscription_id)
await _handle_revolut_subscription(subscription, fiat_provider)
async def _get_revolut_provider() -> RevolutWallet | None:
fiat_provider = await get_fiat_provider("revolut")
if not isinstance(fiat_provider, RevolutWallet):
logger.warning("Revolut fiat provider is not configured.")
return None
return fiat_provider
async def _handle_revolut_subscription(
subscription: dict, fiat_provider: RevolutWallet
):
subscription_id = subscription.get("id")
if not subscription_id:
logger.warning("Revolut subscription missing id.")
return
reference = fiat_provider.deserialize_subscription_reference(
subscription.get("external_reference")
)
@@ -429,21 +455,76 @@ async def _handle_revolut_subscription_initiated(event: dict):
"payment_request": order.get("checkout_url") or "",
},
}
lnbits_payment = await create_fiat_invoice(
lnbits_payment = await _create_revolut_subscription_payment(
wallet_id=reference.wallet_id,
invoice_data=CreateInvoice(
unit=currency,
amount=amount_minor / 100,
memo=reference.memo or "",
extra=extra,
fiat_provider="revolut",
external_id=subscription_id,
),
amount_minor=amount_minor,
currency=currency,
memo=reference.memo or "",
extra=extra,
order_id=order_id,
payment_request=order.get("checkout_url") or "",
subscription_id=subscription_id,
)
await check_fiat_status(lnbits_payment)
async def _handle_revolut_subscription_order_paid(order_id: str):
fiat_provider = await _get_revolut_provider()
if not fiat_provider:
return
order = await fiat_provider.get_order(order_id)
if order.get("type") != "payment" or order.get("state") != "completed":
logger.warning(f"Revolut order is not a completed payment: '{order_id}'.")
return
channel_data = order.get("channel_data") or {}
subscription_id = channel_data.get("subscription_id")
if not subscription_id:
logger.warning(f"Revolut order missing subscription_id: '{order_id}'.")
return
subscription = await fiat_provider.get_subscription(subscription_id)
if subscription.get("state") != "active":
logger.warning(f"Revolut subscription is not active: '{subscription_id}'.")
return
await _handle_revolut_subscription_initiated(subscription)
async def _create_revolut_subscription_payment(
wallet_id: str,
amount_minor: int,
currency: str,
memo: str,
extra: dict,
order_id: str,
payment_request: str,
subscription_id: str,
) -> Payment:
amount = RevolutWallet.minor_units_to_amount(amount_minor, currency)
payment = await create_wallet_invoice(
wallet_id,
CreateInvoice(
unit=currency,
amount=amount,
memo=memo,
extra=extra,
internal=True,
external_id=subscription_id,
),
)
payment.fee = -abs(service_fee_fiat(payment.msat, "revolut"))
payment.fiat_provider = "revolut"
payment.extra["fiat_checking_id"] = f"order_{order_id}"
payment.extra["fiat_payment_request"] = payment_request
checking_id = f"fiat_revolut_order_{order_id}"
await update_payment(payment, checking_id)
payment.checking_id = checking_id
return payment
async def _handle_square_payment_event(event: dict):
payment = _square_extract_payment(event)
payment_options = _deserialize_square_metadata(_square_payment_note(payment))
+4
View File
@@ -95,6 +95,10 @@ class FiatSubscriptionPaymentOptions(BaseModel):
description="Unique ID that can be used to identify the subscription request."
"If not provided, one will be generated.",
)
customer_email: str | None = Field(
default=None,
description="The customer email to use for the subscription.",
)
tag: str | None = Field(
default=None,
description="Payments created by the recurring subscription"
+170 -20
View File
@@ -2,6 +2,7 @@ import asyncio
import ipaddress
import json
from collections.abc import AsyncGenerator
from decimal import ROUND_HALF_UP, Decimal
from typing import Any
from urllib.parse import urlparse
@@ -56,6 +57,37 @@ REVOLUT_WEBHOOK_EVENTS = [
"SUBSCRIPTION_INITIATED",
]
ZERO_DECIMAL_CURRENCIES = {
"BIF",
"CLP",
"DJF",
"GNF",
"ISK",
"JPY",
"KMF",
"KRW",
"PYG",
"RWF",
"UGX",
"VND",
"VUV",
"XAF",
"XOF",
"XPF",
}
THREE_DECIMAL_CURRENCIES = {
"BHD",
"IQD",
"JOD",
"KWD",
"LYD",
"OMR",
"TND",
}
REVOLUT_CUSTOMER_LIST_LIMIT = 500
REVOLUT_CUSTOMER_LIST_MAX_PAGES = 20
REVOLUT_REQUEST_TIMEOUT = 30
class RevolutWallet(FiatProvider):
"""https://developer.revolut.com/docs/merchant"""
@@ -93,7 +125,11 @@ class RevolutWallet(FiatProvider):
return FiatStatusResponse(balance=0)
try:
r = await self.client.get("/api/orders", params={"limit": 1}, timeout=15)
r = await self.client.get(
"/api/orders",
params={"limit": 1},
timeout=REVOLUT_REQUEST_TIMEOUT,
)
r.raise_for_status()
_ = r.json()
return FiatStatusResponse(balance=0)
@@ -118,7 +154,7 @@ class RevolutWallet(FiatProvider):
ok=False, error_message="Invalid Revolut options"
)
amount_minor = int(amount * 100)
amount_minor = self.amount_to_minor_units(amount, currency)
checkout = opts.checkout or RevolutCheckoutOptions()
success_url = (
checkout.success_url
@@ -139,7 +175,9 @@ class RevolutWallet(FiatProvider):
}
try:
r = await self.client.post("/api/orders", json=payload)
r = await self.client.post(
"/api/orders", json=payload, timeout=REVOLUT_REQUEST_TIMEOUT
)
r.raise_for_status()
data = r.json()
order_id = data.get("id")
@@ -183,13 +221,6 @@ class RevolutWallet(FiatProvider):
)
extra = payment_options.extra or {}
customer_id = extra.get("customer_id")
if not customer_id:
return FiatSubscriptionResponse(
ok=False,
error_message="Revolut subscriptions require extra.customer_id.",
)
if not payment_options.subscription_request_id:
payment_options.subscription_request_id = urlsafe_short_hash()
@@ -202,7 +233,6 @@ class RevolutWallet(FiatProvider):
)
payload: dict[str, Any] = {
"plan_variation_id": subscription_id,
"customer_id": customer_id,
"external_reference": self._serialize_subscription_reference(reference),
"setup_order_redirect_url": (
payment_options.success_url
@@ -219,8 +249,17 @@ class RevolutWallet(FiatProvider):
}
try:
customer_id, customer_error = await self._get_subscription_customer_id(
payment_options
)
if not customer_id:
return FiatSubscriptionResponse(ok=False, error_message=customer_error)
payload["customer_id"] = customer_id
r = await self.client.post(
"/api/subscriptions", json=payload, headers=headers
"/api/subscriptions",
json=payload,
headers=headers,
timeout=REVOLUT_REQUEST_TIMEOUT,
)
r.raise_for_status()
data = r.json()
@@ -244,7 +283,7 @@ class RevolutWallet(FiatProvider):
return FiatSubscriptionResponse(
ok=True,
checkout_session_url=checkout_url,
subscription_request_id=revolut_subscription_id,
subscription_request_id=payment_options.subscription_request_id,
)
except json.JSONDecodeError:
return FiatSubscriptionResponse(
@@ -263,7 +302,10 @@ class RevolutWallet(FiatProvider):
**kwargs,
) -> FiatSubscriptionResponse:
try:
r = await self.client.post(f"/api/subscriptions/{subscription_id}/cancel")
r = await self.client.post(
f"/api/subscriptions/{subscription_id}/cancel",
timeout=REVOLUT_REQUEST_TIMEOUT,
)
r.raise_for_status()
return FiatSubscriptionResponse(ok=True)
except Exception as exc:
@@ -304,12 +346,16 @@ class RevolutWallet(FiatProvider):
return value.replace("order_", "", 1) if value.startswith("order_") else value
async def get_order(self, order_id: str) -> dict[str, Any]:
r = await self.client.get(f"/api/orders/{order_id}")
r = await self.client.get(
f"/api/orders/{order_id}", timeout=REVOLUT_REQUEST_TIMEOUT
)
r.raise_for_status()
return r.json()
async def get_subscription(self, subscription_id: str) -> dict[str, Any]:
r = await self.client.get(f"/api/subscriptions/{subscription_id}")
r = await self.client.get(
f"/api/subscriptions/{subscription_id}", timeout=REVOLUT_REQUEST_TIMEOUT
)
r.raise_for_status()
return r.json()
@@ -317,7 +363,60 @@ class RevolutWallet(FiatProvider):
self, subscription_id: str, cycle_id: str
) -> dict[str, Any]:
r = await self.client.get(
f"/api/subscriptions/{subscription_id}/cycles/{cycle_id}"
f"/api/subscriptions/{subscription_id}/cycles/{cycle_id}",
timeout=REVOLUT_REQUEST_TIMEOUT,
)
r.raise_for_status()
return r.json()
async def _get_subscription_customer_id(
self, payment_options: FiatSubscriptionPaymentOptions
) -> tuple[str | None, str | None]:
if not payment_options.customer_email:
return (
None,
"Revolut subscriptions require customer_email.",
)
customer = await self._get_customer_by_email(payment_options.customer_email)
customer_id = customer.get("id") if customer else None
if customer_id:
return customer_id, None
customer = await self._create_customer(payment_options.customer_email)
customer_id = customer.get("id")
if not customer_id:
return None, "Server error: missing customer id"
return customer_id, None
async def _get_customer_by_email(self, email: str) -> dict[str, Any] | None:
page_token = None
for _ in range(REVOLUT_CUSTOMER_LIST_MAX_PAGES):
customer_page = await self._list_customers(page_token=page_token)
customer = _find_customer_by_email(customer_page["customers"], email)
if customer:
return customer
page_token = customer_page.get("next_page_token")
if not page_token:
return None
return None
async def _list_customers(self, page_token: str | None = None) -> dict[str, Any]:
params: dict[str, Any] = {"limit": REVOLUT_CUSTOMER_LIST_LIMIT}
if page_token:
params["page_token"] = page_token
r = await self.client.get(
"/api/customers", params=params, timeout=REVOLUT_REQUEST_TIMEOUT
)
r.raise_for_status()
return _extract_customer_page(r.json())
async def _create_customer(self, email: str) -> dict[str, Any]:
r = await self.client.post(
"/api/customers",
json={"email": email},
timeout=REVOLUT_REQUEST_TIMEOUT,
)
r.raise_for_status()
return r.json()
@@ -354,13 +453,15 @@ class RevolutWallet(FiatProvider):
existing["already_exists"] = True
return existing
response = await client.post("/api/webhooks", json=payload, timeout=15)
response = await client.post(
"/api/webhooks", json=payload, timeout=REVOLUT_REQUEST_TIMEOUT
)
response.raise_for_status()
return response.json()
@classmethod
async def _list_webhooks(cls, client: httpx.AsyncClient) -> list[dict[str, Any]]:
response = await client.get("/api/webhooks", timeout=15)
response = await client.get("/api/webhooks", timeout=REVOLUT_REQUEST_TIMEOUT)
response.raise_for_status()
data = response.json()
if isinstance(data, list):
@@ -385,7 +486,9 @@ class RevolutWallet(FiatProvider):
if webhook_id and (
not webhook.get("events") or not webhook.get("signing_secret")
):
response = await client.get(f"/api/webhooks/{webhook_id}", timeout=15)
response = await client.get(
f"/api/webhooks/{webhook_id}", timeout=REVOLUT_REQUEST_TIMEOUT
)
response.raise_for_status()
webhook = response.json()
@@ -445,6 +548,25 @@ class RevolutWallet(FiatProvider):
return FiatPaymentFailedStatus()
return FiatPaymentPendingStatus()
@classmethod
def amount_to_minor_units(cls, amount: float | Decimal, currency: str) -> int:
scale = Decimal(10) ** cls.currency_exponent(currency)
return int((Decimal(str(amount)) * scale).quantize(Decimal("1"), ROUND_HALF_UP))
@classmethod
def minor_units_to_amount(cls, amount: int, currency: str) -> float:
scale = Decimal(10) ** cls.currency_exponent(currency)
return float(Decimal(amount) / scale)
@classmethod
def currency_exponent(cls, currency: str) -> int:
normalized = currency.upper()
if normalized in ZERO_DECIMAL_CURRENCIES:
return 0
if normalized in THREE_DECIMAL_CURRENCIES:
return 3
return 2
def _parse_create_opts(
self, raw_opts: dict[str, Any]
) -> RevolutCreateInvoiceOptions | None:
@@ -485,3 +607,31 @@ class RevolutWallet(FiatProvider):
str(settings.revolut_webhook_signing_secret),
]
)
def _extract_customer_page(data: Any) -> dict[str, Any]:
if isinstance(data, list):
return {"customers": _filter_customer_list(data)}
if isinstance(data, dict):
for field in ["customers", "data", "items"]:
customers = data.get(field)
if isinstance(customers, list):
return {
"customers": _filter_customer_list(customers),
"next_page_token": data.get("next_page_token"),
}
return {"customers": []}
def _filter_customer_list(customers: list[Any]) -> list[dict[str, Any]]:
return [customer for customer in customers if isinstance(customer, dict)]
def _find_customer_by_email(
customers: list[dict[str, Any]], email: str
) -> dict[str, Any] | None:
normalized_email = email.casefold()
for customer in customers:
if str(customer.get("email") or "").casefold() == normalized_email:
return customer
return None
+4
View File
@@ -137,6 +137,10 @@ class SquareWallet(FiatProvider):
payment_options: FiatSubscriptionPaymentOptions,
**kwargs,
) -> FiatSubscriptionResponse:
if settings.lnbits_running:
return FiatSubscriptionResponse(
ok=False, error_message="Subscription not supported for Square."
)
success_url = (
payment_options.success_url
or settings.square_payment_success_url
+11 -5
View File
@@ -323,11 +323,6 @@ class AssetSettings(LNbitsSettings):
"heic",
"heif",
"heics",
"text/plain",
"text/json",
"text/xml",
"application/json",
"application/pdf",
]
)
lnbits_asset_thumbnail_width: int = Field(default=128, ge=0)
@@ -775,6 +770,8 @@ class FiatProvidersSettings(
SquareFiatProvider,
RevolutFiatProvider,
):
fiat_providers_admin_only: bool = Field(default=True)
def is_fiat_provider_enabled(self, provider: str | None) -> bool:
"""
Checks if a specific fiat provider is enabled.
@@ -795,6 +792,15 @@ class FiatProvidersSettings(
"""
Returns a list of fiat payment methods allowed for the user.
"""
if self.fiat_providers_admin_only:
if not self.is_admin_user(user_id):
return []
return [
provider
for provider in ["stripe", "paypal", "square", "revolut"]
if self.is_fiat_provider_enabled(provider)
]
allowed_providers = []
if self.stripe_enabled and (
not self.stripe_limits.allowed_users
File diff suppressed because one or more lines are too long
+1 -1
View File
File diff suppressed because one or more lines are too long
+18 -18
View File
File diff suppressed because one or more lines are too long
@@ -12,6 +12,21 @@ window.app.component('lnbits-admin-fiat-providers', {
}
},
computed: {
fiatProvidersAllUsers: {
get() {
return this.formData?.fiat_providers_admin_only === false
},
set(value) {
this.formData.fiat_providers_admin_only = !value
this.formData.touch = null
}
},
fiatProviderAccessLabel() {
return this.fiatProvidersAllUsers ? 'All users' : 'Admins only'
},
secretInputStyle() {
return this.hideInputToggle ? {'-webkit-text-security': 'disc'} : {}
},
stripeWebhookUrl() {
return (
this.formData?.stripe_payment_webhook_url ||
+6 -5
View File
@@ -1,16 +1,17 @@
function eventReaction(amount) {
localUrl = ''
reaction = localStorage.getItem('lnbits.reactions')
if (!reaction || reaction === 'None') {
const reaction =
Quasar.LocalStorage.getItem('lnbits.reactions') || SETTINGS.defaultReaction
if (!reaction || reaction.toLowerCase() === 'none') {
return
}
try {
if (amount < 0) {
return
}
reaction = localStorage.getItem('lnbits.reactions')
if (reaction) {
window[reaction.split('|')[1]]()
if (typeof window[reaction] === 'function') {
window[reaction]()
}
} catch (e) {
console.log(e)
File diff suppressed because it is too large Load Diff
-47
View File
@@ -1,47 +0,0 @@
/*
* DOM element rendering detection
* https://davidwalsh.name/detect-node-insertion
*/
@keyframes chartjs-render-animation {
from { opacity: 0.99; }
to { opacity: 1; }
}
.chartjs-render-monitor {
animation: chartjs-render-animation 0.001s;
}
/*
* DOM element resizing detection
* https://github.com/marcj/css-element-queries
*/
.chartjs-size-monitor,
.chartjs-size-monitor-expand,
.chartjs-size-monitor-shrink {
position: absolute;
direction: ltr;
left: 0;
top: 0;
right: 0;
bottom: 0;
overflow: hidden;
pointer-events: none;
visibility: hidden;
z-index: -1;
}
.chartjs-size-monitor-expand > div {
position: absolute;
width: 1000000px;
height: 1000000px;
left: 0;
top: 0;
}
.chartjs-size-monitor-shrink > div {
position: absolute;
width: 200%;
height: 200%;
left: 0;
top: 0;
}
+867 -497
View File
File diff suppressed because it is too large Load Diff
+2773 -3121
View File
File diff suppressed because it is too large Load Diff
+222 -132
View File
@@ -1,5 +1,5 @@
/*!
* qrcode.vue v3.6.0
* qrcode.vue v3.9.0
* A Vue.js component to generate QRCode. Both support Vue 2 and Vue 3
* © 2017-PRESENT @scopewu(https://github.com/scopewu)
* MIT License.
@@ -909,7 +909,18 @@ var qrcodegen;
})(qrcodegen || (qrcodegen = {}));
var QR = qrcodegen;
var _uid = 0;
function getUid() {
if (typeof vue.useId === 'function') {
return "".concat(vue.useId(), "-").concat(_uid++);
}
return "vue-".concat(Math.random().toString(36).slice(2), "-").concat(_uid++);
}
var defaultErrorCorrectLevel = 'L';
var DEFAULT_QR_SIZE = 100;
var DEFAULT_MARGIN = 0;
var DEFAULT_IMAGE_SIZE_RATIO = 0.1;
var IMAGE_EXCAVATE_THICKNESS = 2;
var ErrorCorrectLevelMap = {
L: QR.QrCode.Ecc.LOW,
M: QR.QrCode.Ecc.MEDIUM,
@@ -929,74 +940,139 @@ var SUPPORTS_PATH2D = (function () {
function validErrorCorrectLevel(level) {
return level in ErrorCorrectLevelMap;
}
function getNeighborFlags(modules, row, col) {
var north = row > 0 ? modules[row - 1][col] : false;
var south = row < modules.length - 1 ? modules[row + 1][col] : false;
var west = col > 0 ? modules[row][col - 1] : false;
var east = col < modules[row].length - 1 ? modules[row][col + 1] : false;
return {
nw: !north && !west,
ne: !north && !east,
se: !south && !east,
sw: !south && !west,
};
}
function generateRoundedPath(modules, margin, radius) {
if (margin === void 0) { margin = 0; }
if (radius === void 0) { radius = 0; }
var pathSegments = [];
var r = Math.min(radius, 0.5);
for (var row = 0; row < modules.length; row++) {
for (var col = 0; col < modules[row].length; col++) {
if (!modules[row][col])
continue;
var _a = getNeighborFlags(modules, row, col), nw = _a.nw, ne = _a.ne, se = _a.se, sw = _a.sw;
var x = col + margin;
var y = row + margin;
pathSegments.push("M".concat(x + (nw ? r : 0), " ").concat(y), "L".concat(x + 1 - (ne ? r : 0), " ").concat(y));
if (ne) {
pathSegments.push("A".concat(r, " ").concat(r, " 0 0 1 ").concat(x + 1, " ").concat(y + r));
}
pathSegments.push("L".concat(x + 1, " ").concat(y + 1 - (se ? r : 0)));
if (se) {
pathSegments.push("A".concat(r, " ").concat(r, " 0 0 1 ").concat(x + 1 - r, " ").concat(y + 1));
}
pathSegments.push("L".concat(x + (sw ? r : 0), " ").concat(y + 1));
if (sw) {
pathSegments.push("A".concat(r, " ").concat(r, " 0 0 1 ").concat(x, " ").concat(y + 1 - r));
}
pathSegments.push("L".concat(x, " ").concat(y + (nw ? r : 0)));
if (nw) {
pathSegments.push("A".concat(r, " ").concat(r, " 0 0 1 ").concat(x + r, " ").concat(y));
}
pathSegments.push('z');
}
}
return pathSegments.join('');
}
function generatePath(modules, margin) {
if (margin === void 0) { margin = 0; }
var ops = [];
modules.forEach(function (row, y) {
var pathSegments = [];
for (var y = 0; y < modules.length; y++) {
var row = modules[y];
var start = null;
row.forEach(function (cell, x) {
for (var x = 0; x < row.length; x++) {
var cell = row[x];
if (!cell && start !== null) {
// M0 0h7v1H0z injects the space with the move and drops the comma,
// saving a char per operation
ops.push("M".concat(start + margin, " ").concat(y + margin, "h").concat(x - start, "v1H").concat(start + margin, "z"));
pathSegments.push("M".concat(start + margin, " ").concat(y + margin, "h").concat(x - start, "v1H").concat(start + margin, "z"));
start = null;
return;
continue;
}
// end of row, clean up or skip
if (x === row.length - 1) {
if (!cell) {
// We would have closed the op above already so this can only mean
// 2+ light modules in a row.
return;
continue;
}
if (start === null) {
// Just a single dark module.
ops.push("M".concat(x + margin, ",").concat(y + margin, " h1v1H").concat(x + margin, "z"));
pathSegments.push("M".concat(x + margin, ",").concat(y + margin, " h1v1H").concat(x + margin, "z"));
}
else {
// Otherwise finish the current line.
ops.push("M".concat(start + margin, ",").concat(y + margin, " h").concat(x + 1 - start, "v1H").concat(start + margin, "z"));
pathSegments.push("M".concat(start + margin, ",").concat(y + margin, " h").concat(x + 1 - start, "v1H").concat(start + margin, "z"));
}
return;
continue;
}
if (cell && start === null) {
start = x;
}
});
});
return ops.join('');
}
}
return pathSegments.join('');
}
function getImageSettings(cells, size, margin, imageSettings) {
var width = imageSettings.width, height = imageSettings.height, imageX = imageSettings.x, imageY = imageSettings.y;
var numCells = cells.length + margin * 2;
var defaultSize = Math.floor(size * 0.1);
var defaultSize = Math.floor(size * DEFAULT_IMAGE_SIZE_RATIO);
var scale = numCells / size;
var w = (width || defaultSize) * scale;
var h = (height || defaultSize) * scale;
var x = imageX == null ? cells.length / 2 - w / 2 : imageX * scale;
var y = imageY == null ? cells.length / 2 - h / 2 : imageY * scale;
var excavation = null;
if (imageSettings.excavate) {
var floorX = Math.floor(x);
var floorY = Math.floor(y);
var ceilW = Math.ceil(w + x - floorX);
var ceilH = Math.ceil(h + y - floorY);
excavation = { x: floorX, y: floorY, w: ceilW, h: ceilH };
}
return { x: x, y: y, h: h, w: w, excavation: excavation };
var borderRadius = (imageSettings.borderRadius || 0) * scale;
return { x: x, y: y, h: h, w: w, borderRadius: borderRadius };
}
function excavateModules(modules, excavation) {
return modules.slice().map(function (row, y) {
if (y < excavation.y || y >= excavation.y + excavation.h) {
return row;
}
return row.map(function (cell, x) {
if (x < excavation.x || x >= excavation.x + excavation.w) {
return cell;
}
return false;
});
function useQRCode(props) {
var margin = vue.computed(function () { var _a; return ((_a = props.margin) !== null && _a !== void 0 ? _a : DEFAULT_MARGIN) >>> 0; });
var cells = vue.computed(function () {
var level = validErrorCorrectLevel(props.level) ? props.level : defaultErrorCorrectLevel;
return QR.QrCode.encodeText(props.value, ErrorCorrectLevelMap[level]).getModules();
});
var numCells = vue.computed(function () { return cells.value.length + margin.value * 2; });
var fgPath = vue.computed(function () {
if (props.radius > 0) {
return generateRoundedPath(cells.value, margin.value, props.radius);
}
return generatePath(cells.value, margin.value);
});
var imageProps = vue.computed(function () {
if (!props.imageSettings.src)
return null;
var settings = getImageSettings(cells.value, props.size, margin.value, props.imageSettings);
return {
x: settings.x + margin.value,
y: settings.y + margin.value,
width: settings.w,
height: settings.h,
borderRadius: settings.borderRadius,
};
});
var imageBorderProps = vue.computed(function () {
if (!props.imageSettings.excavate || !imageProps.value)
return null;
var borderThickness = IMAGE_EXCAVATE_THICKNESS / (props.size / numCells.value);
return {
x: imageProps.value.x - borderThickness,
y: imageProps.value.y - borderThickness,
width: imageProps.value.width + borderThickness * 2,
height: imageProps.value.height + borderThickness * 2,
borderRadius: imageProps.value.borderRadius,
};
});
return { margin: margin, numCells: numCells, cells: cells, fgPath: fgPath, imageProps: imageProps, imageBorderProps: imageBorderProps };
}
var QRCodeProps = {
value: {
@@ -1006,7 +1082,7 @@ var QRCodeProps = {
},
size: {
type: Number,
default: 100,
default: DEFAULT_QR_SIZE,
},
level: {
type: String,
@@ -1024,7 +1100,7 @@ var QRCodeProps = {
margin: {
type: Number,
required: false,
default: 0,
default: DEFAULT_MARGIN,
},
imageSettings: {
type: Object,
@@ -1052,6 +1128,12 @@ var QRCodeProps = {
required: false,
default: '#fff',
},
radius: {
type: Number,
required: false,
default: 0,
validator: function (r) { return !isNaN(r) && r >= 0 && r <= 0.5; },
},
};
var QRCodeVueProps = __assign(__assign({}, QRCodeProps), { renderAs: {
type: String,
@@ -1063,36 +1145,11 @@ var QrcodeSvg = vue.defineComponent({
name: 'QRCodeSvg',
props: QRCodeProps,
setup: function (props) {
var numCells = vue.ref(0);
var fgPath = vue.ref('');
var imageProps;
var generate = function () {
var value = props.value, _level = props.level, _margin = props.margin;
var margin = _margin >>> 0;
var level = validErrorCorrectLevel(_level) ? _level : defaultErrorCorrectLevel;
var cells = QR.QrCode.encodeText(value, ErrorCorrectLevelMap[level]).getModules();
numCells.value = cells.length + margin * 2;
if (props.imageSettings.src) {
var imageSettings = getImageSettings(cells, props.size, margin, props.imageSettings);
imageProps = {
x: imageSettings.x + margin,
y: imageSettings.y + margin,
width: imageSettings.w,
height: imageSettings.h,
};
if (imageSettings.excavation) {
cells = excavateModules(cells, imageSettings.excavation);
}
}
// Drawing strategy: instead of a rect per module, we're going to create a
// single path for the dark modules and layer that on top of a light rect,
// for a total of 2 DOM nodes. We pay a bit more in string concat but that's
// way faster than DOM ops.
// For level 1, 441 nodes -> 2
// For level 40, 31329 -> 2
fgPath.value = generatePath(cells, margin);
};
var renderGradient = function () {
var _a = useQRCode(props), numCells = _a.numCells, fgPath = _a.fgPath, imageProps = _a.imageProps, imageBorderProps = _a.imageBorderProps;
var uid = getUid();
var qrGradientId = "qrcode.vue-gradient-".concat(uid);
var qrLogoClipPathId = "qrcode.vue-logo-clip-path-".concat(uid);
var gradientVNode = vue.computed(function () {
if (!props.gradient)
return null;
var gradientProps = props.gradientType === 'linear'
@@ -1109,7 +1166,7 @@ var QrcodeSvg = vue.defineComponent({
fx: '50%',
fy: '50%',
};
return vue.h(props.gradientType === 'linear' ? 'linearGradient' : 'radialGradient', __assign({ id: 'qr-gradient' }, gradientProps), [
return vue.h(props.gradientType === 'linear' ? 'linearGradient' : 'radialGradient', __assign({ id: qrGradientId }, gradientProps), [
vue.h('stop', {
offset: '0%',
style: { stopColor: props.gradientStartColor },
@@ -1119,27 +1176,52 @@ var QrcodeSvg = vue.defineComponent({
style: { stopColor: props.gradientEndColor },
}),
]);
};
generate();
vue.onUpdated(generate);
});
var clipPathVNode = vue.computed(function () {
if (!imageProps.value)
return null;
var borderRadius = imageProps.value.borderRadius;
if (borderRadius <= 0)
return null;
return vue.h('clipPath', { id: qrLogoClipPathId }, [
vue.h('rect', {
x: imageProps.value.x,
y: imageProps.value.y,
width: imageProps.value.width,
height: imageProps.value.height,
rx: borderRadius,
ry: borderRadius,
}),
]);
});
return function () { return vue.h('svg', {
width: props.size,
height: props.size,
'shape-rendering': "crispEdges",
xmlns: 'http://www.w3.org/2000/svg',
viewBox: "0 0 ".concat(numCells.value, " ").concat(numCells.value),
role: 'img',
'aria-label': props.value,
}, [
vue.h('defs', {}, [renderGradient()]),
vue.h('defs', {}, [gradientVNode.value, clipPathVNode.value]),
vue.h('rect', {
width: '100%',
height: '100%',
fill: props.background,
}),
vue.h('path', {
fill: props.gradient ? 'url(#qr-gradient)' : props.foreground,
fill: props.gradient ? "url(#".concat(qrGradientId, ")") : props.foreground,
d: fgPath.value,
}),
props.imageSettings.src && vue.h('image', __assign({ href: props.imageSettings.src }, imageProps)),
imageBorderProps.value && vue.h('rect', {
x: imageBorderProps.value.x,
y: imageBorderProps.value.y,
width: imageBorderProps.value.width,
height: imageBorderProps.value.height,
fill: props.background,
rx: imageBorderProps.value.borderRadius,
ry: imageBorderProps.value.borderRadius,
}),
props.imageSettings.src && imageProps.value && vue.h('image', __assign(__assign({ href: props.imageSettings.src }, imageProps.value), (imageProps.value.borderRadius > 0 ? { 'clip-path': "url(#".concat(qrLogoClipPathId, ")") } : {}))),
]); };
},
});
@@ -1147,81 +1229,89 @@ var QrcodeCanvas = vue.defineComponent({
name: 'QRCodeCanvas',
props: QRCodeProps,
setup: function (props, ctx) {
var _a = useQRCode(props), margin = _a.margin, cells = _a.cells, numCells = _a.numCells, fgPath = _a.fgPath, imageProps = _a.imageProps, imageBorderProps = _a.imageBorderProps;
var canvasEl = vue.ref(null);
var imageRef = vue.ref(null);
var imageEl = vue.ref(null);
var drawRoundedRect = function (ctx, x, y, width, height, radius) {
ctx.beginPath();
if (ctx.roundRect) {
ctx.roundRect(x, y, width, height, radius);
}
else {
ctx.rect(x, y, width, height);
}
};
var generate = function () {
var value = props.value, _level = props.level, size = props.size, _margin = props.margin, background = props.background, foreground = props.foreground, gradient = props.gradient, gradientType = props.gradientType, gradientStartColor = props.gradientStartColor, gradientEndColor = props.gradientEndColor;
var margin = _margin >>> 0;
var level = validErrorCorrectLevel(_level) ? _level : defaultErrorCorrectLevel;
var size = props.size, background = props.background, foreground = props.foreground, gradient = props.gradient, gradientType = props.gradientType, gradientStartColor = props.gradientStartColor, gradientEndColor = props.gradientEndColor;
var canvas = canvasEl.value;
if (!canvas) {
return;
}
var ctx = canvas.getContext('2d');
if (!ctx) {
var canvasCtx = canvas.getContext('2d');
if (!canvasCtx) {
return;
}
var cells = QR.QrCode.encodeText(value, ErrorCorrectLevelMap[level]).getModules();
var numCells = cells.length + margin * 2;
var image = imageRef.value;
var imageProps = { x: 0, y: 0, width: 0, height: 0 };
var showImage = props.imageSettings.src && image != null && image.naturalWidth !== 0 && image.naturalHeight !== 0;
if (showImage) {
var imageSettings = getImageSettings(cells, props.size, margin, props.imageSettings);
imageProps = {
x: imageSettings.x + margin,
y: imageSettings.y + margin,
width: imageSettings.w,
height: imageSettings.h,
};
if (imageSettings.excavation) {
cells = excavateModules(cells, imageSettings.excavation);
}
}
var devicePixelRatio = window.devicePixelRatio || 1;
var scale = (size / numCells) * devicePixelRatio;
var image = imageEl.value;
var devicePixelRatio = typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1;
var scale = (size / numCells.value) * devicePixelRatio;
canvas.height = canvas.width = size * devicePixelRatio;
ctx.scale(scale, scale);
ctx.fillStyle = background;
ctx.fillRect(0, 0, numCells, numCells);
canvasCtx.setTransform(scale, 0, 0, scale, 0, 0);
canvasCtx.fillStyle = background;
canvasCtx.fillRect(0, 0, numCells.value, numCells.value);
if (gradient) {
var grad = void 0;
if (gradientType === 'linear') {
grad = ctx.createLinearGradient(0, 0, numCells, numCells);
grad = canvasCtx.createLinearGradient(0, 0, numCells.value, numCells.value);
}
else {
grad = ctx.createRadialGradient(numCells / 2, numCells / 2, 0, numCells / 2, numCells / 2, numCells / 2);
grad = canvasCtx.createRadialGradient(numCells.value / 2, numCells.value / 2, 0, numCells.value / 2, numCells.value / 2, numCells.value / 2);
}
grad.addColorStop(0, gradientStartColor);
grad.addColorStop(1, gradientEndColor);
ctx.fillStyle = grad;
canvasCtx.fillStyle = grad;
}
else {
ctx.fillStyle = foreground;
canvasCtx.fillStyle = foreground;
}
if (SUPPORTS_PATH2D) {
ctx.fill(new Path2D(generatePath(cells, margin)));
canvasCtx.fill(new Path2D(fgPath.value));
}
else {
cells.forEach(function (row, rdx) {
cells.value.forEach(function (row, rdx) {
row.forEach(function (cell, cdx) {
if (cell) {
ctx.fillRect(cdx + margin, rdx + margin, 1, 1);
canvasCtx.fillRect(cdx + margin.value, rdx + margin.value, 1, 1);
}
});
});
}
if (showImage) {
ctx.drawImage(image, imageProps.x, imageProps.y, imageProps.width, imageProps.height);
var showImage = props.imageSettings.src && image && image.naturalWidth !== 0 && image.naturalHeight !== 0;
if (showImage && imageProps.value) {
if (imageBorderProps.value) {
var imageBorder = imageBorderProps.value;
canvasCtx.fillStyle = props.background;
drawRoundedRect(canvasCtx, imageBorder.x, imageBorder.y, imageBorder.width, imageBorder.height, imageBorder.borderRadius);
canvasCtx.fill();
}
var borderRadius = imageProps.value.borderRadius;
if (borderRadius > 0) {
canvasCtx.save();
drawRoundedRect(canvasCtx, imageProps.value.x, imageProps.value.y, imageProps.value.width, imageProps.value.height, borderRadius);
canvasCtx.clip();
canvasCtx.drawImage(image, imageProps.value.x, imageProps.value.y, imageProps.value.width, imageProps.value.height);
canvasCtx.restore();
}
else {
canvasCtx.drawImage(image, imageProps.value.x, imageProps.value.y, imageProps.value.width, imageProps.value.height);
}
}
};
vue.onMounted(generate);
vue.onUpdated(generate);
var style = ctx.attrs.style;
vue.watchEffect(generate);
return function () { return vue.h(vue.Fragment, [
vue.h('canvas', __assign(__assign({}, ctx.attrs), { ref: canvasEl, style: __assign(__assign({}, style), { width: "".concat(props.size, "px"), height: "".concat(props.size, "px") }) })),
vue.h('canvas', __assign(__assign({}, ctx.attrs), { ref: canvasEl, role: 'img', 'aria-label': props.value, style: __assign(__assign({}, ctx.attrs.style), { width: "".concat(props.size, "px"), height: "".concat(props.size, "px") }) })),
props.imageSettings.src && vue.h('img', {
ref: imageRef,
ref: imageEl,
src: props.imageSettings.src,
style: { display: 'none' },
onLoad: generate,
@@ -1231,23 +1321,23 @@ var QrcodeCanvas = vue.defineComponent({
});
var QrcodeVue = vue.defineComponent({
name: 'Qrcode',
render: function () {
var _a = this.$props, renderAs = _a.renderAs, value = _a.value, size = _a.size, margin = _a.margin, level = _a.level, background = _a.background, foreground = _a.foreground, imageSettings = _a.imageSettings, gradient = _a.gradient, gradientType = _a.gradientType, gradientStartColor = _a.gradientStartColor, gradientEndColor = _a.gradientEndColor;
return vue.h(renderAs === 'svg' ? QrcodeSvg : QrcodeCanvas, {
value: value,
size: size,
margin: margin,
level: level,
background: background,
foreground: foreground,
imageSettings: imageSettings,
gradient: gradient,
gradientType: gradientType,
gradientStartColor: gradientStartColor,
gradientEndColor: gradientEndColor,
});
},
props: QRCodeVueProps,
setup: function (props) {
return function () { return vue.h(props.renderAs === 'svg' ? QrcodeSvg : QrcodeCanvas, {
value: props.value,
size: props.size,
margin: props.margin,
level: props.level,
background: props.background,
foreground: props.foreground,
imageSettings: props.imageSettings,
gradient: props.gradient,
gradientType: props.gradientType,
gradientStartColor: props.gradientStartColor,
gradientEndColor: props.gradientEndColor,
radius: props.radius,
}); };
},
});
exports.QrcodeCanvas = QrcodeCanvas;
+15 -28
View File
@@ -43,8 +43,7 @@ summary {
abbr[title] {
border-bottom: none;
text-decoration: underline;
-webkit-text-decoration: underline dotted;
text-decoration: underline dotted;
text-decoration: underline dotted;
}
/**
@@ -200,8 +199,7 @@ input[type=search]::-webkit-search-decoration {
.material-symbols-outlined,
.material-symbols-rounded,
.material-symbols-sharp {
-webkit-user-select: none;
user-select: none;
user-select: none;
cursor: inherit;
font-size: inherit;
display: inline-flex;
@@ -998,8 +996,7 @@ input[type=search]::-webkit-search-decoration {
height: 1px;
}
.q-checkbox__bg, .q-checkbox__icon-container {
-webkit-user-select: none;
user-select: none;
user-select: none;
}
.q-checkbox__bg {
top: 25%;
@@ -2212,8 +2209,7 @@ body.q-ios-padding .q-dialog__inner > div {
width: 100%;
min-width: 0;
outline: 0 !important;
-webkit-user-select: auto;
user-select: auto;
user-select: auto;
}
.q-field__native:-webkit-autofill, .q-field__input:-webkit-autofill {
-webkit-animation-name: q-autofill;
@@ -3039,8 +3035,7 @@ body.body--dark .q-knob--editable:focus:before {
z-index: 2001;
height: 100%;
width: 15px;
-webkit-user-select: none;
user-select: none;
user-select: none;
}
.q-layout, .q-header, .q-footer, .q-page {
@@ -3297,8 +3292,7 @@ body.platform-ios .q-layout--containerized {
height: 1px;
}
.q-radio__bg, .q-radio__icon-container {
-webkit-user-select: none;
user-select: none;
user-select: none;
}
.q-radio__bg {
top: 25%;
@@ -3782,8 +3776,7 @@ body.platform-ios:not(.native-mobile) .q-dialog__inner--top .q-select__dialog--f
.q-slide-item__content {
background: inherit;
transition: transform 0.2s ease-in;
-webkit-user-select: none;
user-select: none;
user-select: none;
cursor: pointer;
}
@@ -4156,8 +4149,7 @@ body.desktop .q-slider.q-slider--enabled .q-slider__track-container:hover .q-sli
}
.q-splitter__separator {
background-color: rgba(0, 0, 0, 0.12);
-webkit-user-select: none;
user-select: none;
user-select: none;
position: relative;
z-index: 1;
}
@@ -4246,8 +4238,7 @@ body.desktop .q-slider.q-slider--enabled .q-slider__track-container:hover .q-sli
color: #000;
}
.q-stepper__tab--navigation {
-webkit-user-select: none;
user-select: none;
user-select: none;
cursor: pointer;
}
.q-stepper__tab--active, .q-stepper__tab--done {
@@ -4479,8 +4470,7 @@ body.desktop .q-slider.q-slider--enabled .q-slider__track-container:hover .q-sli
.q-table th {
font-weight: 500;
font-size: 12px;
-webkit-user-select: none;
user-select: none;
user-select: none;
}
.q-table th.sortable {
cursor: pointer;
@@ -5484,8 +5474,7 @@ body.desktop .q-table > tbody > tr:not(.q-tr--no-hover):hover > td:not(.q-td--no
width: 0.5em;
height: 0.5em;
transition: left 0.22s cubic-bezier(0.4, 0, 0.2, 1);
-webkit-user-select: none;
user-select: none;
user-select: none;
z-index: 0;
}
.q-toggle__thumb:after {
@@ -10337,6 +10326,7 @@ body.body--dark .inset-shadow-down {
.glossy {
background-image: linear-gradient(to bottom, rgba(255, 255, 255, 0.3), rgba(255, 255, 255, 0) 50%, rgba(0, 0, 0, 0.12) 51%, rgba(0, 0, 0, 0.04)) !important;
}
.q-placeholder::placeholder {
color: inherit;
opacity: 0.7;
@@ -10368,8 +10358,7 @@ body.body--dark .inset-shadow-down {
text-decoration: none;
}
.q-link--focusable:focus-visible {
-webkit-text-decoration: underline dashed currentColor 1px;
text-decoration: underline dashed currentColor 1px;
text-decoration: underline dashed currentColor 1px;
}
body.electron .q-electron-drag {
@@ -10386,8 +10375,7 @@ img.responsive {
}
.non-selectable {
-webkit-user-select: none !important;
user-select: none !important;
user-select: none !important;
}
.scroll,
@@ -11045,8 +11033,7 @@ body.q-ios-padding .fullscreen {
}
.q-touch {
-webkit-user-select: none;
user-select: none;
user-select: none;
user-drag: none;
-khtml-user-drag: none;
-webkit-user-drag: none;
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
@@ -1,5 +1,5 @@
<template id="lnbits-admin-fiat-providers">
<h6 class="q-my-none q-mb-sm">
<h6 class="q-my-none q-mb-sm row items-center q-gutter-sm">
<span v-text="$t('fiat_providers')"></span>
<q-btn
round
@@ -7,6 +7,18 @@
@click="hideInputToggle = !hideInputToggle"
:icon="hideInputToggle ? 'visibility_off' : 'visibility'"
></q-btn>
<q-toggle
dense
size="sm"
color="warning"
v-model="fiatProvidersAllUsers"
:label="fiatProviderAccessLabel"
>
<q-tooltip>
If enabled for all users, your users may pass a memo that suspends your
account with your fiat providers
</q-tooltip>
</q-toggle>
</h6>
<div class="row">
<div class="col">
@@ -46,7 +58,11 @@
<q-input
filled
class="q-mt-md"
:type="hideInputToggle ? 'password' : 'text'"
type="text"
:input-style="secretInputStyle"
autocomplete="off"
autocapitalize="off"
spellcheck="false"
v-model="formData.stripe_api_secret_key"
:label="$t('secret_key')"
></q-input>
@@ -108,7 +124,11 @@
<q-input
filled
class="q-mt-md"
:type="hideInputToggle ? 'password' : 'text'"
type="text"
:input-style="secretInputStyle"
autocomplete="off"
autocapitalize="off"
spellcheck="false"
v-model="formData.stripe_webhook_signing_secret"
:label="$t('signing_secret')"
:hint="$t('signing_secret_hint')"
@@ -325,14 +345,22 @@
<q-input
filled
class="q-mt-md"
:type="hideInputToggle ? 'password' : 'text'"
type="text"
:input-style="secretInputStyle"
autocomplete="off"
autocapitalize="off"
spellcheck="false"
v-model="formData.paypal_client_id"
:label="$t('client_id')"
></q-input>
<q-input
filled
class="q-mt-md"
:type="hideInputToggle ? 'password' : 'text'"
type="text"
:input-style="secretInputStyle"
autocomplete="off"
autocapitalize="off"
spellcheck="false"
v-model="formData.paypal_client_secret"
:label="$t('secret_key')"
></q-input>
@@ -394,7 +422,11 @@
<q-input
filled
class="q-mt-md"
:type="hideInputToggle ? 'password' : 'text'"
type="text"
:input-style="secretInputStyle"
autocomplete="off"
autocapitalize="off"
spellcheck="false"
v-model="formData.paypal_webhook_id"
:label="$t('webhook_id')"
:hint="$t('webhook_id_hint')"
@@ -611,7 +643,11 @@
<q-input
filled
class="q-mt-md"
:type="hideInputToggle ? 'password' : 'text'"
type="text"
:input-style="secretInputStyle"
autocomplete="off"
autocapitalize="off"
spellcheck="false"
v-model="formData.square_access_token"
:label="$t('access_token')"
></q-input>
@@ -688,7 +724,11 @@
<q-input
filled
class="q-mt-md"
:type="hideInputToggle ? 'password' : 'text'"
type="text"
:input-style="secretInputStyle"
autocomplete="off"
autocapitalize="off"
spellcheck="false"
v-model="formData.square_webhook_signature_key"
:label="$t('signing_secret')"
:hint="$t('square_webhook_signature_key_hint')"
@@ -866,6 +906,7 @@
</q-expansion-item>
</q-card>
</q-expansion-item>
<q-separator></q-separator>
<q-expansion-item header-class="text-primary text-bold">
<template v-slot:header>
<q-item-section avatar>
@@ -899,7 +940,11 @@
<q-input
filled
class="q-mt-md"
:type="hideInputToggle ? 'password' : 'text'"
type="text"
:input-style="secretInputStyle"
autocomplete="off"
autocapitalize="off"
spellcheck="false"
v-model="formData.revolut_api_secret_key"
label="API secret key"
></q-input>
@@ -1175,8 +1220,8 @@
<q-chip dense color="positive" text-color="white" icon="check"
>Checkout</q-chip
>
<q-chip dense color="positive" text-color="white" icon="check"
>Subscriptions</q-chip
<q-chip dense color="warning" text-color="black" icon="schedule"
>Subscriptions coming soon</q-chip
>
<q-chip dense color="negative" text-color="white" icon="close"
>Tap-to-pay</q-chip
+670 -198
View File
File diff suppressed because it is too large Load Diff
+10 -10
View File
@@ -15,24 +15,24 @@
"devDependencies": {
"clean-css-cli": "^5.6.3",
"concat": "^1.0.3",
"prettier": "^3.7.4",
"prettier": "^3.8.3",
"pyright": "1.1.289",
"sass": "^1.94.2",
"terser": "^5.44.1"
"sass": "^1.99.0",
"terser": "^5.47.1"
},
"dependencies": {
"axios": "^1.15.0",
"axios": "^1.16.0",
"chart.js": "^4.5.1",
"moment": "^2.30.1",
"nostr-tools": "^2.18.2",
"qrcode.vue": "^3.6.0",
"quasar": "2.18.6",
"nostr-tools": "^2.23.3",
"qrcode.vue": "^3.9.0",
"quasar": "2.19.3",
"showdown": "^2.1.0",
"underscore": "^1.13.8",
"vue": "3.5.25",
"vue-i18n": "^11.2.2",
"vue": "3.5.34",
"vue-i18n": "^11.4.2",
"vue-qrcode-reader": "^5.7.3",
"vue-router": "4.6.3",
"vue-router": "5.0.6",
"vuex": "4.1.0"
},
"vendor": [
Generated
+5 -5
View File
@@ -4560,14 +4560,14 @@ files = [
[[package]]
name = "urllib3"
version = "2.6.3"
version = "2.7.0"
description = "HTTP library with thread-safe connection pooling, file post, and more."
optional = false
python-versions = ">=3.9"
python-versions = ">=3.10"
groups = ["main", "dev"]
files = [
{file = "urllib3-2.6.3-py3-none-any.whl", hash = "sha256:bf272323e553dfb2e87d9bfd225ca7b0f467b919d7bbd355436d3fd37cb0acd4"},
{file = "urllib3-2.6.3.tar.gz", hash = "sha256:1b62b6884944a57dbe321509ab94fd4d3b307075e0c2eae991ac71ee15ad38ed"},
{file = "urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897"},
{file = "urllib3-2.7.0.tar.gz", hash = "sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c"},
]
[package.extras]
@@ -5110,4 +5110,4 @@ migration = ["psycopg2-binary"]
[metadata]
lock-version = "2.1"
python-versions = ">=3.10,<3.13"
content-hash = "0879a6230bbc0d0e1d8d7d090e1572ba863078b18e0d78478baf2100aa245e08"
content-hash = "4dd6ccfc459064fb5335531d4ceb9c0f228279b1c95d0911e895232a51b90006"
+4
View File
@@ -51,6 +51,7 @@ dependencies = [
"pillow~=12.1.0",
"python-dotenv~=1.2.1",
"greenlet~=3.3.0",
"urllib3>=2.7.0",
]
[project.scripts]
@@ -86,6 +87,9 @@ dev = [
"pyinstrument>=5.1.2",
]
[tool.uv]
exclude-newer = "1 week"
[tool.poetry]
packages = [
{include = "lnbits"},
+60 -9
View File
@@ -13,14 +13,15 @@ async def test_asset_api_upload_list_update_and_delete(
client: AsyncClient,
user_headers_from: dict[str, str],
):
payload = get_png_bytes()
upload = await client.post(
"/api/v1/assets?public_asset=false",
headers={"Authorization": user_headers_from["Authorization"]},
files={"file": ("note.txt", b"hello world", "text/plain")},
files={"file": ("note.png", payload, "image/png")},
)
assert upload.status_code == 200
asset = upload.json()
assert asset["name"] == "note.txt"
assert asset["name"] == "note.png"
assert asset["is_public"] is False
page = await client.get("/api/v1/assets/paginated", headers=user_headers_from)
@@ -29,27 +30,30 @@ async def test_asset_api_upload_list_update_and_delete(
info = await client.get(f"/api/v1/assets/{asset['id']}", headers=user_headers_from)
assert info.status_code == 200
assert info.json()["name"] == "note.txt"
assert info.json()["name"] == "note.png"
data = await client.get(
f"/api/v1/assets/{asset['id']}/data", headers=user_headers_from
)
assert data.status_code == 200
assert data.content == b"hello world"
assert data.headers["content-disposition"] == 'inline; filename="note.txt"'
assert data.content == payload
assert data.headers["content-type"] == "image/png"
assert data.headers["content-disposition"] == 'inline; filename="note.png"'
assert data.headers["x-content-type-options"] == "nosniff"
assert data.headers["content-security-policy"].startswith("sandbox")
updated = await client.put(
f"/api/v1/assets/{asset['id']}",
headers=user_headers_from,
json={"name": "renamed.txt", "is_public": True},
json={"name": "renamed.png", "is_public": True},
)
assert updated.status_code == 200
assert updated.json()["name"] == "renamed.txt"
assert updated.json()["name"] == "renamed.png"
assert updated.json()["is_public"] is True
public_data = await client.get(f"/api/v1/assets/{asset['id']}/data")
assert public_data.status_code == 200
assert public_data.content == b"hello world"
assert public_data.content == payload
deleted = await client.delete(
f"/api/v1/assets/{asset['id']}", headers=user_headers_from
@@ -98,15 +102,51 @@ async def test_asset_api_enforces_visibility_and_supports_admin_updates(
assert admin_updated.json()["is_public"] is True
assert admin_updated.json()["name"] == "admin-visible.png"
image_data = await client.get(f"/api/v1/assets/{private_asset.id}/data")
assert image_data.status_code == 200
assert image_data.headers["content-type"] == "image/png"
assert image_data.headers["content-disposition"] == (
'inline; filename="admin-visible.png"'
)
assert image_data.headers["x-content-type-options"] == "nosniff"
thumbnail = await client.get(f"/api/v1/assets/{private_asset.id}/thumbnail")
assert thumbnail.status_code == 200
assert thumbnail.content
assert thumbnail.headers["content-type"] == "image/png"
assert thumbnail.headers["content-disposition"] == (
'inline; filename="admin-visible.png"'
)
@pytest.mark.anyio
async def test_asset_api_blocks_non_image_uploads(
client: AsyncClient,
user_headers_from: dict[str, str],
):
payload = (
b'<?xml version="1.0"?>'
b'<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform">'
b'<xsl:template match="/">'
b"<script>alert(1)</script>"
b"</xsl:template>"
b"</xsl:stylesheet>"
)
blocked = await client.post(
"/api/v1/assets",
headers={"Authorization": user_headers_from["Authorization"]},
files={"file": ("payload.xsl", payload, "text/xml")},
)
assert blocked.status_code == 400
assert blocked.json()["detail"] == "File type 'text/xml' not allowed."
@pytest.mark.anyio
async def test_asset_api_validates_uploads_and_missing_assets(
client: AsyncClient,
to_user,
user_headers_from: dict[str, str],
):
invalid = await client.post(
@@ -117,6 +157,15 @@ async def test_asset_api_validates_uploads_and_missing_assets(
assert invalid.status_code == 400
assert "not allowed" in invalid.json()["detail"]
fake_image_headers = await get_user_token_headers(client, to_user.id)
fake_image = await client.post(
"/api/v1/assets",
headers={"Authorization": fake_image_headers["Authorization"]},
files={"file": ("fake.png", b"<root></root>", "image/png")},
)
assert fake_image.status_code == 400
assert "does not match declared file type" in fake_image.json()["detail"]
missing = await client.delete(
f"/api/v1/assets/{uuid4().hex}",
headers=user_headers_from,
@@ -128,7 +177,9 @@ async def test_asset_api_validates_uploads_and_missing_assets(
stored = await create_user_asset(
"missing-user-check",
make_upload_file(b"content", filename="content.txt", content_type="text/plain"),
make_upload_file(
get_png_bytes(), filename="content.png", content_type="image/png"
),
is_public=True,
)
fetched = await get_user_asset("missing-user-check", stored.id)
+127 -19
View File
@@ -185,17 +185,10 @@ async def test_callback_api_handles_revolut_paid_events(mocker):
async def test_callback_api_handles_revolut_subscription_event(
mocker, settings: Settings
):
user = await create_user_account(
Account(
id=uuid4().hex,
username=f"user_{uuid4().hex[:8]}",
email=f"user_{uuid4().hex[:8]}@lnbits.com",
)
)
wallet = user.wallets[0]
payment = await create_wallet_invoice(
wallet.id, CreateInvoice(out=False, amount=15, memo="subscription")
)
wallet_id = "wallet_1"
payment = mocker.Mock()
payment.extra = {}
payment.msat = 925_000
settings.revolut_api_endpoint = "https://sandbox-merchant.revolut.com"
settings.revolut_api_secret_key = "revolut-secret"
@@ -209,7 +202,7 @@ async def test_callback_api_handles_revolut_subscription_event(
"current_cycle_id": "CYCLE_1",
"external_reference": json.dumps(
{
"wallet_id": wallet.id,
"wallet_id": wallet_id,
"tag": "members",
"subscription_request_id": "request_1",
"extra": {"link": "link-1", "customer_id": "customer_1"},
@@ -241,10 +234,14 @@ async def test_callback_api_handles_revolut_subscription_event(
"lnbits.core.views.callback_api.get_standalone_payment",
mocker.AsyncMock(side_effect=[None]),
)
create_fiat_invoice_mock = mocker.patch(
"lnbits.core.views.callback_api.create_fiat_invoice",
create_wallet_invoice_mock = mocker.patch(
"lnbits.core.views.callback_api.create_wallet_invoice",
mocker.AsyncMock(return_value=payment),
)
mocker.patch("lnbits.core.views.callback_api.service_fee_fiat", return_value=2)
update_payment_mock = mocker.patch(
"lnbits.core.views.callback_api.update_payment", mocker.AsyncMock()
)
fiat_status_mock = mocker.patch(
"lnbits.core.views.callback_api.check_fiat_status", mocker.AsyncMock()
)
@@ -256,16 +253,127 @@ async def test_callback_api_handles_revolut_subscription_event(
}
)
assert create_fiat_invoice_mock.await_count == 1
revolut_call = create_fiat_invoice_mock.await_args.kwargs
assert revolut_call["wallet_id"] == wallet.id
invoice = revolut_call["invoice_data"]
assert invoice.fiat_provider == "revolut"
assert create_wallet_invoice_mock.await_count == 1
called_wallet_id, invoice = create_wallet_invoice_mock.await_args.args
assert called_wallet_id == "wallet_1"
assert invoice.amount == 9.25
assert invoice.memo == "Revolut Members"
assert invoice.external_id == "SUBSCRIPTION_1"
assert invoice.internal is True
assert invoice.extra["fiat_method"] == "subscription"
assert invoice.extra["subscription"]["checking_id"] == "order_ORDER_SUB_1"
assert payment.fiat_provider == "revolut"
assert payment.fee == -2
assert payment.extra["fiat_checking_id"] == "order_ORDER_SUB_1"
assert payment.checking_id == "fiat_revolut_order_ORDER_SUB_1"
update_payment_mock.assert_awaited_once_with(
payment, "fiat_revolut_order_ORDER_SUB_1"
)
fiat_status_mock.assert_awaited_once_with(payment)
@pytest.mark.anyio
async def test_callback_api_handles_revolut_subscription_order_event(
mocker, settings: Settings
):
wallet_id = "wallet_1"
payment = mocker.Mock()
payment.extra = {}
payment.msat = 925_000
settings.revolut_api_endpoint = "https://sandbox-merchant.revolut.com"
settings.revolut_api_secret_key = "revolut-secret"
settings.revolut_api_version = "2026-04-20"
revolut_provider = RevolutWallet()
subscription = {
"id": "SUBSCRIPTION_1",
"state": "active",
"current_cycle_id": "CYCLE_1",
"external_reference": json.dumps(
{
"wallet_id": wallet_id,
"tag": "members",
"subscription_request_id": "request_1",
"extra": {"link": "link-1"},
"memo": "Revolut Members",
}
),
}
order = {
"id": "ORDER_SUB_1",
"type": "payment",
"state": "completed",
"amount": 925,
"currency": "USD",
"checkout_url": "https://checkout.revolut.com/payment-link/sub_1",
"channel_data": {
"subscription_id": "SUBSCRIPTION_1",
"subscription_cycle_id": "CYCLE_1",
},
}
get_order_mock = mocker.patch.object(
revolut_provider, "get_order", side_effect=[order, order]
)
get_subscription_mock = mocker.patch.object(
revolut_provider,
"get_subscription",
return_value=subscription,
)
mocker.patch.object(
revolut_provider,
"get_subscription_cycle",
return_value={"id": "CYCLE_1", "order_id": "ORDER_SUB_1"},
)
mocker.patch(
"lnbits.core.views.callback_api.get_fiat_provider",
mocker.AsyncMock(return_value=revolut_provider),
)
get_payment_mock = mocker.patch(
"lnbits.core.views.callback_api.get_standalone_payment",
mocker.AsyncMock(side_effect=[None, None]),
)
create_wallet_invoice_mock = mocker.patch(
"lnbits.core.views.callback_api.create_wallet_invoice",
mocker.AsyncMock(return_value=payment),
)
mocker.patch("lnbits.core.views.callback_api.service_fee_fiat", return_value=2)
update_payment_mock = mocker.patch(
"lnbits.core.views.callback_api.update_payment", mocker.AsyncMock()
)
fiat_status_mock = mocker.patch(
"lnbits.core.views.callback_api.check_fiat_status", mocker.AsyncMock()
)
await handle_revolut_event(
{
"event": "ORDER_COMPLETED",
"order_id": "ORDER_SUB_1",
}
)
assert get_payment_mock.await_count == 2
get_payment_mock.assert_any_await("fiat_revolut_order_ORDER_SUB_1")
assert get_order_mock.await_count == 2
assert [call.args for call in get_subscription_mock.await_args_list] == [
("SUBSCRIPTION_1",),
("SUBSCRIPTION_1",),
]
assert create_wallet_invoice_mock.await_count == 1
called_wallet_id, invoice = create_wallet_invoice_mock.await_args.args
assert called_wallet_id == "wallet_1"
assert invoice.amount == 9.25
assert invoice.memo == "Revolut Members"
assert invoice.external_id == "SUBSCRIPTION_1"
assert invoice.internal is True
assert invoice.extra["fiat_method"] == "subscription"
assert invoice.extra["subscription"]["checking_id"] == "order_ORDER_SUB_1"
assert payment.fiat_provider == "revolut"
assert payment.fee == -2
assert payment.extra["fiat_checking_id"] == "order_ORDER_SUB_1"
assert payment.checking_id == "fiat_revolut_order_ORDER_SUB_1"
update_payment_mock.assert_awaited_once_with(
payment, "fiat_revolut_order_ORDER_SUB_1"
)
fiat_status_mock.assert_awaited_once_with(payment)
-1
View File
@@ -1 +0,0 @@
98ae578877a3479bb0424d2e418b427a
-1
View File
@@ -1 +0,0 @@
6355d3c6c5df49dbb562a74f9deb19ce
+396 -13
View File
@@ -74,7 +74,9 @@ class MockHTTPClient:
@pytest.fixture(autouse=True)
def fiat_provider_test_settings(settings: Settings):
original_lnbits_running = settings.lnbits_running
original_allowed_currencies = settings.lnbits_allowed_currencies
original_fiat_providers_admin_only = settings.fiat_providers_admin_only
original_paypal_enabled = settings.paypal_enabled
original_square_enabled = settings.square_enabled
original_square_api_endpoint = settings.square_api_endpoint
@@ -94,11 +96,14 @@ def fiat_provider_test_settings(settings: Settings):
original_revolut_webhook_signing_secret = settings.revolut_webhook_signing_secret
original_revolut_limits = settings.revolut_limits.copy(deep=True)
settings.lnbits_allowed_currencies = []
settings.fiat_providers_admin_only = False
settings.paypal_enabled = False
settings.square_enabled = False
settings.revolut_enabled = False
yield
settings.lnbits_running = original_lnbits_running
settings.lnbits_allowed_currencies = original_allowed_currencies
settings.fiat_providers_admin_only = original_fiat_providers_admin_only
settings.paypal_enabled = original_paypal_enabled
settings.square_enabled = original_square_enabled
settings.square_api_endpoint = original_square_api_endpoint
@@ -215,6 +220,39 @@ async def test_create_wallet_fiat_invoice_allowed_users(
assert user.fiat_providers == ["revolut"]
@pytest.mark.anyio
async def test_fiat_providers_admin_only_default(to_user: User, settings: Settings):
original_admin_users = list(settings.lnbits_admin_users)
try:
settings.fiat_providers_admin_only = True
settings.stripe_enabled = True
user = await get_user(to_user.id)
assert user
assert user.fiat_providers == []
settings.lnbits_admin_users.append(to_user.id)
user = await get_user(to_user.id)
assert user
assert user.fiat_providers == ["stripe"]
finally:
settings.lnbits_admin_users = original_admin_users
@pytest.mark.anyio
async def test_create_wallet_fiat_invoice_admin_only_rejects_non_admin(
to_wallet: Wallet, settings: Settings
):
settings.fiat_providers_admin_only = True
settings.stripe_enabled = True
invoice_data = CreateInvoice(
unit="USD", amount=1.0, memo="Test", fiat_provider="stripe"
)
with pytest.raises(ValueError, match="available to admins only"):
await payments.create_fiat_invoice(to_wallet.id, invoice_data)
@pytest.mark.anyio
async def test_create_wallet_fiat_invoice_fiat_limits_fail(
to_wallet: Wallet, settings: Settings, mocker: MockerFixture
@@ -445,6 +483,7 @@ async def test_square_wallet_create_invoice(settings: Settings):
@pytest.mark.anyio
async def test_square_wallet_create_subscription(settings: Settings):
settings.lnbits_running = False
settings.square_api_endpoint = "https://connect.squareupsandbox.com"
settings.square_access_token = "square-token"
settings.square_location_id = "LOC123"
@@ -520,6 +559,7 @@ async def test_square_wallet_create_subscription(settings: Settings):
@pytest.mark.anyio
async def test_square_wallet_create_subscription_from_plan_id(settings: Settings):
settings.lnbits_running = False
settings.square_api_endpoint = "https://connect.squareupsandbox.com"
settings.square_access_token = "square-token"
settings.square_location_id = "LOC123"
@@ -808,6 +848,48 @@ async def test_revolut_wallet_create_invoice(settings: Settings):
assert payload["redirect_url"] == "https://lnbits.example/success"
@pytest.mark.anyio
async def test_revolut_wallet_create_invoice_uses_currency_minor_units(
settings: Settings,
):
settings.revolut_api_endpoint = "https://sandbox-merchant.revolut.com"
settings.revolut_api_secret_key = "revolut-secret"
settings.revolut_api_version = "2026-04-20"
wallet = RevolutWallet()
client = MockHTTPClient(
[
MockHTTPResponse(
json_data={
"id": "ORDER_JPY",
"checkout_url": "https://checkout.revolut.com/payment-link/jpy",
}
),
MockHTTPResponse(
json_data={
"id": "ORDER_KWD",
"checkout_url": "https://checkout.revolut.com/payment-link/kwd",
}
),
]
)
wallet.client = client # type: ignore[assignment]
await wallet.create_invoice(
amount=123,
payment_hash="hash_jpy",
currency="JPY",
)
await wallet.create_invoice(
amount=1.234,
payment_hash="hash_kwd",
currency="KWD",
)
assert client.calls[0][1]["json"]["amount"] == 123
assert client.calls[1][1]["json"]["amount"] == 1234
@pytest.mark.anyio
async def test_revolut_wallet_get_invoice_status(settings: Settings):
settings.revolut_api_endpoint = "https://sandbox-merchant.revolut.com"
@@ -834,6 +916,16 @@ async def test_revolut_wallet_create_subscription(settings: Settings):
wallet = RevolutWallet()
client = MockHTTPClient(
[
MockHTTPResponse(
json_data={
"customers": [
{
"id": "CUSTOMER123",
"email": "customer@example.com",
}
]
}
),
MockHTTPResponse(
json_data={
"id": "SUBSCRIPTION123",
@@ -854,7 +946,8 @@ async def test_revolut_wallet_create_subscription(settings: Settings):
wallet_id="wallet_1",
memo="Monthly Gold",
tag="gold",
extra={"customer_id": "CUSTOMER123", "link": "link-1"},
customer_email="customer@example.com",
extra={"link": "link-1"},
success_url="https://lnbits.example/subscription-success",
)
@@ -863,24 +956,312 @@ async def test_revolut_wallet_create_subscription(settings: Settings):
)
assert response.ok is True
assert response.subscription_request_id == "SUBSCRIPTION123"
assert response.subscription_request_id is not None
assert (
response.checkout_session_url
== "https://checkout.revolut.com/payment-link/sub_123"
)
assert client.calls[0][0] == "/api/subscriptions"
payload = client.calls[0][1]["json"]
assert client.calls[0][0] == "/api/customers"
assert client.calls[0][1]["params"] == {"limit": 500}
assert client.calls[0][1]["timeout"] == 30
assert client.calls[1][0] == "/api/subscriptions"
payload = client.calls[1][1]["json"]
assert payload["plan_variation_id"] == "PLAN_VARIATION_123"
assert payload["customer_id"] == "CUSTOMER123"
assert client.calls[1][1]["timeout"] == 30
assert client.calls[1][1]["headers"]["Idempotency-Key"] == (
response.subscription_request_id
)
assert payload["setup_order_redirect_url"] == (
"https://lnbits.example/subscription-success"
)
reference = json.loads(payload["external_reference"])
assert reference["wallet_id"] == "wallet_1"
assert reference["tag"] == "gold"
assert reference["subscription_request_id"] == response.subscription_request_id
assert reference["memo"] == "Monthly Gold"
assert reference["extra"]["customer_id"] == "CUSTOMER123"
assert client.calls[1][0] == "/api/orders/ORDER123"
assert reference["extra"]["link"] == "link-1"
assert client.calls[2][0] == "/api/orders/ORDER123"
@pytest.mark.anyio
async def test_revolut_wallet_create_subscription_uses_customer_email(
settings: Settings,
):
settings.revolut_api_endpoint = "https://sandbox-merchant.revolut.com"
settings.revolut_api_secret_key = "revolut-secret"
settings.revolut_api_version = "2026-04-20"
wallet = RevolutWallet()
client = MockHTTPClient(
[
MockHTTPResponse(
json_data={
"customers": [
{
"id": "CUSTOMER123",
"email": "customer@example.com",
}
]
}
),
MockHTTPResponse(
json_data={
"id": "SUBSCRIPTION123",
"setup_order_id": "ORDER123",
}
),
MockHTTPResponse(
json_data={
"id": "ORDER123",
"checkout_url": "https://checkout.revolut.com/payment-link/sub_123",
}
),
]
)
wallet.client = client # type: ignore[assignment]
payment_options = FiatSubscriptionPaymentOptions(
wallet_id="wallet_1",
customer_email="customer@example.com",
)
response = await wallet.create_subscription(
"PLAN_VARIATION_123", 1, payment_options
)
assert response.ok is True
assert client.calls[0][0] == "/api/customers"
assert client.calls[0][1]["params"] == {"limit": 500}
assert client.calls[0][1]["timeout"] == 30
assert client.calls[1][0] == "/api/subscriptions"
assert client.calls[1][1]["json"]["customer_id"] == "CUSTOMER123"
assert client.calls[1][1]["timeout"] == 30
assert client.calls[2][0] == "/api/orders/ORDER123"
assert client.calls[2][1]["timeout"] == 30
@pytest.mark.anyio
async def test_revolut_wallet_create_subscription_uses_paginated_customer_email(
settings: Settings,
):
settings.revolut_api_endpoint = "https://sandbox-merchant.revolut.com"
settings.revolut_api_secret_key = "revolut-secret"
settings.revolut_api_version = "2026-04-20"
wallet = RevolutWallet()
client = MockHTTPClient(
[
MockHTTPResponse(
json_data={
"next_page_token": "PAGE2",
"customers": [
{
"id": "OTHER_CUSTOMER",
"email": "other@example.com",
}
],
}
),
MockHTTPResponse(
json_data={
"customers": [
{
"id": "CUSTOMER123",
"email": "customer@example.com",
}
],
}
),
MockHTTPResponse(
json_data={
"id": "SUBSCRIPTION123",
"setup_order_id": "ORDER123",
}
),
MockHTTPResponse(
json_data={
"id": "ORDER123",
"checkout_url": "https://checkout.revolut.com/payment-link/sub_123",
}
),
]
)
wallet.client = client # type: ignore[assignment]
payment_options = FiatSubscriptionPaymentOptions(
wallet_id="wallet_1",
customer_email="customer@example.com",
)
response = await wallet.create_subscription(
"PLAN_VARIATION_123", 1, payment_options
)
assert response.ok is True
assert client.calls[0][0] == "/api/customers"
assert client.calls[0][1]["params"] == {"limit": 500}
assert client.calls[1][0] == "/api/customers"
assert client.calls[1][1]["params"] == {
"limit": 500,
"page_token": "PAGE2",
}
assert client.calls[1][1]["timeout"] == 30
assert client.calls[2][0] == "/api/subscriptions"
assert client.calls[2][1]["json"]["customer_id"] == "CUSTOMER123"
assert client.calls[3][0] == "/api/orders/ORDER123"
@pytest.mark.anyio
async def test_revolut_wallet_create_subscription_creates_customer(settings: Settings):
settings.revolut_api_endpoint = "https://sandbox-merchant.revolut.com"
settings.revolut_api_secret_key = "revolut-secret"
settings.revolut_api_version = "2026-04-20"
wallet = RevolutWallet()
client = MockHTTPClient(
[
MockHTTPResponse(
json_data={
"next_page_token": "PAGE2",
"customers": [
{
"id": "OTHER_CUSTOMER",
"email": "other@example.com",
}
],
}
),
MockHTTPResponse(json_data={"customers": []}),
MockHTTPResponse(json_data={"id": "CUSTOMER123"}),
MockHTTPResponse(
json_data={
"id": "SUBSCRIPTION123",
"setup_order_id": "ORDER123",
}
),
MockHTTPResponse(
json_data={
"id": "ORDER123",
"checkout_url": "https://checkout.revolut.com/payment-link/sub_123",
}
),
]
)
wallet.client = client # type: ignore[assignment]
payment_options = FiatSubscriptionPaymentOptions(
wallet_id="wallet_1",
customer_email="customer@example.com",
)
response = await wallet.create_subscription(
"PLAN_VARIATION_123", 1, payment_options
)
assert response.ok is True
assert client.calls[0][0] == "/api/customers"
assert client.calls[0][1]["params"] == {"limit": 500}
assert client.calls[1][0] == "/api/customers"
assert client.calls[1][1]["params"] == {
"limit": 500,
"page_token": "PAGE2",
}
assert client.calls[2][0] == "/api/customers"
assert client.calls[2][1]["json"] == {"email": "customer@example.com"}
assert client.calls[2][1]["timeout"] == 30
assert client.calls[3][0] == "/api/subscriptions"
assert client.calls[3][1]["json"]["customer_id"] == "CUSTOMER123"
assert client.calls[4][0] == "/api/orders/ORDER123"
@pytest.mark.anyio
async def test_revolut_wallet_create_subscription_stops_customer_lookup_after_20_pages(
settings: Settings,
):
settings.revolut_api_endpoint = "https://sandbox-merchant.revolut.com"
settings.revolut_api_secret_key = "revolut-secret"
settings.revolut_api_version = "2026-04-20"
wallet = RevolutWallet()
customer_pages = [
MockHTTPResponse(
json_data={
"next_page_token": f"PAGE{page + 2}",
"customers": [
{
"id": f"OTHER_CUSTOMER_{page}",
"email": f"other-{page}@example.com",
}
],
}
)
for page in range(20)
]
client = MockHTTPClient(
[
*customer_pages,
MockHTTPResponse(json_data={"id": "CUSTOMER123"}),
MockHTTPResponse(
json_data={
"id": "SUBSCRIPTION123",
"setup_order_id": "ORDER123",
}
),
MockHTTPResponse(
json_data={
"id": "ORDER123",
"checkout_url": "https://checkout.revolut.com/payment-link/sub_123",
}
),
]
)
wallet.client = client # type: ignore[assignment]
payment_options = FiatSubscriptionPaymentOptions(
wallet_id="wallet_1",
customer_email="customer@example.com",
)
response = await wallet.create_subscription(
"PLAN_VARIATION_123", 1, payment_options
)
assert response.ok is True
assert [call[0] for call in client.calls[:20]] == ["/api/customers"] * 20
assert client.calls[0][1]["params"] == {"limit": 500}
assert client.calls[19][1]["params"] == {
"limit": 500,
"page_token": "PAGE20",
}
assert client.calls[20][0] == "/api/customers"
assert client.calls[20][1]["json"] == {"email": "customer@example.com"}
assert client.calls[21][0] == "/api/subscriptions"
assert client.calls[21][1]["json"]["customer_id"] == "CUSTOMER123"
assert client.calls[22][0] == "/api/orders/ORDER123"
@pytest.mark.anyio
async def test_revolut_wallet_create_subscription_requires_customer_email(
settings: Settings,
):
settings.revolut_api_endpoint = "https://sandbox-merchant.revolut.com"
settings.revolut_api_secret_key = "revolut-secret"
settings.revolut_api_version = "2026-04-20"
wallet = RevolutWallet()
client = MockHTTPClient([])
wallet.client = client # type: ignore[assignment]
payment_options = FiatSubscriptionPaymentOptions(wallet_id="wallet_1")
response = await wallet.create_subscription(
"PLAN_VARIATION_123", 1, payment_options
)
assert response.ok is False
assert response.error_message == "Revolut subscriptions require customer_email."
assert client.calls == []
@pytest.mark.anyio
@@ -936,7 +1317,7 @@ async def test_revolut_wallet_create_webhook(mocker: MockerFixture):
(
"/api/webhooks",
{
"timeout": 15,
"timeout": 30,
},
),
(
@@ -946,7 +1327,7 @@ async def test_revolut_wallet_create_webhook(mocker: MockerFixture):
"url": "https://lnbits.example/api/v1/callback/revolut",
"events": REVOLUT_WEBHOOK_EVENTS,
},
"timeout": 15,
"timeout": 30,
},
),
]
@@ -986,7 +1367,7 @@ async def test_revolut_wallet_reuses_existing_webhook(mocker: MockerFixture):
(
"/api/webhooks",
{
"timeout": 15,
"timeout": 30,
},
)
]
@@ -1005,20 +1386,22 @@ async def test_revolut_wallet_rejects_local_webhook_url():
def test_check_revolut_signature():
payload = b'{"event":"ORDER_COMPLETED","order_id":"ORDER123"}'
timestamp = str(int(time.time()))
timestamp = str(int(time.time() * 1000))
secret = "revolut-secret"
sig = hmac.new(secret.encode(), payload, hashlib.sha256).hexdigest()
signed_payload = b"v1." + timestamp.encode() + b"." + payload
sig = "v1=" + hmac.new(secret.encode(), signed_payload, hashlib.sha256).hexdigest()
check_revolut_signature(payload, sig, timestamp, secret)
def test_check_revolut_signature_millisecond_timestamp():
def test_check_revolut_signature_rejects_payload_only_signature():
payload = b'{"event":"ORDER_COMPLETED","order_id":"ORDER123"}'
timestamp = str(int(time.time() * 1000))
secret = "revolut-secret"
sig = hmac.new(secret.encode(), payload, hashlib.sha256).hexdigest()
check_revolut_signature(payload, sig, timestamp, secret)
with pytest.raises(ValueError, match="signature verification failed"):
check_revolut_signature(payload, sig, timestamp, secret)
def test_check_revolut_signature_v1_header():
+91 -14
View File
@@ -15,7 +15,7 @@ from tests.helpers import make_upload_file
@pytest.mark.anyio
async def test_create_user_asset_validates_upload_constraints(
settings: Settings, mocker: MockerFixture
app, settings: Settings, mocker: MockerFixture
):
file_without_type = make_upload_file(b"hello", filename="a.txt", content_type=None)
with pytest.raises(ValueError, match="File must have a content type."):
@@ -31,6 +31,40 @@ async def test_create_user_asset_validates_upload_constraints(
):
await create_user_asset("user-1", bad_type, is_public=False)
xsl_upload = make_upload_file(
b"hello",
filename="style.xsl",
content_type="text/xml",
)
with pytest.raises(ValueError, match="File type 'text/xml' not allowed."):
await create_user_asset("user-1", xsl_upload, is_public=False)
original_allowed_mime_types = list(settings.lnbits_assets_allowed_mime_types)
try:
settings.lnbits_assets_allowed_mime_types = [
*original_allowed_mime_types,
"text/xml",
]
xsl_content = make_upload_file(
b'<stylesheet xmlns="http://www.w3.org/1999/XSL/Transform"></stylesheet>',
filename="style.xml",
content_type="text/xml",
)
with pytest.raises(ValueError, match="File type 'text/xml' not allowed."):
await create_user_asset("user-1", xsl_content, is_public=False)
finally:
settings.lnbits_assets_allowed_mime_types = original_allowed_mime_types
fake_image = make_upload_file(
b"<?xml version='1.0'?><root></root>",
filename="fake.png",
content_type="image/png",
)
with pytest.raises(
ValueError, match="Image file content does not match declared file type."
):
await create_user_asset("user-1", fake_image, is_public=False)
original_max_assets = settings.lnbits_max_assets_per_user
original_max_size = settings.lnbits_max_asset_size_mb
original_no_limit_users = list(settings.lnbits_assets_no_limit_users)
@@ -40,14 +74,14 @@ async def test_create_user_asset_validates_upload_constraints(
settings.lnbits_assets_no_limit_users = []
limited_user = await _create_user()
allowed_type = make_upload_file(
b"hello", filename="ok.txt", content_type="text/plain"
_png_bytes(), filename="ok.png", content_type="image/png"
)
await create_user_asset(limited_user, allowed_type, is_public=False)
blocked_by_count = make_upload_file(
b"again",
filename="again.txt",
content_type="text/plain",
_png_bytes(),
filename="again.png",
content_type="image/png",
)
with pytest.raises(ValueError, match="Max upload count of 1 exceeded."):
await create_user_asset(limited_user, blocked_by_count, is_public=False)
@@ -55,9 +89,9 @@ async def test_create_user_asset_validates_upload_constraints(
settings.lnbits_max_asset_size_mb = 0.000001
oversized_user = await _create_user()
large_file = make_upload_file(
b"0123456789",
filename="ok.txt",
content_type="text/plain",
_png_bytes(),
filename="ok.png",
content_type="image/png",
)
with pytest.raises(ValueError, match="File limit of 1e-06MB exceeded."):
await create_user_asset(oversized_user, large_file, is_public=False)
@@ -68,29 +102,66 @@ async def test_create_user_asset_validates_upload_constraints(
@pytest.mark.anyio
async def test_create_user_asset_success(mocker: MockerFixture):
async def test_create_user_asset_success(app, mocker: MockerFixture):
user_id = await _create_user()
mocker.patch(
"lnbits.core.services.assets.thumbnail_from_bytes",
return_value=None,
)
file = make_upload_file(b"hello", filename="hello.txt", content_type="text/plain")
contents = _png_bytes()
file = make_upload_file(contents, filename="hello.png", content_type="image/png")
asset = await create_user_asset(user_id, file, is_public=True)
stored = await get_user_asset(user_id, asset.id)
assert asset.id
assert asset.user_id == user_id
assert asset.name == "hello.txt"
assert asset.size_bytes == 5
assert asset.data == b"hello"
assert asset.name == "hello.png"
assert asset.size_bytes == len(contents)
assert asset.data == contents
assert asset.is_public is True
assert stored is not None
assert stored.id == asset.id
assert stored.data == b"hello"
assert stored.data == contents
assert await get_user_assets_count(user_id) == 1
@pytest.mark.anyio
async def test_create_user_asset_stores_detected_image_mime_type(app):
user_id = await _create_user()
buffer = BytesIO()
Image.new("RGB", (32, 32), color="blue").save(buffer, format="JPEG")
file = make_upload_file(
buffer.getvalue(), filename="photo.jpg", content_type="image/jpg"
)
asset = await create_user_asset(user_id, file, is_public=True)
stored = await get_user_asset(user_id, asset.id)
assert asset.mime_type == "image/jpeg"
assert stored is not None
assert stored.mime_type == "image/jpeg"
@pytest.mark.anyio
async def test_create_user_asset_rejects_mismatched_image_content(app):
user_id = await _create_user()
buffer = BytesIO()
Image.new("RGB", (32, 32), color="blue").save(buffer, format="JPEG")
file = make_upload_file(
buffer.getvalue(), filename="photo.png", content_type="image/png"
)
with pytest.raises(
ValueError,
match=(
"Image file content does not match declared file type. "
"Declared: 'image/png', detected: 'image/jpeg'."
),
):
await create_user_asset(user_id, file, is_public=False)
def test_thumbnail_from_bytes_success_and_failure():
image = Image.new("RGB", (512, 512), color="red")
buffer = BytesIO()
@@ -107,3 +178,9 @@ async def _create_user() -> str:
user_id = uuid4().hex
await create_account(Account(id=user_id, username=f"user_{user_id[:8]}"))
return user_id
def _png_bytes() -> bytes:
buffer = BytesIO()
Image.new("RGB", (32, 32), color="green").save(buffer, format="PNG")
return buffer.getvalue()
Generated
+490 -461
View File
File diff suppressed because it is too large Load Diff