What changed, and why it matters
This commit adds a new 'File Download' paywall feature to the LNbits Paywall extension. It lets sellers charge for access to files hosted elsewhere, with the server fetching the file on behalf of paying customers. The change also introduces paywall editing, switches some endpoints to require admin keys, and adds a WebSocket for real-time payment confirmation. There are some security-relevant design choices, but no clear vulnerability is directly introduced by the patch itself.
Review the file-download feature for SSRF and header-injection risks before deploying. Restrict allowed URL schemes (e.g., http/https only), validate or block internal/reserved hosts and IP ranges, and sanitize or restrict custom HTTP headers. Consider adding per-paywall download limits and logging of outbound fetches. Verify that the WebSocket queue lifecycle does not leak entries on errors or disconnects. No immediate emergency patch is indicated by the diff alone, but a security-focused code review of the new download path is warranted.
Security signals we found
Server-Side Request Forgery (SSRF) risk: `_file_streamer` fetches user-controlled `file_config.url` with user-controlled `file_config.headers` from the server, potentially allowing internal network probing or credential exfiltration if headers/URL are attacker-controlled.
Payment-hash reuse across paywalls is mitigated: `_is_payment_made` now checks `payment.extra.get('id')` matches the requested paywall ID.
Authorization elevation: create/update/delete now require admin key instead of any wallet key.
WebSocket listener stores queues in a global `paid_invoices` dict keyed by `payment_hash`; no cleanup on disconnect before queue creation could leak entries, though `finally` closes the socket.
No input validation on `file_config.url` scheme, host, or header names/values.
No rate limiting or download-count cap on paid file downloads.
Version placeholder `{version}` is interpolated into the URL via `str.format`, which could be abused if the URL contains other braces, but this is a minor formatting issue rather than a clear exploit.
Evidence from the diff
The commit extends the paywall extension with a new PaywallConfig/PaywallFileConfig model, CRUD update support, UI for file downloads, and new API endpoints. Key backend changes include: a PATCH/PUT update endpoint, a /download/{paywall_id} endpoint that streams remote files after payment verification, a HEAD endpoint for pre-download checks, a WebSocket for paid-invoice notifications, and a background task listening for invoice payments. The server performs outbound HTTP requests to user-supplied URLs with user-supplied headers on behalf of downloaders. Authentication for create/update/delete is tightened from get_key_type to require_admin_key.
Changed components
LNbits Paywall extension backend (views_api.py, crud.py, models.py, tasks.py, __init__.py)LNbits Paywall extension frontend (templates/paywall/index.html, templates/paywall/display.html)README.mdInspect captured patch +561 / −108
### README.md
@@ -1,4 +1,5 @@
# Paywall - <small>[LNbits](https://github.com/lnbits/lnbits) extension</small>
+
<small>For more about LNBits extension check [this tutorial](https://github.com/lnbits/lnbits/wiki/LNbits-Extensions)</small>
## Hide content behind a paywall, a user has to pay some amount to access your hidden content
### __init__.py
@@ -1,7 +1,11 @@
+import asyncio
+from typing import List
from fastapi import APIRouter
+from asyncio import Queue, Task
from lnbits.db import Database
from lnbits.helpers import template_renderer
+from lnbits.tasks import catch_everything_and_restart
db = Database("ext_paywall")
@@ -19,5 +23,15 @@ def paywall_renderer():
return template_renderer(["paywall/templates"])
-from .views import * # noqa: F401,F403
-from .views_api import * # noqa: F401,F403
+scheduled_tasks: List[Task] = []
+
+
+from .tasks import wait_for_paid_invoices, paid_invoices # noqa: F401,F403,E402
+from .views import * # noqa: F401,F403,E402
+from .views_api import * # noqa: F401,F403,E402
+
+
+def paywall_start():
+ loop = asyncio.get_event_loop()
+ task1 = loop.create_task(catch_everything_and_restart(wait_for_paid_invoices))
+ scheduled_tasks.append(task1)
### crud.py
@@ -1,3 +1,4 @@
+import json
from typing import List, Optional, Union
from lnbits.helpers import urlsafe_short_hash
@@ -10,8 +11,9 @@ async def create_paywall(wallet_id: str, data: CreatePaywall) -> Paywall:
paywall_id = urlsafe_short_hash()
await db.execute(
"""
- INSERT INTO paywall.paywalls (id, wallet, url, memo, description, amount, remembers)
- VALUES (?, ?, ?, ?, ?, ?, ?)
+ INSERT INTO paywall.paywalls
+ (id, wallet, url, memo, description, amount, remembers, extras)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""",
(
paywall_id,
@@ -21,6 +23,7 @@ async def create_paywall(wallet_id: str, data: CreatePaywall) -> Paywall:
data.description,
data.amount,
int(data.remembers),
+ json.dumps(data.extras.dict()) if data.extras else None,
),
)
@@ -29,6 +32,32 @@ async def create_paywall(wallet_id: str, data: CreatePaywall) -> Paywall:
return paywall
+async def update_paywall(id: str, wallet_id: str, data: CreatePaywall) -> Paywall:
+ await db.execute(
+ """
+ UPDATE paywall.paywalls
+ SET (wallet, url, memo, description, amount, remembers, extras) =
+ (?, ?, ?, ?, ?, ?, ?)
+ WHERE id = ? AND wallet = ?
+ """,
+ (
+ wallet_id,
+ data.url,
+ data.memo,
+ data.description,
+ data.amount,
+ int(data.remembers),
+ json.dumps(data.extras.dict()) if data.extras else None,
+ id,
+ wallet_id,
+ ),
+ )
+
+ paywall = await get_paywall(id)
+ assert paywall, "Updated paywall couldn't be retrieved"
+ return paywall
+
+
async def get_paywall(paywall_id: str) -> Optional[Paywall]:
row = await db.fetchone(
"SELECT * FROM paywall.paywalls WHERE id = ?", (paywall_id,)
### models.py
@@ -6,12 +6,27 @@
from pydantic import BaseModel
+class PaywallFileConfig(BaseModel):
+ url: str
+ headers: dict[str, str]
+ # todo: nice to have:
+ # expiration_time: Optional[int]
+ # max_number_of_downloads: Optional[int]
+
+
+class PaywallConfig(BaseModel):
+ # possible types: 'url' and 'file'
+ type: Optional[str] = "url"
+ file_config: Optional[PaywallFileConfig] = None
+
+
class CreatePaywall(BaseModel):
url: str = Query(...)
memo: str = Query(...)
description: str = Query(None)
amount: int = Query(..., ge=0)
remembers: bool = Query(...)
+ extras: Optional[PaywallConfig] = None
class CreatePaywallInvoice(BaseModel):
@@ -31,11 +46,13 @@ class Paywall(BaseModel):
amount: int
time: int
remembers: bool
- extras: Optional[dict]
+ extras: Optional[PaywallConfig] = PaywallConfig()
@classmethod
def from_row(cls, row: Row) -> "Paywall":
data = dict(row)
data["remembers"] = bool(data["remembers"])
- data["extras"] = json.loads(data["extras"]) if data["extras"] else None
+ data["extras"] = (
+ PaywallConfig(**json.loads(data["extras"])) if data["extras"] else None
+ )
return cls(**data)
### tasks.py
@@ -0,0 +1,24 @@
+from asyncio import Queue
+
+
+from lnbits.core.models import Payment
+from lnbits.tasks import register_invoice_listener
+
+paid_invoices: dict[str, Queue] = {}
+
+
+async def wait_for_paid_invoices():
+ invoice_queue = Queue()
+ register_invoice_listener(invoice_queue)
+
+ while True:
+ payment = await invoice_queue.get()
+ await on_invoice_paid(payment)
+
+
+async def on_invoice_paid(payment: Payment) -> None:
+ if payment.extra.get("tag") != "paywall":
+ return
+
+ if payment.payment_hash in paid_invoices:
+ await paid_invoices[payment.payment_hash].put(payment)
### templates/paywall/display.html
@@ -53,7 +53,7 @@ <h5 class="text-subtitle1 q-mt-none q-mb-sm">{{ paywall.memo }}</h5>
<q-separator class="q-my-lg"></q-separator>
<p>
You can access the URL behind this paywall:<br />
- <strong>{% raw %}{{ redirectUrl }}{% endraw %}</strong>
+ <strong style="word-break: break-all;">{% raw %}{{ redirectUrl }}{% endraw %}</strong>
</p>
<div class="row q-mt-lg">
<q-btn outline color="grey" type="a" :href="redirectUrl"
### templates/paywall/index.html
@@ -4,7 +4,7 @@
<div class="col-12 col-md-8 col-lg-7 q-gutter-y-md">
<q-card>
<q-card-section>
- <q-btn unelevated color="primary" @click="formDialog.show = true"
+ <q-btn unelevated color="primary" @click="showPaywallDialog()"
>New paywall</q-btn
>
</q-card-section>
@@ -61,6 +61,15 @@ <h5 class="text-subtitle1 q-my-none">Paywalls</h5>
:href="props.row.url"
target="_blank"
></q-btn>
+ <q-btn
+ @click="editPaywall(props.row.id)"
+ unelevated
+ dense
+ size="xs"
+ icon="edit"
+ :color="($q.dark.isActive) ? 'grey-7' : 'grey-5'"
+ class="q-ml-sm"
+ ></q-btn>
</q-td>
<q-td v-for="col in props.cols" :key="col.name" :props="props">
{{ col.value }}
@@ -98,8 +107,8 @@ <h6 class="text-subtitle1 q-my-none">
</div>
<q-dialog v-model="formDialog.show" position="top">
- <q-card class="q-pa-lg q-pt-xl lnbits__dialog-card">
- <q-form @submit="createPaywall" class="q-gutter-md">
+ <q-card v-if="formDialog.show" class="q-pa-lg q-pt-xl lnbits__dialog-card">
+ <q-form @submit="createoOrUpdatePaywall" class="q-gutter-md">
<q-select
filled
dense
@@ -109,27 +118,14 @@ <h6 class="text-subtitle1 q-my-none">
label="Wallet *"
>
</q-select>
- <q-input
- filled
- dense
- v-model.trim="formDialog.data.url"
- type="url"
- label="Redirect URL *"
- ></q-input>
+
<q-input
filled
dense
v-model.trim="formDialog.data.memo"
label="Title *"
placeholder="LNbits paywall"
></q-input>
- <q-input
- filled
- dense
- autogrow
- v-model.trim="formDialog.data.description"
- label="Description"
- ></q-input>
<q-input
filled
dense
@@ -138,32 +134,135 @@ <h6 class="text-subtitle1 q-my-none">
label="Amount (sat) *"
hint="This is the minimum amount users can pay/donate."
></q-input>
- <q-list>
- <q-item tag="label" class="rounded-borders">
- <q-item-section avatar>
- <q-checkbox
- v-model="formDialog.data.remembers"
- color="primary"
- ></q-checkbox>
- </q-item-section>
- <q-item-section>
- <q-item-label>Remember payments</q-item-label>
- <q-item-label caption
- >A succesful payment will be registered in the browser's
- storage, so the user doesn't need to pay again to access the
- URL.</q-item-label
+ <q-select
+ filled
+ dense
+ emit-value
+ v-model="formDialog.data.type"
+ :options="paywallTypeOptions"
+ label="Paywall Type"
+ >
+ </q-select>
+ <div v-if="formDialog.data.type.id == 'url'">
+ <q-input
+ filled
+ dense
+ v-model.trim="formDialog.data.url"
+ type="url"
+ label="URL *"
+ ></q-input>
+ </div>
+ <div v-else-if="formDialog.data.type.id == 'file'">
+ <q-input
+ filled
+ dense
+ v-model.trim="formDialog.data.fileUrl"
+ type="url"
+ label="File URL *"
+ hint="This is the location of the file. The client will never have direct access to it."
+ class="q-mb-sm"
+ ></q-input>
+ <div class="row q-mb-sm">
+ <div class="col-1">
+ <q-btn icon="info" flat size="sm"></q-btn>
+ </div>
+ <div class="col-11">
+ <small class=""
+ >An optional `{version}` placeholder can be used in the URL.
+ Example:
+ 'https://api.github.com/repos/lnbits/paywall/zipball/{version}'</small
>
- </q-item-section>
- </q-item>
- </q-list>
+ </div>
+ </div>
+ <div class="row q-ml-md q-mb-sm q-mt-sm">
+ <div class="col-12">
+ <div>
+ <q-btn
+ icon="add"
+ label="Add Http Header"
+ @click="addFileHttpHeader"
+ size="sm"
+ unelevated
+ color="secondary"
+ class="float-right"
+ ></q-btn>
+ </div>
+ </div>
+ </div>
+ <div
+ v-for="(header, index) in formDialog.data.headers"
+ class="row q-mb-sm q-ml-md"
+ >
+ <div class="col-5">
+ <q-input
+ filled
+ dense
+ v-model.trim="header.key"
+ label="Key"
+ ></q-input>
+ </div>
+ <div class="col-5">
+ <q-input
+ filled
+ dense
+ v-model.trim="header.value"
+ label="Value"
+ class="q-pl-sm"
+ ></q-input>
+ </div>
+ <div class="col-2">
+ <q-btn
+ @click="removeFileHttpHeader(index)"
+ icon="clear"
+ size="sm"
+ unelevated
+ color="primary"
+ class="float-right q-mt-sm"
+ ></q-btn>
+ </div>
+ </div>
+ </div>
+ <q-toggle
+ label="Advanced"
+ v-model="formDialog.showAdvanced"
+ class="q-mt-md"
+ ></q-toggle>
+ <div v-if="formDialog.showAdvanced">
+ <q-input
+ filled
+ dense
+ autogrow
+ v-model.trim="formDialog.data.description"
+ label="Description"
+ ></q-input>
+
+ <q-list>
+ <q-item tag="label" class="rounded-borders">
+ <q-item-section avatar>
+ <q-checkbox
+ v-model="formDialog.data.remembers"
+ color="primary"
+ ></q-checkbox>
+ </q-item-section>
+ <q-item-section>
+ <q-item-label>Remember payments</q-item-label>
+ <q-item-label caption
+ >A succesful payment will be registered in the browser's
+ storage, so the user doesn't need to pay again to access the
+ URL.</q-item-label
+ >
+ </q-item-section>
+ </q-item>
+ </q-list>
+ </div>
<div class="row q-mt-lg">
<q-btn
unelevated
color="primary"
- :disable="formDialog.data.amount == null || formDialog.data.amount < 0 || formDialog.data.url == null || formDialog.data.memo == null"
+ :disable="!isValidForm"
type="submit"
- >Create paywall</q-btn
- >
+ :label="formDialog.data.id ? 'Update Paywall' : 'Create paywall'"
+ ></q-btn>
<q-btn v-close-popup flat color="grey" class="q-ml-auto"
>Cancel</q-btn
>
@@ -181,6 +280,14 @@ <h6 class="text-subtitle1 q-my-none">
)
obj.fsat = new Intl.NumberFormat(LOCALE).format(obj.amount)
obj.displayUrl = ['/paywall/', obj.id].join('')
+ obj.type = obj.extras?.type
+ obj.fileUrl = obj.extras?.file_config?.url
+ if (obj.extras?.file_config?.headers) {
+ obj.headers = Object.entries(obj.extras?.file_config?.headers).map(h => ({
+ key: h[0],
+ value: h[1]
+ }))
+ }
return obj
}
@@ -224,13 +331,56 @@ <h6 class="text-subtitle1 q-my-none">
},
formDialog: {
show: false,
- data: {
- remembers: false
+ showAdvanced: false,
+ data: null
+ },
+ paywallTypeOptions: [
+ {id: 'url', label: 'Redirect URL'},
+ {id: 'file', label: 'File Download'}
+ ]
+ }
+ },
+ computed: {
+ extras: function () {
+ const type = this.formDialog.data.type.id
+ let file_config = null
+ if (type === 'file') {
+ file_config = {
+ url: this.formDialog.data.fileUrl,
+ headers: this.formDialog.data.headers
+ .filter(v => !!v.key)
+ .reduce((a, h) => {
+ a[h.key] = h.value
+ return a
+ }, {})
}
}
+ return {type, file_config}
+ },
+ isValidForm: function () {
+ const url =
+ this.formDialog.data.type.id === 'url'
+ ? this.formDialog.data.url
+ : this.formDialog.data.fileUrl
+
+ return (
+ url &&
+ this.formDialog.data.amount &&
+ this.formDialog.data.amount >= 0 &&
+ this.formDialog.data.memo
+ )
}
},
methods: {
+ emptyPaywall: function () {
+ return {
+ remembers: false,
+ type: this.paywallTypeOptions[0],
+ url: null,
+ fileUrl: null,
+ headers: []
+ }
+ },
getPaywalls: function () {
var self = this
@@ -246,34 +396,56 @@ <h6 class="text-subtitle1 q-my-none">
})
})
},
- createPaywall: function () {
- var data = {
- url: this.formDialog.data.url,
- memo: this.formDialog.data.memo,
- amount: this.formDialog.data.amount,
- description: this.formDialog.data.description,
- remembers: this.formDialog.data.remembers
- }
- var self = this
+ showPaywallDialog: function (paywallData) {
+ this.formDialog.show = true
+ this.formDialog.data = paywallData || this.emptyPaywall()
+ },
+ createoOrUpdatePaywall: async function () {
+ try {
+ const paywall = {
+ url: this.formDialog.data.url || '',
+ memo: this.formDialog.data.memo,
+ amount: this.formDialog.data.amount,
+ description: this.formDialog.data.description,
+ remembers: this.formDialog.data.remembers,
+ extras: this.extras
+ }
- LNbits.api
- .request(
- 'POST',
- '/paywall/api/v1/paywalls',
- _.findWhere(this.g.user.wallets, {id: this.formDialog.data.wallet})
- .inkey,
- data
+ const paywallId = this.formDialog.data.id
+ let method = 'POST'
+ let path = '/paywall/api/v1/paywalls'
+ const adminkey = _.findWhere(this.g.user.wallets, {
+ id: this.formDialog.data.wallet
+ }).adminkey
+
+ if (paywallId) {
+ method = 'PATCH'
+ path = `/paywall/api/v1/paywalls/${paywallId}`
+ }
+
+ const {data} = await LNbits.api.request(
+ method,
+ path,
+ adminkey,
+ paywall
)
- .then(function (response) {
- self.paywalls.push(mapPaywall(response.data))
- self.formDialog.show = false
- self.formDialog.data = {
- remembers: false
- }
- })
- .catch(function (error) {
- LNbits.utils.notifyApiError(error)
- })
+
+ this.paywalls = this.paywalls.filter(p => p.id !== data.id)
+ this.paywalls.unshift(mapPaywall(data))
+
+ this.formDialog.show = false
+ this.formDialog.data = this.emptyPaywall()
+ } catch (error) {
+ LNbits.utils.notifyApiError(error)
+ }
+ },
+ editPaywall: function (paywallId) {
+ let paywall = this.paywalls.find(p => p.id === paywallId) || {}
+ paywall = {...this.emptyPaywall(), ...paywall}
+ paywall.type =
+ this.paywallTypeOptions.find(p => paywall.type === p.id) ||
+ this.paywallTypeOptions[0]
+ this.showPaywallDialog(paywall)
},
deletePaywall: function (paywallId) {
var self = this
@@ -286,7 +458,7 @@ <h6 class="text-subtitle1 q-my-none">
.request(
'DELETE',
'/paywall/api/v1/paywalls/' + paywallId,
- _.findWhere(self.g.user.wallets, {id: paywall.wallet}).inkey
+ _.findWhere(self.g.user.wallets, {id: paywall.wallet}).adminkey
)
.then(function (response) {
self.paywalls = _.reject(self.paywalls, function (obj) {
@@ -298,6 +470,15 @@ <h6 class="text-subtitle1 q-my-none">
})
})
},
+ addFileHttpHeader: function () {
+ this.formDialog.data.headers = this.formDialog.data.headers || []
+ this.formDialog.data.headers.push({key: '', value: ''})
+ },
+ removeFileHttpHeader: function (index) {
+ if (index < this.formDialog.data.headers.length) {
+ this.formDialog.data.headers.splice(index, 1)
+ }
+ },
exportCSV: function () {
LNbits.utils.exportCSV(this.paywallsTable.columns, this.paywalls)
}
### views_api.py
@@ -1,15 +1,32 @@
+from asyncio import Queue
from http import HTTPStatus
+import json
+from typing import Optional
+from urllib import request
-from fastapi import Depends, Query
+from fastapi import Depends, Query, Request, Response, WebSocket, WebSocketDisconnect
from fastapi.exceptions import HTTPException
+from fastapi.responses import StreamingResponse
+from loguru import logger
-from lnbits.core.crud import get_user, get_wallet
+from lnbits.core.crud import get_standalone_payment, get_user
from lnbits.core.services import check_transaction_status, create_invoice
-from lnbits.decorators import WalletTypeInfo, get_key_type
+from lnbits.decorators import (
+ WalletTypeInfo,
+ check_admin,
+ get_key_type,
+ require_admin_key,
+)
-from . import paywall_ext
-from .crud import create_paywall, delete_paywall, get_paywall, get_paywalls
-from .models import CheckPaywallInvoice, CreatePaywall, CreatePaywallInvoice
+from . import paywall_ext, paid_invoices, scheduled_tasks
+from .crud import (
+ create_paywall,
+ delete_paywall,
+ get_paywall,
+ get_paywalls,
+ update_paywall,
+)
+from .models import CheckPaywallInvoice, CreatePaywall, CreatePaywallInvoice, Paywall
@paywall_ext.get("/api/v1/paywalls")
@@ -27,15 +44,24 @@ async def api_paywalls(
@paywall_ext.post("/api/v1/paywalls")
async def api_paywall_create(
- data: CreatePaywall, wallet: WalletTypeInfo = Depends(get_key_type)
+ data: CreatePaywall, wallet: WalletTypeInfo = Depends(require_admin_key)
):
paywall = await create_paywall(wallet_id=wallet.wallet.id, data=data)
return paywall.dict()
+@paywall_ext.patch("/api/v1/paywalls/{id}")
+@paywall_ext.put("/api/v1/paywalls/{id}")
+async def api_paywall_update(
+ id: str, data: CreatePaywall, wallet: WalletTypeInfo = Depends(require_admin_key)
+):
+ paywall = await update_paywall(id=id, wallet_id=wallet.wallet.id, data=data)
+ return paywall.dict()
+
+
@paywall_ext.delete("/api/v1/paywalls/{paywall_id}")
async def api_paywall_delete(
- paywall_id: str, wallet: WalletTypeInfo = Depends(get_key_type)
+ paywall_id: str, wallet: WalletTypeInfo = Depends(require_admin_key)
):
paywall = await get_paywall(paywall_id)
@@ -54,52 +80,213 @@ async def api_paywall_delete(
@paywall_ext.post("/api/v1/paywalls/invoice/{paywall_id}")
-async def api_paywall_create_invoice(
- data: CreatePaywallInvoice, paywall_id: str
-):
- paywall = await get_paywall(paywall_id)
- assert paywall
- if data.amount < paywall.amount:
- raise HTTPException(
- status_code=HTTPStatus.BAD_REQUEST,
- detail=f"Minimum amount is {paywall.amount} sat.",
- )
+async def api_paywall_create_invoice(data: CreatePaywallInvoice, paywall_id: str):
try:
- amount = data.amount if data.amount > paywall.amount else paywall.amount
- payment_hash, payment_request = await create_invoice(
- wallet_id=paywall.wallet,
- amount=amount,
- memo=f"{paywall.memo}",
- extra={"tag": "paywall"},
- )
+ paywall = await get_paywall(paywall_id)
+ assert paywall, "Paywall not found"
+ return await _create_paywall_invoice(paywall, data.amount)
+ except AssertionError as e:
+ raise HTTPException(HTTPStatus.BAD_REQUEST, str(e))
except Exception as e:
raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=str(e))
- return {"payment_hash": payment_hash, "payment_request": payment_request}
+
+@paywall_ext.get("/api/v1/paywalls/invoice/{paywall_id}")
+async def api_paywall_create_fixed_amount_invoice(
+ paywall_id: str, amount: Optional[int] = None
+):
+ try:
+ paywall = await get_paywall(paywall_id)
+ assert paywall, "Paywall not found"
+
+ if not amount:
+ return {"amount": paywall.amount}
+
+ return await _create_paywall_invoice(paywall, amount)
+ except AssertionError as e:
+ raise HTTPException(HTTPStatus.BAD_REQUEST, str(e))
+ except Exception as e:
+ raise HTTPException(
+ status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
+ detail="Cannot create invoice.",
+ )
@paywall_ext.post("/api/v1/paywalls/check_invoice/{paywall_id}")
async def api_paywal_check_invoice(
- data: CheckPaywallInvoice, paywall_id: str
+ request: Request, data: CheckPaywallInvoice, paywall_id: str
):
paywall = await get_paywall(paywall_id)
- payment_hash = data.payment_hash
if not paywall:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="Paywall does not exist."
)
+ paid_amount = await _is_payment_made(paywall, data.payment_hash)
+
+ url = (
+ paywall.url
+ or f"{request.base_url}paywall/download/{paywall.id}"
+ + f"?payment_hash={data.payment_hash}&version=__your_version_here___"
+ )
+
+ if paid_amount:
+ return {"paid": True, "url": url, "remembers": paywall.remembers}
+
+ return {"paid": False}
+
+
+@paywall_ext.websocket("/api/v1/paywalls/invoice/{paywall_id}/{payment_hash}")
+async def websocket_connect(ws: WebSocket, paywall_id: str, payment_hash: str) -> None:
+ try:
+ await ws.accept()
+
+ paywall = await get_paywall(paywall_id)
+ if not paywall:
+ await ws.send_text(json.dumps({"paid": False}))
+ return
+
+ payment = await get_standalone_payment(
+ checking_id_or_hash=payment_hash,
+ incoming=True,
+ )
+ if not payment:
+ await ws.send_text(json.dumps({"paid": False}))
+ return
+
+ if payment.extra.get("tag", None) != "paywall":
+ await ws.send_text(json.dumps({"paid": False}))
+ return
+
+ if not payment.pending:
+ await ws.send_text(json.dumps({"paid": True}))
+ return
+
+ paid_invoices[payment.payment_hash] = Queue()
+ paid_payment = await paid_invoices[payment.payment_hash].get()
+ del paid_invoices[paid_payment.payment_hash]
+ await ws.send_text(json.dumps({"paid": True}))
+
+ except WebSocketDisconnect as e:
+ logger.warning(e)
+ finally:
+ await ws.close()
+
+
+@paywall_ext.get("/download/{paywall_id}")
+async def api_paywall_download_file(
+ paywall_id: str, version: Optional[str] = None, payment_hash: Optional[str] = None
+):
+ try:
+ logger.info(f"Prepare download for paywall '{paywall_id}'.")
+ assert payment_hash, "Payment hash is missing."
+
+ paywall = await get_paywall(paywall_id)
+ assert paywall, "Paywall does not exist."
+ assert paywall.extras, "Paywall invalid."
+ assert paywall.extras.type == "file", "Paywall has not file to be downloaded."
+
+ file_config = paywall.extras.file_config
+ assert file_config, "Cannot find file to download"
+
+ paid_amount = await _is_payment_made(paywall, payment_hash)
+
+ assert paid_amount, "Invoice not paid."
+ logger.info(
+ f"Downloading file for paywall '{paywall_id}'." + f" Version: '{version}'."
+ )
+
+ headers = {"Content-Disposition": f'attachment; filename="{paywall.memo}"'}
+ if version:
+ file_config.url = file_config.url.format(version=version)
+ return StreamingResponse(
+ content=_file_streamer(file_config.url, file_config.headers),
+ headers=headers,
+ )
+ except AssertionError as e:
+ raise HTTPException(HTTPStatus.BAD_REQUEST, str(e))
+ except Exception as e:
+ logger.error(e)
+ raise HTTPException(HTTPStatus.INTERNAL_SERVER_ERROR, "Cannot download file.")
+ finally:
+ logger.info(
+ f"Downloaded file for paywall '{paywall_id}'." + f" Version: '{version}'."
+ )
+
+
+@paywall_ext.head("/download/{paywall_id}")
+async def api_paywall_check_file(paywall_id: str, payment_hash: Optional[str] = None):
+ try:
+ assert payment_hash, "Payment hash is missing."
+
+ paywall = await get_paywall(paywall_id)
+ assert paywall, "Paywall does not exist."
+ assert paywall.extras, "Paywall invalid."
+ assert paywall.extras.type == "file", "Paywall has not file to be downloaded."
+
+ file_config = paywall.extras.file_config
+ assert file_config, "Cannot find file to download"
+
+ paid_amount = await _is_payment_made(paywall, payment_hash)
+
+ assert paid_amount, "Invoice not paid."
+
+ return Response(
+ status_code=HTTPStatus.CREATED,
+ headers={"paid_sats": f"{int(paid_amount / 1000)}"},
+ )
+
+ except AssertionError as e:
+ raise HTTPException(HTTPStatus.BAD_REQUEST, str(e))
+ except Exception as e:
+ logger.error(e)
+ raise HTTPException(HTTPStatus.INTERNAL_SERVER_ERROR, "Cannot download file.")
+
+
+@paywall_ext.delete("/api/v1", status_code=HTTPStatus.OK)
+async def api_stop(wallet: WalletTypeInfo = Depends(check_admin)):
+ for t in scheduled_tasks:
+ try:
+ t.cancel()
+ except Exception as ex:
+ logger.warning(ex)
+
+ return {"success": True}
+
+
+async def _file_streamer(url, headers):
+ with request.urlopen(request.Request(url=url, headers=headers)) as dl_file:
+ yield dl_file.read()
+
+
+async def _create_paywall_invoice(paywall: Paywall, amount: int):
+ assert amount >= paywall.amount, f"Minimum amount is {paywall.amount} sat."
+ payment_hash, payment_request = await create_invoice(
+ wallet_id=paywall.wallet,
+ amount=max(amount, paywall.amount),
+ memo=f"{paywall.memo}",
+ extra={"tag": "paywall", "id": paywall.id},
+ )
+ return {"payment_hash": payment_hash, "payment_request": payment_request}
+
+
+async def _is_payment_made(paywall: Paywall, payment_hash: str) -> int:
try:
status = await check_transaction_status(paywall.wallet, payment_hash)
is_paid = not status.pending
except Exception:
- return {"paid": False}
+ return 0
if is_paid:
- wallet = await get_wallet(paywall.wallet)
- assert wallet
- payment = await wallet.get_payment(payment_hash)
- assert payment
+ payment = await get_standalone_payment(
+ checking_id_or_hash=payment_hash, incoming=True, wallet_id=paywall.wallet
+ )
+ assert payment, f"Payment not found for payment_hash: '{payment_hash}'."
+ if payment.extra.get("tag", None) != "paywall":
+ return 0
+ paywall_id = payment.extra.get("id", None)
+ if paywall_id and paywall_id != paywall.id:
+ return 0
await payment.set_pending(False)
- return {"paid": True, "url": paywall.url, "remembers": paywall.remembers}
- return {"paid": False}
+ return payment.amount
+ return 0Why this scored 48/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.