diff --git a/__init__.py b/__init__.py index 28b04b9..159e280 100644 --- a/__init__.py +++ b/__init__.py @@ -17,4 +17,51 @@ withdraw_ext.include_router(withdraw_ext_generic) withdraw_ext.include_router(withdraw_ext_api) withdraw_ext.include_router(withdraw_ext_lnurl) -__all__ = ["db", "withdraw_ext", "withdraw_static_files"] + +def withdraw_start() -> None: + """ + Register this extension's RPCs with the LNbits nostr transport so an + HTTP-allergic client (e.g. lamassu-next ATM) can manage LNURL-withdraw + links without touching the HTTP API. Also wires the link-owner + resolver so subscribe_payments({tag:"withdraw", link_id:...}) can + verify ownership. + + No-op if the core transport module isn't present in the LNbits build. + No runtime `if nostr_transport_enabled` guard is needed — when + disabled, the relay pool never publishes, so registered RPCs are + simply unreachable. + """ + try: + from lnbits.core.services.nostr_transport.dispatcher import ( + AUTH_ACCOUNT, + AUTH_WALLET, + register_rpc, + ) + from lnbits.core.services.nostr_transport.subscriptions import ( + register_link_owner_resolver, + ) + except ImportError: + return + + from .transport_rpcs import ( + handle_lnurlw_create_link, + handle_lnurlw_delete_link, + handle_lnurlw_get_link, + handle_lnurlw_list_links, + handle_lnurlw_unique_hashes, + handle_lnurlw_update_link, + resolve_withdraw_owner, + ) + + register_rpc("lnurlw_create_link", handle_lnurlw_create_link, AUTH_WALLET) + register_rpc("lnurlw_get_link", handle_lnurlw_get_link, AUTH_WALLET) + register_rpc("lnurlw_list_links", handle_lnurlw_list_links, AUTH_ACCOUNT) + register_rpc("lnurlw_unique_hashes", handle_lnurlw_unique_hashes, AUTH_WALLET) + register_rpc("lnurlw_update_link", handle_lnurlw_update_link, AUTH_WALLET) + register_rpc("lnurlw_delete_link", handle_lnurlw_delete_link, AUTH_WALLET) + register_link_owner_resolver( + "withdraw", resolve_withdraw_owner, link_extra_key="withdrawal_link_id" + ) + + +__all__ = ["db", "withdraw_ext", "withdraw_start", "withdraw_static_files"] diff --git a/config.json b/config.json index 292d2d9..e54edf5 100644 --- a/config.json +++ b/config.json @@ -2,7 +2,7 @@ "name": "Withdraw Links", "short_description": "Make LNURL withdraw links", "tile": "/withdraw/static/image/lnurl-withdraw.png", - "version": "1.2.1", + "version": "1.2.2-aio.2", "min_lnbits_version": "1.3.0", "contributors": [ { diff --git a/crud.py b/crud.py index b914ae5..73966a5 100644 --- a/crud.py +++ b/crud.py @@ -32,6 +32,7 @@ async def create_withdraw_link( webhook_headers=data.webhook_headers, webhook_body=data.webhook_body, custom_url=data.custom_url, + extra=data.extra, number=0, ) await db.insert("withdraw.withdraw_link", withdraw_link) diff --git a/helpers.py b/helpers.py index 51eb948..31efcff 100644 --- a/helpers.py +++ b/helpers.py @@ -1,4 +1,5 @@ from fastapi import Request +from lnbits.settings import settings from lnurl import Lnurl from lnurl import encode as lnurl_encode from shortuuid import uuid @@ -26,3 +27,28 @@ def create_lnurl(link: WithdrawLink, req: Request) -> Lnurl: f"Error creating LNURL with url: `{url!s}`, " "check your webserver proxy configuration." ) from e + + +def create_lnurl_from_baseurl(link: WithdrawLink) -> Lnurl: + """ + Same shape as `create_lnurl`, but composes the callback URL from + `settings.lnbits_baseurl` instead of a FastAPI `Request`. Used by + the nostr-transport RPC handlers, which have no HTTP request to + derive a base URL from. + """ + base = settings.lnbits_baseurl.rstrip("/") + if link.is_unique: + usescssv = link.usescsv.split(",") + tohash = link.id + link.unique_hash + usescssv[link.number] + multihash = uuid(name=tohash) + url = f"{base}/withdraw/api/v1/lnurl/{link.unique_hash}/{multihash}" + else: + url = f"{base}/withdraw/api/v1/lnurl/{link.unique_hash}" + + try: + return lnurl_encode(url) + except Exception as e: + raise ValueError( + f"Error creating LNURL with url: `{url!s}`, " + "check your `LNBITS_BASEURL` configuration." + ) from e diff --git a/migrations.py b/migrations.py index 754a57f..e27af8a 100644 --- a/migrations.py +++ b/migrations.py @@ -139,3 +139,9 @@ async def m007_add_created_at_timestamp(db): "ALTER TABLE withdraw.withdraw_link " f"ADD COLUMN created_at TIMESTAMP DEFAULT {db.timestamp_column_default}" ) + + +async def m008_add_enabled_column(db): + await db.execute( + "ALTER TABLE withdraw.withdraw_link ADD COLUMN enabled BOOLEAN DEFAULT true;" + ) diff --git a/migrations_fork.py b/migrations_fork.py new file mode 100644 index 0000000..1caf27c --- /dev/null +++ b/migrations_fork.py @@ -0,0 +1,44 @@ +""" +Fork-specific database migrations for the aiolabs withdraw extension. + +These migrations are tracked separately under `withdraw_fork` in the +`dbversions` table (loaded by `lnbits/core/helpers.py:migrate_extension_database`), +so they do not collide with upstream's `m{NNN}_*` numbering in +`migrations.py`. Keeping the upstream-tracked file untouched means +`git pull upstream` stays rebase-clean for schema changes. + +Conventions: + - Sequential numbering starting from m001. + - Each migration is `async def m{NNN}_(db)`. + - DDL must be idempotent: a fresh install runs every migration; an + install that already carries the column must not crash. Use + `_alter_add_column_safe` so re-runs are no-ops. +""" + + +async def _alter_add_column_safe(db, sql: str) -> None: + """ALTER TABLE ADD COLUMN that swallows duplicate-column errors, so a + re-run on a DB that already has the column is a silent no-op.""" + try: + await db.execute(sql) + except Exception as exc: + msg = str(exc).lower() + if "duplicate column" in msg or "already exists" in msg: + return + raise + + +async def m001_aio_withdraw_schema(db): + """ + Apply every aiolabs schema delta on top of upstream withdraw. + + `withdraw_link.extra` — arbitrary JSON merged into the payout payment's + `extra` when the link is claimed (see views_lnurl). Lets a caller tag the + resulting payment with settlement/attribution metadata an external listener + can key on — e.g. bitSpire stamps {source, type, principal_sats, fee_sats, + ...} so the spirekeeper cash-in settlement fires off an LNURL-withdraw + payout. Stored as TEXT; (de)serialized to a dict by the WithdrawLink model. + """ + await _alter_add_column_safe( + db, "ALTER TABLE withdraw.withdraw_link ADD COLUMN extra TEXT" + ) diff --git a/models.py b/models.py index ff8c657..2f8ae48 100644 --- a/models.py +++ b/models.py @@ -15,6 +15,13 @@ class CreateWithdrawData(BaseModel): webhook_headers: str = Query(None) webhook_body: str = Query(None) custom_url: str = Query(None) + enabled: bool = Query(True) + # Arbitrary JSON merged into the payout payment's `extra` when this link is + # claimed (see views_lnurl). Lets a caller tag the resulting payment with + # settlement/attribution metadata an external listener can key on — e.g. + # bitSpire stamps {source, type, principal_sats, fee_sats, ...} so the + # spirekeeper cash-in settlement fires off an LNURL-withdraw payout. + extra: dict | None = None class WithdrawLink(BaseModel): @@ -36,7 +43,12 @@ class WithdrawLink(BaseModel): webhook_headers: str = Query(None) webhook_body: str = Query(None) custom_url: str = Query(None) + # Persisted as TEXT (JSON); merged into the payout payment's `extra` on + # claim. LNbits' db layer (de)serializes dict-typed columns to/from JSON + # natively (same as Payment.extra) — no per-field validator needed. + extra: dict | None = None created_at: datetime + enabled: bool = Query(True) lnurl: str | None = Field( default=None, no_database=True, @@ -47,6 +59,11 @@ class WithdrawLink(BaseModel): "Example: lnurlw://${window.location.hostname}/lnurlw/${id}" ), ) + lnurl_url: str | None = Field( + default=None, + no_database=True, + description="The raw LNURL callback URL (use for QR code generation)", + ) @property def is_spent(self) -> bool: diff --git a/static/js/index.js b/static/js/index.js index 9a8a9c1..0b42b40 100644 --- a/static/js/index.js +++ b/static/js/index.js @@ -51,9 +51,7 @@ window.app = Vue.createApp({ align: 'right', label: 'Max (sat)', field: 'max_withdrawable', - format: v => { - return new Intl.NumberFormat(LOCALE).format(v) - } + format: LNbits.utils.formatSat } ], pagination: { @@ -70,7 +68,8 @@ window.app = Vue.createApp({ data: { is_unique: false, use_custom: false, - has_webhook: false + has_webhook: false, + enabled: true } }, simpleformDialog: { @@ -80,7 +79,8 @@ window.app = Vue.createApp({ use_custom: false, title: 'Vouchers', min_withdrawable: 0, - wait_time: 1 + wait_time: 1, + enabled: true } }, qrCodeDialog: { @@ -127,20 +127,22 @@ window.app = Vue.createApp({ this.formDialog.data = { is_unique: false, use_custom: false, - has_webhook: false + has_webhook: false, + enabled: true } }, simplecloseFormDialog() { this.simpleformDialog.data = { is_unique: false, - use_custom: false + use_custom: false, + enabled: true } }, openQrCodeDialog(linkId) { const link = _.findWhere(this.withdrawLinks, {id: linkId}) this.qrCodeDialog.data = _.clone(link) this.qrCodeDialog.show = true - this.activeUrl = `${window.location.origin}/withdraw/api/v1/lnurl/${link.unique_hash}` + this.activeUrl = link.lnurl_url }, openUpdateDialog(linkId) { let link = _.findWhere(this.withdrawLinks, {id: linkId}) diff --git a/templates/withdraw/display.html b/templates/withdraw/display.html index 4d06e11..812c95f 100644 --- a/templates/withdraw/display.html +++ b/templates/withdraw/display.html @@ -7,6 +7,12 @@ Withdraw is spent. + Withdraw is spent. + Withdraw is disabled.