What changed, and why it matters
This commit adds a new background job scheduler to LNbits. It lets core code, Python extensions, and sandboxed WASM extensions register recurring cron-like tasks. The change is a feature addition, not a documented security fix. The scheduler introduces new attack surface: arbitrary code execution paths for extensions, permission checks, job ownership, and cron parsing. However, the supplied diff is truncated before the API routes and most implementation details, so only a partial security review is possible from the materials given.
Treat this as a significant new feature with security implications rather than a confirmed vulnerability. Complete the review by examining the truncated files (scheduler_api.py, wasm_ext/api/scheduler.py, wasm_ext/wasm/scheduler.py, utils/cron.py) and their tests. Verify that HTTP endpoints enforce admin/user authorization correctly, that WASM schedule policies cannot be bypassed, that cron parsing is robust against denial-of-service or unexpected timezone behavior, and that extension callbacks run with appropriate privilege boundaries. Consider requesting a security-focused design review or audit before enabling WASM extension scheduling in production.
Security signals we found
New privileged execution path: scheduled callbacks can run in the background without an interactive request
WASM extensions can request scheduler.user and scheduler.extension permissions with admin-approved cron policies
Job payloads are JSON objects up to 8192 bytes; HTML-sensitive characters are escaped before storage
Lease-based concurrency control (60s lease, 20s renewal) with conditional completion on claim token
Access rechecked on execution and heartbeat; deactivated users/extensions disable further runs
Error messages redacted for credentials, bearer tokens, and 64-character hex values
History retention and per-user/per-extension count limits implemented
Documentation explicitly warns that leases do not guarantee exactly-once external effects
Evidence from the diff
The patch introduces a core scheduler service (lnbits/core/services/scheduler.py), database tables (scheduled_jobs, scheduled_job_runs), CRUD, models, migrations, WASM scheduler integration, admin UI/API, and documentation. Security-relevant design elements visible in the diff include: namespace-scoped handlers (core or extension:<id>), user vs extension job ownership, admin-approved WASM schedule policies, lease-based claiming to prevent overlapping runs, access rechecking on heartbeat, disabling jobs for deactivated users/extensions, payload size limits (8192 bytes), error-message redaction, and history retention limits. The diff cuts off at lnbits/core/views/scheduler_api.py, so the HTTP endpoints, authentication/authorization checks, and full WASM scheduler implementation are not visible. No CVE, advisory, or vendor security statement is present in the commit or supplied references.
Changed components
lnbits/core/services/scheduler.pylnbits/core/crud/scheduler.pylnbits/core/models/scheduler.pylnbits/core/views/scheduler_api.pylnbits/core/wasm_ext/api/scheduler.pylnbits/core/wasm_ext/wasm/scheduler.pylnbits/core/migrations.pylnbits/app.pylnbits/core/services/extensions.pylnbits/core/services/notifications.pylnbits/utils/cron.pylnbits/utils/error.pyInspect captured patch +7020 / −103
diff --git a/docs/devs/extensions.md b/docs/devs/extensions.md
index 87f0ca4..7a75532 100644
--- a/docs/devs/extensions.md
+++ b/docs/devs/extensions.md
@@ -7,6 +7,11 @@ nav_order: 2
# Extension set up
+**Before creating or modifying a WASM extension, read the
+[WASM extension development guide](../wasm-extensions.md).** It documents host
+capabilities, permissions, browser restrictions, and examples checked against core.
+The setup instructions below describe Python extensions.
+
Start off by creating a fork of the [example extension](https://github.com/lnbits/example) into own GitHub repository and rename the repository to `mysuperplugin`:
```sh
@@ -32,6 +37,8 @@ mv templates/example templates/mysuperplugin # Rename templates folder.
## Extension structure explained
+For persistent background jobs, see the [core scheduler](scheduler.md).
+
- views_api.py: This is where your public API would go. It will be exposed at "$DOMAIN/$PLUGIN/$ROUTE". For example: https://lnbits.com/mysuperplugin/api/v1/tools.
- views.py: The `/` path will show up as your plugin's home page in lnbits' UI. Other pages you can define yourself. The `templates` folder should explain itself in relation to this.
- migrations.py: Create database tables for your plugin. They'll be created automatically when you start lnbits.
diff --git a/docs/devs/scheduler.md b/docs/devs/scheduler.md
new file mode 100644
index 0000000..6d3995d
--- /dev/null
+++ b/docs/devs/scheduler.md
@@ -0,0 +1,310 @@
+---
+layout: default
+parent: For developers
+title: Scheduler
+nav_order: 8
+---
+
+# Core scheduler
+
+LNbits stores core, Python extension, and WASM extension jobs in one core table,
+`scheduled_jobs`. The task manager starts the scheduler after database migration
+and extension registration. No external cron daemon is required.
+
+## Supported expressions
+
+Expressions have exactly five fields, in this order:
+
+```text
+minute hour day-of-month month day-of-week
+```
+
+| Field | Values |
+| ------------ | ---------------------------------------- |
+| Minute | 0–59 |
+| Hour | 0–23 |
+| Day of month | 1–31 |
+| Month | 1–12 or JAN–DEC |
+| Day of week | 0–7 or SUN–SAT; both 0 and 7 mean Sunday |
+
+Supported operators are `*`, comma-separated lists, inclusive ranges (`-`), and
+steps (`/`). Month and weekday names are case-insensitive. A whole-field `?` in
+day-of-month or day-of-week is accepted and normalized to `*`.
+
+When both day-of-month and day-of-week are restricted, either field matching is
+sufficient (standard cron OR semantics). Numeric weekdays follow standard cron,
+not Quartz's 1–7 numbering. This is a small cron dialect, not full Quartz.
+
+Seconds, years, `L`, `W`, `#`, `H`, `R`, and aliases such as `@daily` are rejected.
+Expressions with no occurrence in the next eight years are rejected when saved.
+
+| Expression | Meaning |
+| ----------------- | ------------------------------------------------------- |
+| `* * * * *` | Every minute |
+| `*/10 * * * *` | Every ten minutes, at minutes 0, 10, 20, 30, 40, and 50 |
+| `0 9 * * MON-FRI` | Weekdays at 09:00 |
+| `0 0 1 * *` | Midnight on the first of each month |
+| `0 9 ? * MON` | Mondays at 09:00 |
+
+Times are interpreted in the job's IANA timezone, defaulting to `UTC`. The database
+stores execution and lease times as UTC Unix seconds. Local daylight-saving
+behavior follows `croniter`: nonexistent local times can move to the spring
+transition, and repeated local times can run twice at distinct UTC instants. For
+example, `30 2 * * *` in `Europe/Berlin` runs at 03:00 on March 29, 2026, and can run
+at both occurrences of 02:30 on October 25, 2026. Use UTC for schedules that must
+avoid daylight-saving shifts.
+
+## Execution and recovery
+
+- After downtime, an overdue job runs once using its saved payload. Missed ticks
+ are coalesced into that one execution.
+- A job does not overlap itself. Ticks during execution are skipped; completion
+ calculates the next occurrence strictly after the finish time.
+- Callback failures are logged without including payloads or exception details.
+ The next attempt follows the normal schedule, with no immediate retry loop.
+- The runner polls once per second and permits four concurrent jobs per process.
+ Minute-level expressions describe intended start times, not a hard latency
+ guarantee when workers are busy.
+- Workers claim jobs atomically with a 60-second lease, renewed every 20 seconds.
+ Completion is conditional on the claim token. An interrupted job becomes
+ eligible once its lease expires, including after shutdown.
+- Revoked permissions, disabled extensions, and disabled/deleted users prevent
+ further executions. Running jobs recheck access on lease renewal. Extension
+ deactivation also cancels its local scheduled callbacks.
+- An execution or lease renewal that finds a deleted or deactivated owner
+ disables all that user's jobs, stopping repeated failed attempts. Existing run
+ history is retained. Reactivating the account does not automatically resume
+ those jobs; their owner must explicitly enable them again.
+- Pausing sets `enabled` to false. A running callback is cancelled on its next
+ lease renewal. Deleting an actively leased job is rejected; pause it and wait
+ before deleting. Uninstallation removes that extension's schedules.
+- Admins can enable or disable the scheduler in Settings > Scheduler. The
+ `lnbits_scheduler_enabled` setting defaults to true and takes effect on save
+ without restarting the server. While disabled, the scheduler stays alive but
+ does not poll for jobs or maintain run history. Jobs already running finish
+ normally. Re-enabling runs each overdue job once, then resumes its cron schedule
+ without replaying every missed occurrence.
+- Application shutdown and extension job shutdown wait up to five seconds for
+ scheduler cleanup, log failures or unfinished jobs, and continue the remaining
+ cleanup. This deadline requires a responsive event loop; it cannot forcibly
+ terminate native threads or bound an extension's separate Python stop hook.
+
+Leases coordinate workers but do not make external effects exactly-once. Callbacks
+that send messages or make payments must handle duplicate attempts after a crash
+or lost lease. Python callbacks must be asynchronous and cooperate with
+cancellation. WASM jobs use the existing runtime resource limits and invocation
+monitoring (`trigger_type="schedule"`, schedule ID in `context`).
+
+## Execution history
+
+The admin-only Scheduler page shows each job's latest attempt and result. Select
+a job to open its execution history, or use **Run history** to browse all retained
+attempts, including deleted jobs. History opens on `/scheduler/runs` with
+clearable job ID, namespace, user ID, and status filters, search, and pagination.
+Opening a job prefills its job ID, namespace, and user ID. Filters are stored in
+the URL so refreshes and shared links preserve them. Its API is
+`GET /scheduler/api/v1/runs`, with optional `job_id`, `namespace`, `user_id`,
+`status`, `search`, `limit`, and `offset` parameters.
+
+Each attempt is stored in the core database's `scheduled_job_runs` table. Records
+snapshot the job ID, source, handler, scope, timezone, scheduled time, actual
+start and finish times, and result. Durations are calculated from start and finish
+times. User ownership is stored internally so history limits still apply after a
+job is deleted. User IDs and lease tokens are never returned by the API. Failed
+attempts include the exception type and a redacted error message, limited to 500
+characters, in the run details and server log. Common credential fields, bearer
+tokens, and 64-character hex values are redacted. WASM backtraces are omitted in
+favor of the cause. Job payloads and Python tracebacks are not attached to errors.
+
+Results are `running`, `succeeded`, `failed`, `cancelled`, `interrupted`, or
+`skipped`. Missing or paused jobs and unregistered handlers are skipped. An
+unfinished attempt whose lease is no longer active becomes interrupted; its
+finish time and duration remain unknown. A recorded result describes the
+callback's completion, not a guarantee about its external effects.
+
+History limits are configurable under **Settings → Scheduler** and apply without
+a restart:
+
+- `lnbits_scheduler_history_retention_days`: seven days for successful, cancelled,
+ interrupted, and skipped attempts.
+- `lnbits_scheduler_history_failed_retention_days`: thirty days for failed attempts.
+- `lnbits_scheduler_history_max_runs_per_user`: 1,000 completed attempts per user,
+ across all extensions and handlers.
+- `lnbits_scheduler_history_max_runs_per_extension`: 1,000 completed shared attempts
+ per extension, across all handlers. User attempts do not consume this limit.
+
+All settings have a minimum of one. While the scheduler is enabled, abandoned
+runs are marked interrupted once per minute and history cleanup runs every
+15 minutes. History can temporarily exceed its limits between cleanups.
+Completed attempts expire relative to their finish time; interrupted attempts
+use their start time. After expired attempts are removed, count limits remove
+oldest non-failed attempts first, then oldest failures.
+Active runs are preserved and do not count toward these limits. Shared core jobs
+use age retention only.
+
+Deleting a job does not immediately delete its history.
+History writes are best-effort: recording failures do not prevent execution or
+change the scheduler's retry and lease behavior.
+
+## Core and Python API
+
+Register handlers whenever the application or extension starts. Store a stable
+job ID in your configuration and reuse it for edits. Registration alone does not
+change a persisted job's next execution time.
+
+```python
+import json
+
+from lnbits.core.models.scheduler import ScheduleConfig, ScheduledJob
+from lnbits.core.services.scheduler import scheduler
+from lnbits.helpers import sha256s
+
+
+async def refresh(job: ScheduledJob) -> None:
+ options = json.loads(job.payload_json)
+ # Perform the extension's work using options and job.user_id.
+
+
+def myextension_start() -> None:
+ scheduler.register("extension:myextension", "refresh", refresh)
+
+
+async def enable_refresh(user_id: str) -> dict:
+ # Call this from your authenticated user configuration endpoint.
+ job = await scheduler.save(
+ "extension:myextension",
+ ScheduleConfig(
+ id="myextension:" + sha256s(user_id) + ":refresh",
+ handler="refresh",
+ cron_expression="*/10 * * * *",
+ payload_json='{"configuration_id":"example"}',
+ ),
+ user_id=user_id,
+ )
+ return job.public_data()
+```
+
+Job IDs must be globally unique. A UUID saved with the configuration or a
+namespaced ID using a hashed user ID is suitable. Return `public_data()` to
+clients so account IDs and lease tokens remain private.
+
+Core uses the same API with namespace `core`. An extension-wide job omits
+`user_id`. Python extensions must enforce authentication/admin checks in their
+own configuration endpoints: Python is trusted application code, not sandboxed.
+The service checks that the extension and any user owner remain active.
+
+Use `scheduler.list_paginated(namespace, user_id=..., limit=100, offset=0)` and
+`scheduler.delete(namespace, job_id, user_id=...)` to manage the corresponding
+scope. Listing returns a `Page` with `data` and the total number of matching jobs
+in `total`. Save the same ID with `enabled=False` to pause, or `enabled=True` to resume.
+Saving recalculates the next occurrence from the current time. IDs cannot be
+reassigned across namespaces or owners.
+
+## WASM host API and permissions
+
+Declare scheduling permissions in the extension manifest for administrator
+approval:
+
+| Permission | Scope |
+| --------------------- | ----------------------------------------------------------------------------- |
+| `scheduler.user` | Manage jobs belonging to the authenticated user |
+| `scheduler.extension` | Manage shared jobs for the extension; requires an authenticated administrator |
+
+An extension may request either or both. Scheduling permission does not grant
+notification, HTTP, storage, or payment access. Each still needs its own grants.
+
+Each scheduling permission must declare a nonempty `policies` list containing
+one cron expression and timezone per handler. The administrator reviews and
+approves these schedules at installation; policies alone do not create jobs.
+For example, a pricebot can declare:
+
+```json
+{
+ "permissions": [
+ {
+ "id": "scheduler.extension",
+ "policies": [
+ {
+ "handler": "collect_prices",
+ "cron_expression": "* * * * *",
+ "timezone": "UTC"
+ }
+ ]
+ },
+ {
+ "id": "scheduler.user",
+ "policies": [
+ {
+ "handler": "check_alerts",
+ "cron_expression": "*/10 * * * *",
+ "timezone": "UTC",
+ "max_jobs_per_user": 10
+ }
+ ]
+ }
+ ]
+}
+```
+
+Both handlers must be declared in `wasm.exports` with `visibility: "event"`.
+Timezone defaults to `UTC`. Handlers must be unique within each permission;
+the same handler can have different schedules in the two scopes. Administrators
+may grant a subset of the declared handlers, or omit a permission entirely.
+Cron and timezone must match the declared policy; schedule changes require an
+updated manifest and administrator approval.
+
+Each `scheduler.user` handler policy has a positive integer `max_jobs_per_user`,
+defaulting to 10 when omitted, including in existing grants. The quota is separate
+for each extension, user, and handler, and counts enabled and paused jobs. Admins
+can raise or lower it in the extension permission editor, effective immediately.
+Lowering it preserves existing jobs and permits updates and deletion; new jobs
+are rejected until the count is below the limit. Deleting a job frees a slot.
+
+WASM extensions can also declare a top-level `schedules` array containing the
+shared policies to start automatically. These entries must match granted
+`scheduler.extension` policies and cannot be omitted from the grants. Core creates
+the jobs on activation and restores missing jobs on startup, preserving existing
+jobs' next runs, leases, and administrator pauses. See
+[automatic WASM schedules](../wasm-extensions.md#scheduled-work).
+
+The host methods are `scheduler.set`, `scheduler.list`, and `scheduler.delete`,
+exposed through WIT instance `lnbits:extension/scheduler` as `set-schedule`,
+`list-schedules`, and `delete-schedule`. The TypeScript SDK generator discovers
+these methods automatically.
+
+`scheduler.set` accepts `id` (optional on first creation), `handler`,
+`cronExpression`, `timezone` (default `UTC`), `payloadJson` (a JSON object, up to
+8192 bytes), `enabled` (default true), and `scope` (`user` by default, or
+`extension`). It returns `scheduleJson`; retain its `id` and send it on updates.
+For user jobs, omitting `id` creates a new job, even for the same handler. Supplying
+the same ID updates that job; its handler, owner, and namespace cannot change.
+Shared extension jobs retain one stable job ID per handler.
+IDs consisting of 64 lowercase hexadecimal characters are reserved for shared
+jobs and cannot be supplied for user jobs.
+The handler, normalized cron expression, and timezone must match the approved
+policy for that scope on both creation and updates. Core checks approval again
+before executing a job and during its heartbeat. Revoking the policy blocks
+future callbacks and cancels running callbacks at the next heartbeat. The
+extension may check its own conditions and return without doing work; it cannot
+override the approved schedule. Core and trusted Python schedules do not require
+these WASM policies.
+Listing returns `schedulesJson` and accepts `scope`, `limit`, and `offset`.
+Deletion accepts `id` and `scope` and returns `deleted`.
+
+The host assigns the extension namespace and user identity; callers cannot
+supply either. Only interactive authenticated requests may manage schedules.
+Scheduled callbacks cannot create additional jobs. Owners may still list/delete
+their jobs after the scheduling grant is revoked; shared jobs remain admin-only.
+
+The handler must be a registered WASM export with `visibility: "event"`. Its
+JSON payload contains `scheduleId`, `scheduledAt` (the saved due time), and `data`
+(the decoded `payloadJson`). The callback runs with `context="schedule"` and
+without a browser access token. User-scoped callbacks receive their owner's
+storage and notification context. Shared callbacks use the storage owner
+`extension:<id>`, without a user identity. They can access that extension-owned
+partition, but cannot access users' private rows or choose a user's wallet. Scheduled
+payments require the existing background-payment permission and per-wallet grant.
+
+Shared data APIs are separate from scheduling. An extension-wide price collector
+and per-user alert evaluators can use different schedules and permissions; this
+scheduler does not create the pricebot, its tables, or a shared storage API.
diff --git a/docs/wasm-extensions.md b/docs/wasm-extensions.md
new file mode 100644
index 0000000..8fccf82
--- /dev/null
+++ b/docs/wasm-extensions.md
@@ -0,0 +1,594 @@
+---
+layout: default
+parent: For developers
+title: WASM extensions
+nav_order: 9
+---
+
+# Developing WASM extensions
+
+**Read this guide before creating a WASM extension or choosing its architecture.**
+Check the host APIs, execution context, browser restrictions, and release format
+before copying an existing extension. The [extension setup guide](devs/extensions.md)
+describes the separate Python workflow.
+
+## Work directly in the extension directory
+
+**Make extension changes directly in `data/wasm_extensions/<id>`**, or the
+corresponding directory under the configured `LNBITS_WASM_EXTENSIONS_PATH`.
+For Pricebot in this checkout, work in `data/wasm_extensions/pricebot`.
+If that directory is a symlink, edit its existing target and preserve the link.
+
+Keep the source, configuration, UI/assets, schema, migrations, tests, and rebuilt
+WASM component in that extension directory. Run the extension's checks there.
+Do not use a temporary copy or separate checkout as the primary working directory
+unless the user explicitly requests it. Temporary test databases and fixtures
+are fine, but completed extension changes must be present in the actual directory.
+
+If filesystem permissions block an edit, request access to the actual target;
+do not silently redirect the work elsewhere. If changes were already staged in
+a temporary copy, reconcile them into the extension directory, preserve any
+concurrent user edits, and verify the destination before reporting completion.
+State separately whether the running instance has loaded the changes and whether
+installation or permission approval is still required.
+
+This working-directory rule does not authorize core edits. Core changes still
+require the explicit approval described below and belong in their core files.
+
+## Core changes require explicit user approval
+
+**Never change LNbits core while creating, fixing, or updating a WASM extension
+without first asking the user and receiving explicit approval for those core
+changes.** Approval to work on an extension, including a general "go ahead", does
+not authorize core changes. A missing host capability or a failing extension test
+does not create an exception.
+
+This applies to host APIs, the WASM runtime, scheduling and activation, permissions,
+authentication, storage and migrations, core frontend code, core tests, and core
+dependencies or build configuration. Do not change core indirectly through build
+scripts, generated files, or patches in another checkout.
+
+Read-only inspection of core is allowed. If the existing APIs cannot meet an
+extension requirement, explain the limitation, any extension-only alternatives,
+and the specific core changes and files proposed. Ask whether the user authorizes
+that scope, then wait for their answer before editing core. Continue only the
+extension work that does not depend on that approval.
+
+## Review scope
+
+This guide combines source and documentation review of all **16 extensions and
+21 releases** in the [WASM registry snapshot](https://github.com/lnbits/lnbits-extensions-wasm/blob/2ee1c7b4adedeb49bb23fc2ac66af7564adc9527/extensions.json).
+Reviewed on **2026-10-08**, against LNbits commit
+`e6301243e82790ecd50550eb9ee6f1d20a1db799`. Core behavior below comes from this
+checkout; extension examples are pinned to their registry-listed releases.
+This was a static review of manifests, WIT, application source, frontend code,
+build scripts, migrations, tests, and available documentation. It does not certify
+the security or runtime compatibility of the released binaries. See the
+[review inventory](#review-inventory) for every repository and version.
+
+## Start with these decisions
+
+1. Choose a component toolchain: existing extensions demonstrate JavaScript, Rust,
+ and C. Browser JavaScript and server-side WASM are separate programs.
+2. Map each operation to an existing host method and the permission it requires.
+ Identify whether it runs for a logged-in user, a public visitor, a payment
+ event, or a scheduled job. These contexts have different capabilities.
+3. Design ownership and public responses before defining tables. Shared jobs do
+ not provide shared storage. Public owner-context routes need their own action
+ authorization.
+4. Choose explicit Vue render functions or templates compiled during the build.
+ Runtime template compilation violates the iframe's CSP.
+5. Budget storage calls, HTTP calls, response sizes, and execution time. Work that
+ requires SQL transactions, an arbitrary server process, or a missing host API
+ needs a different extension design or a core change explicitly approved under
+ the [rule above](#core-changes-require-explicit-user-approval).
+
+## Runtime and languages
+
+LNbits runs a **WebAssembly component** in Wasmtime on the server. A bare WASM
+module, Python extension directory, or browser WASM bundle is not interchangeable
+with that component. Imports must match the host's WIT interfaces and records;
+exports accept a JSON string and return a JSON string.
+
+| Guest language | Observed build approach | Examples |
+| -------------- | ------------------------------------------------------------------------ | ------------------------------------------------- |
+| JavaScript | Bundle guest source, then use `@bytecodealliance/jco` to componentize it | Tips, games, SupportChat, InventoryStats, PopMenu |
+| Rust | `cargo-component`, WIT bindings, compiled component | BigPayment, Forms, GiftCards, ZapGoals |
+| C | WASI SDK, `wit-bindgen` C bindings, then `jco embed` / `jco new` | PaySplit |
+
+Other languages are possible if they produce a compatible component. The table
+records build approaches present in the reviewed source, not a required language.
+JavaScript guests do not receive Node.js or browser APIs such as `process`, DOM,
+or unrestricted `fetch` merely because the source language is JavaScript.
+
+Each invocation gets a fresh instance and store. Compiled components are cached;
+guest globals are not persistent application state or reliable locks. The host
+links WASI, but supplies no preopened application directories or inherited
+environment through its empty WASI configuration. Use host storage, HTTP, wallet,
+event, and scheduler APIs instead of assuming filesystem, socket, or background
+process access. Rebuild the component after changing guest source.
+
+Sources: [component lifecycle](../lnbits/core/wasm_ext/wasm/component.py),
+[invocation](../lnbits/core/wasm_ext/wasm/invoke.py),
+[host imports](../lnbits/core/wasm_ext/wasm/host.py).
+
+## Files and interface contracts
+
+A typical package contains:
+
+```text
+config.json Identity, module, exports, routes, permissions
+wasm/<extension>.wasm Built component referenced by config.json
+wasm/lnbits-extension.wit WIT contract, if configured
+storage/schema.json Table and field definitions, if storage is used
+storage/migrations/0001_*.json Declarative schema operations
+ui/*.html Configured iframe entrypoints
+static/*.js, static/*.css Browser application and other allowed assets
+dev/ or wasm/src/ Source/build tooling; layout varies by toolchain
+```
+
+`config.json` needs a matching `id`, name, description, version,
+`extension_type: "wasm"`, and `wasm.module`. Declare exports with visibility
+`authenticated`, `public`, or `event`. HTTP routes cannot expose event exports.
+The currently supported payment event configuration is `events.onInvoicePaid`.
+Scheduler handlers also use event exports, with separate scheduler policies.
+
+When first creating a WASM extension, set `config.json`'s `min_lnbits_version`
+to the current LNbits version from `[project].version` in
+[`pyproject.toml`](../pyproject.toml). Read that value at creation time and preserve
+any prerelease suffix. Do not copy an older minimum version from a template or
+another extension.
+
+Host method IDs such as `utils.currencies.rate` are different from their WIT
+import names. Imports live in interfaces such as `lnbits:extension/host`,
+`lnbits:extension/utils-currencies`, and `lnbits:extension/scheduler`. Match names,
+record fields, optional values, and numeric types exactly. JavaScript bindings
+for WIT 64-bit integers use `BigInt`; normalize values before JSON serialization
+and only convert to `Number` when precision is safe.
+
+The authoritative method list and request/response schemas come from
+[`list_extension_api_methods()` / `extension_api_contract()`](../lnbits/core/wasm_ext/api/registry.py)
+and the [host models](../lnbits/core/wasm_ext/api/models.py). The
+[TypeScript SDK generator](../tools/codegen/extension_sdk_typescript.py) derives
+types and wrappers from those methods. It does not replace building a matching
+WIT component. Repository-specific `lnbits-sdk.js` wrappers can differ; verify
+their behavior rather than treating one copied SDK as the host specification.
+
+Unknown config fields are currently ignored. In particular, copying a
+`wasm.resource_limits` or `wasm.host_api` field does not configure the runtime.
+Unknown requested permission IDs are rejected. See the
+[config models](../lnbits/core/wasm_ext/wasm/config.py) and
+[permission registry](../lnbits/core/wasm_ext/api/registry.py).
+
+### Routes and JSON
+
+API routes are mounted at `/api/v1/ext/<id><configured-path>`. UI routes are
+mounted under `/ext`, and assets under `/ext-assets/<id>/`. UI entrypoints are
+served through the core wrapper with a short-lived frame token; static HTML is
+not an alternate entrypoint.
+
+API payloads merge mapped path parameters, then query parameters, then JSON body
+fields; later values override earlier ones. Query values are strings. POST, PUT,
+and PATCH accept a JSON object. Configure `path_params` explicitly when names
+matter, and validate the merged payload inside the guest. Do not assume that an
+identifier came exclusively from the path.
+
+Guests receive structured JSON, not a FastAPI request with arbitrary headers,
+raw body, uploaded files, or control over response headers and status. A webhook
+scheme that needs signatures over raw bytes or a special header may need a host
+change. Returning `{ "ok": false, "error": "..." }` is an extension convention
+and can still produce HTTP 200; handle business errors and transport errors.
+
+Sources: [API routing](../lnbits/core/wasm_ext/routes/api.py),
+[UI routing](../lnbits/core/wasm_ext/routes/ui.py),
+[OpenAPI metadata](../lnbits/core/wasm_ext/routes/open_api.py).
+
+## Browser UI: build for the actual sandbox
+
+The iframe has `sandbox allow-scripts allow-pointer-lock`, without
+`allow-same-origin`, `allow-forms`, or `allow-popups`. Its CSP permits scripts and
+styles only from the extension asset prefix, forbids inline scripts and
+`unsafe-eval`, and sets `connect-src 'none'` and `form-action 'none'`.
+
+Consequences for implementation:
+
+- **Vue templates must not compile in the browser.** Use `render()` / `Vue.h()`,
+ as the JavaScript examples do, or compile templates into JavaScript at build
+ time, as Forms, GiftCards, and ZapGoals do. Mounting Vue over template markup,
+ using a `template` string, or calling `new Function` can cause `EvalError`.
+- Load JavaScript and CSS as external extension assets. Inline handlers, inline
+ style attributes, runtime-injected style blocks, and CDN dependencies are not
+ supported by this policy. Test libraries that manipulate styles under the real
+ CSP; a permissive development page is insufficient.
+- Use explicit button click handlers and bridge API calls for save actions.
+ Use `type="button"` where appropriate. Do not depend on native form submission,
+ including a submit button inside a Quasar form.
+- Direct `fetch`, XHR, browser WebSockets, workers, nested frames, and popup flows
+ are unavailable. Use the parent bridge for its supported operations.
+- The opaque iframe does not share the parent's DOM, cookies, or normal origin
+ storage. Use the session-storage bridge for transient UI state and host storage
+ for durable state. Do not assume browser wallet or Nostr providers are injected.
+
+Allowed static file suffixes are `.css`, `.gif`, `.ico`, `.jpeg`, `.jpg`, `.js`,
+`.ogg`, `.png`, `.webp`, `.woff`, and `.woff2`. **SVG files, JSON files, HTML files,
+and WASM binaries are not served by the static asset route.** Use supported image
+formats, canvas, or bundled JavaScript data as appropriate. This restriction on
+SVG files is separate from generating DOM elements in JavaScript.
+
+Core exposes a small asset proxy at `/ext-assets/<id>/_lnbits/`: Vue, Quasar,
+QR-code JavaScript, bundled/Quasar CSS, and Material Icons CSS/font. Use its
+allowlist rather than referencing arbitrary `/static/` paths.
+
+### Parent bridge
+
+The bridge uses a message channel to the LNbits wrapper. Account credentials
+remain in the parent. Supported actions include:
+
+| Action family | Purpose and boundary |
+| ---------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
+| `context`, `api` | Obtain UI context and call this extension's registered API routes |
+| `ui.notify` | Display a browser notification/toast; separate from delivery to a user's notification channels |
+| `navigation.replace`, `navigation.open_new_tab` | Parent-mediated navigation; opening an external tab requires confirmation |
+| `storage.session.get`, `storage.session.set` | Transient session state |
+| `ui.scan_qr` | Parent camera UI, with `ui.camera.scan_qr` and user approval |
+| `permissions.request*` | User permission dialogs, including background-payment and wallet-watch grants |
+| `payment.subscribe`, `payment.unsubscribe` | Payment updates for hashes accepted by the parent, including hashes returned by approved API calls |
+| `websocket.subscribe`, `websocket.unsubscribe`, `websocket.send` | Parent-managed extension channels |
+
+The bridge is not a generic browser-to-core RPC or an arbitrary URL proxy.
+External widgets in some repositories execute on another site's page and have
+their own CSP/CORS constraints. They do not relax the LNbits iframe policy;
+`frame-ancestors 'self'` also prevents simply embedding the LNbits UI cross-site.
+
+Sources: [CSP and frame tokens](../lnbits/core/wasm_ext/routes/security.py),
+[asset allowlist](../lnbits/core/wasm_ext/routes/assets.py),
+[parent bridge implementation](../lnbits/static/js/wasm-extension-component.js).
+
+## Permissions and execution context
+
+Permissions are declared in the extension configuration and reviewed by the
+administrator during installation. Policies narrow access to tables, fields,
+external origins, target extensions, websocket rates, or scheduled handlers.
+Installation approval does not replace per-user wallet grants.
+
+| Capability | Permission / restriction |
+| ---------------------------------------------- | -------------------------------------------------------------------------------------------- |
+| Private storage reads and writes | `ext.storage.read`, `ext.storage.write`; requires an owner |
+| Public reads and public append | `ext.storage.read_public`, `ext.storage.append_public`; explicit table/field/source policies |
+| List wallets / read balance | `wallet.list`, `wallet.balance.read`; accessible user wallets |
+| Create invoices | `wallet.create_invoice`; user's wallet |
+| Public invoice creation | `wallet.create_invoice_public`; wallet selected through an approved stored source |
+| Interactive outgoing payments | `wallet.pay_invoice`; user's wallet |
+| Background outgoing payments | `wallet.pay_invoice_background` plus an enabled per-wallet user grant |
+| Observe additional wallet payments | `wallet.payments.watch` plus a per-wallet watch grant |
+| Currency rates, conversions, invoice utilities | `utils.basic` |
+| Outbound HTTPS | `http.request`; approved origins and host network restrictions |
+| Another extension's API | `extension.api.request`; approved target/read-write policy and interactive account token |
+| Core user notifications | `notifications.send_user_notification`; resolved user's saved channel settings |
+| Server-published channel messages | `websocket.publish`; approved rate policy |
+| Browser channel access | `websocket.subscribe`; parent-managed connection |
+| User / shared schedules | `scheduler.user` / `scheduler.extension`; approved handler, cron, timezone |
+
+Host ID generation, current time, and logging do not require a separate
+permission. LNURL helpers have their own wallet requirements; inspect the
+method contract rather than assuming every utility belongs to `utils.basic`.
+
+| Invocation | Identity available | Practical effect |
+| -------------------------------- | ---------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
+| Authenticated HTTP request | Logged-in account, owner, account access token | User storage and approved interactive wallet/API operations |
+| Ordinary public HTTP request | No account or owner | Explicit public capabilities only |
+| Public route with `ownerContext` | Owner resolved from a source row; event context, no logged-in account token | Owner-scoped operations become possible; the guest must authorize the public action |
+| Invoice-paid event | Event wallet; owner may be resolved from the approved source or wallet watch | Approved event work; no browser account token |
+| User schedule | Job's user and storage owner; no browser account token | Owner storage, notifications, separately authorized background payments |
+| Extension-wide schedule | Extension storage owner (`extension:<id>`); no user or account token | Extension-owned storage and approved shared work; no private user storage or selectable user wallet |
+
+### Public owner context is not caller authentication
+
+`ownerContext: { "table": "...", "idParam": "..." }` resolves the owner of a
+stored source and invokes the guest in event context. A public visitor who knows
+the source ID does not thereby become that owner. Validate bearer/action tokens,
+game membership, permitted transitions, amounts, and related row IDs in the
+extension before performing an operation.
+
+Return an explicit public projection. A `public_fields` policy filters the public
+storage API; it does not sanitize JSON assembled from private storage inside an
+owner-context route. Secrets such as player tokens, unrevealed cards, claim
+credentials, and private configuration must remain out of those responses.
+
+Sources: [host methods and authorization](../lnbits/core/wasm_ext/api/host.py),
+[method permissions](../lnbits/core/wasm_ext/api/registry.py),
+[route owner resolution](../lnbits/core/wasm_ext/routes/api.py).
+
+## Storage and concurrency
+
+Tables are described in `storage/schema.json`. Numbered JSON migration files
+support `create_table`, `add_field`, and `create_index`. Field types include
+strings, integers, numbers, booleans, datetimes, and lists. Complex objects can
+be serialized into declared string fields. There is no guest SQL interface,
+join API, multi-call transaction, or compare-and-set operation.
+
+Core adds the reserved `__lnbits_owner_id__` column and scopes private operations
+to the invocation owner. Do not declare or supply that field. Each table's `id`
+is nevertheless a **table-wide primary key**, not a key unique only within one
+user's partition. Reusing `id: "settings"` for every user can collide and fail to
+save the second user's settings. Generate distinct IDs and locate configuration
+through an owner-scoped query.
+
+Private storage supports get, upsert, delete, and pagination. Pages are limited
+to 1,000 rows, with equality filters, search, and one sort key. Pagination is not
+a transactionally consistent snapshot. Large scans must fit the invocation's
+storage-call and response budgets.
+
+Public reads require explicit `public_fields`. Public pagination additionally
+requires a configured `source_id_field` and a `sourceId` in the request. Public
+append policies restrict the destination table, source table/link, allowed
+fields, and rows per source; the host derives ownership and generates the row
+ID. Public append is not permission for arbitrary updates or deletions.
+Policy keys differ: public-read policies use `table_name`, while public append
+and public-invoice policies use `table`. Copy the schema for the actual method.
+
+**There is no shared-storage host API in this checkout.** An extension-wide
+schedule does not get access to all users' rows. Do not invent `storage.shared`
+or `ext.storage.read_shared` / `ext.storage.write_shared` permissions. A shared
+collector can store rows under its extension owner and expose selected fields
+to user evaluators through approved public-read policies. The extension owner
+is separate from every user's private storage partition.
+
+Multiple invocations can run concurrently. Reading a version or processing flag
+and then writing a row is not an atomic lock. Separate writes can partially
+complete, and an HTTP timeout does not undo a payment or a stored row. Use
+durable operation IDs, immutable receipts where suitable, bounded retries, and
+reconciliation. If correctness requires an atomic primitive the host lacks,
+resolve that requirement before shipping; guest globals cannot supply it.
+
+Sources: [storage implementation and migrations](../lnbits/core/wasm_ext/storage/crud.py),
+[storage policies](../lnbits/core/wasm_ext/api/host.py).
+
+## Payments, events, and notifications
+
+Public invoice creation uses a configured source row and wallet-field policy;
+the caller does not choose an arbitrary wallet. Guest metadata is nested under
+`extra_<extension-id>`. Check the actual event fields and units: settled payment
+amounts are in millisatoshis, whereas invoice APIs also accept currency-specific
+amounts. Do not assume all numeric amounts represent sats.
+
+For settlement-driven state changes, verify status/pending state, payment hash,
+amount, wallet, source, and the extension's stored invoice binding. Store enough
+information before invoice creation to cope with settlement arriving before
+that call returns. Treat browser payment/channel messages as UI updates, not
+proof that funds were received.
+
+The event dispatcher does not provide a durable application retry queue. Handle
+duplicate attempts and recovery explicitly. A processed-hash row helps with
+replays, but a separate check and write does not make concurrent side effects
+exactly-once. Check `success` / pending status on payment responses rather than
+equating `ok` with confirmed settlement.
+
+Background payments, including payments from scheduled callbacks and public
+owner-context actions, need the extension permission plus the user's wallet
+grant. Grants restrict amount and destination policy; a per-payment cap is not
+a daily spending budget. Wallet-watch permission only enables additional incoming
+events and does not authorize spending. A shared schedule has no wallet owner.
+
+`notifications.send_user_notification` queues a message through core using the
+resolved user's saved email, Nostr, or Telegram preferences. It is not an
+arbitrary-recipient messaging API. An owner hash alone is not always enough to
+resolve a notification recipient; ordinary public owner-context requests lack
+the event wallet and logged-in user. A queued response is not a delivery receipt.
+
+Sources: [wallet and notification methods](../lnbits/core/wasm_ext/api/host.py),
+[payment events](../lnbits/core/wasm_ext/wasm/events.py).
+
+## Scheduled work
+
+Use the [core scheduler guide](devs/scheduler.md) for the exact API and supported
+cron syntax. The relevant WASM rules are:
+
+- Declare handler, cron expression, and timezone policies at installation for
+ administrator approval. Policies alone do not create jobs.
+- To start shared work automatically, declare a top-level `schedules` array in
+ `config.json`. Each entry has `handler`, `cron_expression`, and `timezone`, and
+ must exactly match a granted `scheduler.extension` policy. Handlers must be
+ unique event exports; at most 100 automatic schedules are allowed. Core creates
+ these jobs on activation and restores missing jobs on server startup. The first
+ run follows the cron expression; activation does not invoke the handler directly.
+ Existing matching jobs keep their next run, lease, and administrator pause.
+- `scheduler.user` manages the authenticated user's jobs.
+ `scheduler.extension` manages shared jobs and requires an administrator.
+ Guest management calls require interactive authenticated requests. Automatic
+ schedules are created by core using the approved manifest declaration.
+- User jobs are limited per extension, user, and handler by the approved
+ `max_jobs_per_user` policy (default 10), including paused jobs. Admins can edit
+ this limit without restarting; lowering it blocks new jobs but preserves
+ existing jobs and allows updates/deletion. Omit the job ID to create a user job;
+ reuse its ID to update it. A job's handler cannot change. Shared extension jobs
+ retain one durable job per handler. Core assigns ownership and namespace. Users cannot replace
+ the approved cron with a different expression. A callback may inspect internal conditions and
+ return without doing its application work.
+- Expressions have five fields and minute-or-longer granularity. Lists, ranges,
+ steps, month/weekday names, and whole-field `?` in a day field are supported.
+ This is not full Quartz: no seconds, years, `L`, `W`, `#`, `H`, `R`, or aliases.
+ Weekday numbering and day-field OR semantics follow standard cron.
+- Missed ticks are coalesced into one execution. A job does not overlap itself;
+ the next occurrence is calculated after completion. Failures wait for the
+ normal next occurrence. Different jobs can run concurrently.
+- Leases enable recovery, not exactly-once external effects. Disabled extensions,
+ disabled owners, and revoked permissions prevent further authorized execution;
+ cancellation cannot reverse an already completed side effect.
+
+For a price alert extension, core already exposes `utils.currencies.rate` with
+`utils.basic`, including the BTC price for the requested fiat currency. It uses
+core's rate provider/cache; it is not a guarantee of a new market quote for each
+call. A user job can fetch that rate, maintain owner-scoped history, evaluate an
+alert threshold, and request a notification. A shared price collector can use an
+automatic extension schedule and publish its extension-owned history through
+explicit public-read policies; user jobs evaluate private alerts against it.
+
+Sources: [WASM scheduler API](../lnbits/core/wasm_ext/api/scheduler.py),
+[scheduled invocation](../lnbits/core/wasm_ext/wasm/scheduler.py),
+[currency helpers](../lnbits/core/wasm_ext/api/utils.py).
+
+## Networking and live updates
+
+`http.request` is server-side, requires an authenticated/event/schedule context,
+and accepts only approved HTTPS origins. Origin matching includes the host and
+port. URL credentials, localhost, and non-public resolved IP addresses are
+rejected; redirects are not followed and proxy environment variables are not
+inherited. The body is text, limited to 65,536 UTF-8 bytes. Cookie and transport
+headers are filtered. There is no arbitrary guest socket or browser fetch access.
+
+`extension.api.request` can call approved target-extension APIs using the logged-in
+account's token. The target must be installed, active, and enabled for that user.
+Its URL construction targets the extension's `/api/` routes; it is not a generic
+core API proxy or the WASM route dispatcher. This capability is unavailable to
+scheduled callbacks and payment events because they lack the interactive token.
+InventoryStats demonstrates the interactive use case.
+
+Websockets **are supported through core**. Guests can publish with the relevant
+permission/rate policy, and the UI can subscribe/send through the parent bridge.
+Channels are extension-scoped; item IDs use a restricted character set and
+length. Browser relay messages have an 8 KiB limit and a 60 messages/second
+per-connection limit. Server publication has a separate approved rate policy.
+
+Channel messages are untrusted input. Browser relay does not invoke guest
+validation automatically. Do not send secrets on public channels or authorize
+payments from peer messages. The current hub is in-memory and process-local,
+not durable storage or a cross-worker message bus. Use authoritative API reads
+and polling/reconnection recovery where needed.
+
+Sources: [HTTP client](../lnbits/core/wasm_ext/client/http.py),
+[extension API client](../lnbits/core/wasm_ext/client/extensions.py),
+[websocket channels and limits](../lnbits/core/wasm_ext/api/websockets.py),
+[parent bridge](../lnbits/static/js/wasm-extension-component.js).
+
+## Resource limits
+
+These are current **default settings**, not values an extension can promise or
+override in `config.json`. Administrators can change defaults and installed
+extension overrides. Design bounded work even when a deployment relaxes limits.
+
+| Limit | Default |
+| ----------------------------------- | ------------------------------------------------------- |
+| Guest memory | 64 MiB |
+| Execution budget | 5,000 ms and 100,000,000 fuel |
+| Invocation request / response | 1 MiB each |
+| WASM stack | 1 MiB |
+| Component resources | 10,000 table elements, 8 instances, 10 tables, 1 memory |
+| Concurrent invocations, per process | 16 globally; 4 per extension; 4 per user |
+| Host calls per invocation | 1,000 total; 100 storage; 20 HTTP; 20 wallet |
+| Outbound HTTP | 5,000 ms timeout; 1 MiB response |
+
+The HTTP helper's fallback constants differ from the runtime's effective
+defaults; the host passes the runtime values. A guest execution deadline is not
+a universal wall-clock guarantee for stopping native threads or already-started
+host I/O. Timeouts and cancellation do not provide transaction rollback.
+
+Sources: [default settings](../lnbits/settings.py),
+[limit resolution and monitoring](../lnbits/core/services/extensions.py),
+[component execution](../lnbits/core/wasm_ext/wasm/component.py).
+
+## Build, release, and verification
+
+Use the chosen extension's build instructions and pinned dependencies, then
+verify against the intended core version. Existing repositories demonstrate
+component smoke tests, domain tests, host mocks, frontend bridge tests, and
+release-package checks. Mock success alone does not verify WIT imports, host
+authorization, browser CSP, or release installation.
+
+For a new extension:
+
+1. Check configuration, WIT, exports, routes, and permission policies against the
+ current core contract. Test actual component instantiation and a host call.
+2. Check owner isolation with two users, public projections, forged identifiers,
+ denied permissions, and unavailable invocation contexts.
+3. For payments or stateful events, check duplicates, pending/failed results,
+ concurrent attempts, partial completion, and recovery. For schedules, check
+ approved expressions, user/shared scope, deactivation, and missed runs.
+4. Exercise the UI through the actual LNbits wrapper, including save buttons,
+ asset loading, navigation, bridge errors, and CSP console messages.
+5. Build and inspect the installable ZIP. Include one top-level extension
+ directory containing config, the compiled module, required WIT, UI/assets,
+ schema, and migrations. Exclude files the WASM installer rejects.
+6. Check installation, approval, migration, activation, and update with the
+ target LNbits version. Copying a folder alone does not complete this flow.
+
+WASM extensions live under `LNBITS_WASM_EXTENSIONS_PATH`, defaulting to
+`<LNBITS_DATA_FOLDER>/wasm_extensions`. They must remain outside Python-importable
+extension and upgrade directories. Old examples using
+`lnbits/extensions/<id>` should not be followed for this checkout.
+
+The installer rejects `.py`, `.pyc`, `.pyo`, `.so`, and `.pyd` files anywhere in a
+WASM package, including development/test helpers. A repository may contain such
+tools, but its automatic GitHub source ZIP can consequently be unsuitable.
+For example, the reviewed PaySplit v0.2.2 source tree includes
+[`dev/test_notifications.py`](https://github.com/lnbits/paysplit/blob/ae9f3e9c9c33d0f4ab9f2fd595ce22a873498af4/dev/test_notifications.py);
+packaging that file would fail this checkout's installer. Inspect the selected
+release artifact rather than assuming the source archive is installable.
+
+Registry manifests can describe repository discovery or explicit release
+entries. Keep extension identity, release version, package contents, and minimum
+core version consistent. A minimum-version string does not prove that an older
+WIT contract or copied SDK matches a locally modified host.
+
+Sources: [installer and archive validation](../lnbits/core/models/extensions.py),
+[WASM loader](../lnbits/core/wasm_ext/wasm/loader.py),
+[host tests](../tests/unit/test_wasm_extension_host_api.py),
+[component tests](../tests/unit/test_wasm_extension_component.py),
+[frontend contract tests](../tests/unit/test_wasm_extension_frontend.py).
+
+## Differences from older extension documentation
+
+| Statement or copied pattern | Guidance for this checkout |
+| ------------------------------------------------------------------- | ----------------------------------------------------------------------------------- |
+| Websockets are unavailable, or a game is only a polling placeholder | Inspect its actual code; core supports mediated channels and several games use them |
+| Mount Vue over HTML templates | Use render functions or compile templates during the build |
+| A normal submit button is sufficient | Validate and save through an explicit handler in the sandbox |
+| Copy SVGs or fetch JSON from `static/` | The static suffix allowlist excludes both |
+| Install under `lnbits/extensions` | Use the separate WASM directory and normal approval/registration flow |
+| Put runtime limits in extension config | Limits come from core settings and installed-extension overrides |
+| Every user can save the same settings row ID | IDs are table-wide; generate distinct IDs |
+| A version field or `redeeming` flag provides a lock | Storage has no compare-and-set or multi-call transaction |
+| A shared scheduled job can read every user's private rows | It has a separate extension storage owner; cross-owner reads need public policies |
+| HTTP always has a 10-second / 256 KiB limit | Runtime defaults passed by core are 5 seconds / 1 MiB |
+
+Recheck the linked core code when it changes. Update this guide when a host
+capability, permission contract, sandbox policy, scheduler rule, or package
+format changes; treat example READMEs as supporting material.
+
+## Review inventory
+
+The table records every registry entry. Where a repository has multiple entries,
+the older tagged source was compared with the newest listed release. Code links
+point to immutable commits. Documentation was read where present, including
+Tips' `agent.md`, Forms' `AGENTS.md` and design notes, and ZapGoals' policy and test
+notes. Repositories without a README were reviewed through code and configuration.
+
+| Extension | All listed releases | Guest | Reviewed code / documentation | Useful example |
+| ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
+| battleshipswasm | [v0.1.2](https://github.com/lnbits/battleshipswasm/tree/ac62fa9b843f4f3e5af8fffc3c3a9801c36ab1b9), [v0.1.6](https://github.com/lnbits/battleshipswasm/tree/b3eec844791624b77388c1da1d623575c4a3d819) | JavaScript | [code](https://github.com/lnbits/battleshipswasm/blob/b3eec844791624b77388c1da1d623575c4a3d819/dev/src/index.js) · [config](https://github.com/lnbits/battleshipswasm/blob/b3eec844791624b77388c1da1d623575c4a3d819/config.json) · [README.md](https://github.com/lnbits/battleshipswasm/blob/b3eec844791624b77388c1da1d623575c4a3d819/README.md) | Private fleets, paid player access, action IDs, and state-version checks. |
+| bigpayment | [v0.1.1](https://github.com/lnbits/bigpayment/tree/d68736e60a1a122af2bea6e3eb03dd39342f4420) | Rust | [code](https://github.com/lnbits/bigpayment/blob/d68736e60a1a122af2bea6e3eb03dd39342f4420/dev/src/lib.rs) · [config](https://github.com/lnbits/bigpayment/blob/d68736e60a1a122af2bea6e3eb03dd39342f4420/config.json) | Authenticated wallet aggregation and outgoing payment results; partial transfers need handling. |
+| chesswasm | [v0.1.4](https://github.com/lnbits/chesswasm/tree/f2a6c94477bc0205ff610c46c7a4ee1cc160f34c), [v0.1.7](https://github.com/lnbits/chesswasm/tree/6f0bd55f559daa1a5950a45e39aa0ca8a69c7bb1) | JavaScript | [code](https://github.com/lnbits/chesswasm/blob/6f0bd55f559daa1a5950a45e39aa0ca8a69c7bb1/dev/src/index.js) · [config](https://github.com/lnbits/chesswasm/blob/6f0bd55f559daa1a5950a45e39aa0ca8a69c7bb1/config.json) · [README.md](https://github.com/lnbits/chesswasm/blob/6f0bd55f559daa1a5950a45e39aa0ca8a69c7bb1/README.md) | Guest-side move validation, player authorization, and duplicate-action handling. |
+| forms | [v0.2.5](https://github.com/bitkarrot/forms/tree/7930173bb5d3475660af502bdb936ebbd9aa4a14) | Rust | [code](https://github.com/bitkarrot/forms/blob/7930173bb5d3475660af502bdb936ebbd9aa4a14/wasm/src/lib.rs) · [config](https://github.com/bitkarrot/forms/blob/7930173bb5d3475660af502bdb936ebbd9aa4a14/config.json) · [README.md](https://github.com/bitkarrot/forms/blob/7930173bb5d3475660af502bdb936ebbd9aa4a14/README.md) · [AGENTS.md](https://github.com/bitkarrot/forms/blob/7930173bb5d3475660af502bdb936ebbd9aa4a14/AGENTS.md) | Validated free/paid submissions, invoice bindings, notifications, and precompiled Vue templates. |
+| giftcardswasm | [v0.3.0](https://github.com/bitkarrot/giftcardswasm/tree/1fa537459e10966f1542365c49b8dfd1705cb6b4) | Rust | [code](https://github.com/bitkarrot/giftcardswasm/blob/1fa537459e10966f1542365c49b8dfd1705cb6b4/wasm/src/lib.rs) · [config](https://github.com/bitkarrot/giftcardswasm/blob/1fa537459e10966f1542365c49b8dfd1705cb6b4/config.json) · [README.md](https://github.com/bitkarrot/giftcardswasm/blob/1fa537459e10966f1542365c49b8dfd1705cb6b4/README.md) | Hashed claim tokens, public owner context, LNURL redemption, and explicit storage-race limitations. |
+| inventorystats | [v0.1.1](https://github.com/lnbits/inventorystats/tree/19050c29b681e051ae38224168e57242768627c8) | JavaScript | [code](https://github.com/lnbits/inventorystats/blob/19050c29b681e051ae38224168e57242768627c8/dev/src/index.js) · [config](https://github.com/lnbits/inventorystats/blob/19050c29b681e051ae38224168e57242768627c8/config.json) · [README.md](https://github.com/lnbits/inventorystats/blob/19050c29b681e051ae38224168e57242768627c8/README.md) | Interactive calls to the Inventory Python extension, pagination, and dashboard calculations. |
+| lnq1 | [v0.1.4](https://github.com/lnbits/lnq1/tree/f6a4a46204aa639a345b60f029ba5ce01d8150be), [v0.1.5](https://github.com/lnbits/lnq1/tree/22775d1fcbd8d00cda8a5bd6473b2ab14e4cba11) | JavaScript | [code](https://github.com/lnbits/lnq1/blob/22775d1fcbd8d00cda8a5bd6473b2ab14e4cba11/dev/src/index.js) · [config](https://github.com/lnbits/lnq1/blob/22775d1fcbd8d00cda8a5bd6473b2ab14e4cba11/config.json) · [README.md](https://github.com/lnbits/lnq1/blob/22775d1fcbd8d00cda8a5bd6473b2ab14e4cba11/README.md) | Browser game integration, player presence, paid gameplay, and parent-bridge channels. |
+| paysplit | [v0.1.1](https://github.com/lnbits/paysplit/tree/092e8995a2c552612c764e2219f39340e927e648), [v0.2.2](https://github.com/lnbits/paysplit/tree/ae9f3e9c9c33d0f4ab9f2fd595ce22a873498af4) | C | [code](https://github.com/lnbits/paysplit/blob/ae9f3e9c9c33d0f4ab9f2fd595ce22a873498af4/dev/src/paysplit.c) · [config](https://github.com/lnbits/paysplit/blob/ae9f3e9c9c33d0f4ab9f2fd595ce22a873498af4/config.json) | Watched wallet events, background LNURL splits, and user notifications. |
+| pingpong | [v0.1.1](https://github.com/lnbits/pingpong/tree/6f1f013c62214823e90f870ab6a221348b06d403) | JavaScript | [code](https://github.com/lnbits/pingpong/blob/6f1f013c62214823e90f870ab6a221348b06d403/dev/src/index.js) · [config](https://github.com/lnbits/pingpong/blob/6f1f013c62214823e90f870ab6a221348b06d403/config.json) | Token-authorized public games, invoices, and winner payouts. |
+| poker | [v0.1.2](https://github.com/lnbits/poker/tree/8bbaf5f035268339ff9ac12a8f4cffebf5ba0f7d) | JavaScript | [code](https://github.com/lnbits/poker/blob/8bbaf5f035268339ff9ac12a8f4cffebf5ba0f7d/dev/src/index.js) · [config](https://github.com/lnbits/poker/blob/8bbaf5f035268339ff9ac12a8f4cffebf5ba0f7d/config.json) · [README.md](https://github.com/lnbits/poker/blob/8bbaf5f035268339ff9ac12a8f4cffebf5ba0f7d/README.md) | Persistent rounds, private hand projections, and payout tracking. |
+| popmenu | [v0.1.0](https://github.com/lnbits/popmenu/tree/42638e8df2efbe3ed4ae17d9030c97b455691c3b) | JavaScript | [code](https://github.com/lnbits/popmenu/blob/42638e8df2efbe3ed4ae17d9030c97b455691c3b/dev/src/domain.js) · [config](https://github.com/lnbits/popmenu/blob/42638e8df2efbe3ed4ae17d9030c97b455691c3b/config.json) · [README.md](https://github.com/lnbits/popmenu/blob/42638e8df2efbe3ed4ae17d9030c97b455691c3b/README.md) | Menus, order/payment state, decimal calculations, and separate domain/host/component tests. |
+| satoshisplacewasm | [v0.1.4](https://github.com/lnbits/satoshisplacewasm/tree/971ab69589372d8d47de9a6399c07a7096bdf4e3) | JavaScript | [code](https://github.com/lnbits/satoshisplacewasm/blob/971ab69589372d8d47de9a6399c07a7096bdf4e3/dev/src/index.js) · [config](https://github.com/lnbits/satoshisplacewasm/blob/971ab69589372d8d47de9a6399c07a7096bdf4e3/config.json) · [README.md](https://github.com/lnbits/satoshisplacewasm/blob/971ab69589372d8d47de9a6399c07a7096bdf4e3/README.md) | Paid pixel updates, compact invoice metadata, and public canvas data. |
+| streetfighterwasm | [v0.1.5](https://github.com/lnbits/streetfighterwasm/tree/62eede95d2287d4aa16eb7580c8d69c7cf5f8e89), [v0.1.6](https://github.com/lnbits/streetfighterwasm/tree/2355a203013ba6b6d25ec7b97e5555a0a9f3c277) | JavaScript | [code](https://github.com/lnbits/streetfighterwasm/blob/2355a203013ba6b6d25ec7b97e5555a0a9f3c277/dev/src/index.js) · [config](https://github.com/lnbits/streetfighterwasm/blob/2355a203013ba6b6d25ec7b97e5555a0a9f3c277/config.json) · [README.md](https://github.com/lnbits/streetfighterwasm/blob/2355a203013ba6b6d25ec7b97e5555a0a9f3c277/README.md) | Canvas game, player-token checks, live input/state messaging, and paid matches. |
+| supportchat | [v0.2.2](https://github.com/lnbits/supportchat/tree/b0abb1986117ada2a6c31e64627de6a67c7e2b32) | JavaScript | [code](https://github.com/lnbits/supportchat/blob/b0abb1986117ada2a6c31e64627de6a67c7e2b32/dev/src/index.js) · [config](https://github.com/lnbits/supportchat/blob/b0abb1986117ada2a6c31e64627de6a67c7e2b32/config.json) | Public append policies, source-scoped conversations, widgets, and live messages. |
+| tips | [v0.1.4](https://github.com/lnbits/tips/tree/c7195fbd203c1eb207dd974087b53b20c4596317) | JavaScript | [code](https://github.com/lnbits/tips/blob/c7195fbd203c1eb207dd974087b53b20c4596317/dev/src/index.js) · [config](https://github.com/lnbits/tips/blob/c7195fbd203c1eb207dd974087b53b20c4596317/config.json) · [README.md](https://github.com/lnbits/tips/blob/c7195fbd203c1eb207dd974087b53b20c4596317/README.md) · [agent.md](https://github.com/lnbits/tips/blob/c7195fbd203c1eb207dd974087b53b20c4596317/agent.md) | Public tip jars, source-bound invoices, declarative migrations, and detailed authoring notes. |
+| zapgoalswasm | [v0.5.2](https://github.com/bitkarrot/zapgoalswasm/tree/052a7299b5693a7e60afb39043caff0e01d146ba) | Rust | [code](https://github.com/bitkarrot/zapgoalswasm/blob/052a7299b5693a7e60afb39043caff0e01d146ba/wasm/src/lib.rs) · [config](https://github.com/bitkarrot/zapgoalswasm/blob/052a7299b5693a7e60afb39043caff0e01d146ba/config.json) · [README.md](https://github.com/bitkarrot/zapgoalswasm/blob/052a7299b5693a7e60afb39043caff0e01d146ba/README.md) | Verified immutable payment receipts, recurring-goal projections, sweeps, and precompiled UI. |
+
+The older Chess, Battleships, StreetFighter, and LNQ1 entries illustrate the
+fixed-settings-ID problem; their newer listed releases generate distinct IDs.
+Chess and Battleships also add action IDs/state versions, and PaySplit adds
+notification support. Those changes do not supply an atomic storage primitive.
+
+These examples demonstrate possibilities, not guarantees of production safety.
+For example, GiftCards explicitly discusses the lack of compare-and-set around
+redemption, and multi-wallet or multi-recipient payments can partially complete.
+None of the registry examples is the specification for the scheduler or a missing
+host capability; use this checkout's core implementation and tests for those.
diff --git a/lnbits/app.py b/lnbits/app.py
index 38904c1..b936dcf 100644
--- a/lnbits/app.py
+++ b/lnbits/app.py
@@ -41,6 +41,7 @@ from lnbits.core.services.payments import (
check_pending_payments,
fundingsource_invoice_producer,
)
+from lnbits.core.services.scheduler import scheduler, stop_scheduler_safely
from lnbits.core.tasks import (
audit_queue,
collect_exchange_rates_data,
@@ -57,6 +58,7 @@ from lnbits.core.wasm_ext.wasm.loader import (
is_wasm_extension_dir,
is_wasm_extension_id,
)
+from lnbits.core.wasm_ext.wasm.scheduler import ensure_wasm_extension_schedules
from lnbits.exceptions import register_exception_handlers
from lnbits.helpers import version_parse
from lnbits.llms_txt import create_llms_txt_route
@@ -149,9 +151,10 @@ async def shutdown():
settings.lnbits_running = False
# shutdown event
+ await stop_scheduler_safely()
task_manager.cancel_all_tasks()
- # wait a bit to allow them to finish, so that cleanup can run without problems
+ # Give cancelled tasks a chance to finish their cleanup.
await asyncio.sleep(0.1)
funding_source = get_funding_source()
await funding_source.cleanup()
@@ -563,6 +566,7 @@ async def check_and_register_extensions(app: FastAPI) -> None:
try:
if is_wasm_extension_id(ext.code):
register_wasm_extension(app, ext.code)
+ await ensure_wasm_extension_schedules(ext.code)
continue
register_ext_routes(app, ext)
register_ext_tasks(ext)
@@ -577,6 +581,7 @@ def register_async_tasks() -> None:
# listen to all incoming payments and dispatch payment notifications
# note: should be the first in task list for a bit quicker notifications
task_manager.register_invoice_listener(dispatch_payment_notification, "core")
+ task_manager.create_permanent_task(scheduler.run, name="core_scheduler")
# Core onchain wallets retain their snapshots when no browser is open.
task_manager.create_permanent_task(sync_wallets, interval=60)
diff --git a/lnbits/core/__init__.py b/lnbits/core/__init__.py
index 7b9757c..f5ac3e7 100644
--- a/lnbits/core/__init__.py
+++ b/lnbits/core/__init__.py
@@ -18,6 +18,7 @@ from .views.lnurl_api import lnurl_router
from .views.node_api import node_router, public_node_router, super_node_router
from .views.onchain_api import onchain_router
from .views.payment_api import payment_router
+from .views.scheduler_api import scheduler_router
from .views.tinyurl_api import tinyurl_router
from .views.two_factor_api import two_factor_router
from .views.user_api import users_router
@@ -51,6 +52,7 @@ def init_core_routers(app: FastAPI):
app.include_router(webpush_router)
app.include_router(users_router)
app.include_router(audit_router)
+ app.include_router(scheduler_router)
app.include_router(asset_router)
app.include_router(fiat_router)
app.include_router(lnurl_router)
diff --git a/lnbits/core/crud/scheduler.py b/lnbits/core/crud/scheduler.py
new file mode 100644
index 0000000..f18c01a
--- /dev/null
+++ b/lnbits/core/crud/scheduler.py
@@ -0,0 +1,333 @@
+from lnbits.core.db import db
+from lnbits.core.models.scheduler import (
+ ScheduledJob,
+ ScheduledJobFilters,
+ ScheduledJobRun,
+ ScheduledJobRunFilters,
+ ScheduledJobRunStatus,
+ ScheduledJobSummary,
+)
+from lnbits.db import Filters, Page
+
+
+async def save_scheduled_job(job: ScheduledJob) -> ScheduledJob:
+ result = await db.execute(
+ """
+ INSERT INTO scheduled_jobs
+ (id, namespace, user_id, handler, cron_expression, timezone,
+ payload_json, enabled, next_run_at)
+ VALUES
+ (:id, :namespace, :user_id, :handler, :cron_expression, :timezone,
+ :payload_json, :enabled, :next_run_at)
+ ON CONFLICT (id) DO UPDATE SET
+ cron_expression = excluded.cron_expression,
+ timezone = excluded.timezone,
+ payload_json = excluded.payload_json,
+ enabled = excluded.enabled,
+ next_run_at = excluded.next_run_at
+ WHERE scheduled_jobs.namespace = excluded.namespace
+ AND scheduled_jobs.handler = excluded.handler
+ AND (scheduled_jobs.user_id = excluded.user_id
+ OR (scheduled_jobs.user_id IS NULL AND excluded.user_id IS NULL))
+ """,
+ job.dict(),
+ )
+ if result.rowcount != 1:
+ raise PermissionError(
+ "Schedule ID is already in use by another owner or handler."
+ )
+ stored = await get_scheduled_job(job.id)
+ assert stored
+ return stored
+
+
+async def get_scheduled_job(job_id: str) -> ScheduledJob | None:
+ return await db.fetchone(
+ "SELECT * FROM scheduled_jobs WHERE id = :id",
+ {"id": job_id},
+ ScheduledJob,
+ )
+
+
+async def get_scheduled_jobs_count(namespace: str, user_id: str, handler: str) -> int:
+ row: dict | None = await db.fetchone(
+ """
+ SELECT COUNT(*) AS count FROM scheduled_jobs
+ WHERE namespace = :namespace AND user_id = :user_id AND handler = :handler
+ """,
+ {"namespace": namespace, "user_id": user_id, "handler": handler},
+ )
+ return int(row["count"]) if row else 0
+
+
+async def get_scheduled_jobs_paginated(
+ namespace: str, user_id: str | None, *, limit: int = 100, offset: int = 0
+) -> Page[ScheduledJob]:
+ return await db.fetch_page(
+ "SELECT * FROM scheduled_jobs",
+ where=[
+ "namespace = :namespace",
+ "(user_id = :user_id "
+ "OR (user_id IS NULL AND CAST(:user_id AS TEXT) IS NULL))",
+ ],
+ values={"namespace": namespace, "user_id": user_id},
+ filters=Filters(limit=limit, offset=offset, sortby="id"),
+ model=ScheduledJob,
+ table_name="scheduled_jobs",
+ )
+
+
+async def get_scheduled_jobs_overview_paginated(
+ filters: Filters[ScheduledJobFilters],
+) -> Page[ScheduledJobSummary]:
+ if not filters.sortby:
+ filters.sortby = "next_run_at"
+ return await db.fetch_page(
+ """
+ SELECT * FROM (
+ SELECT job.id, job.namespace, job.handler, job.cron_expression,
+ job.timezone, job.enabled, job.next_run_at,
+ job.user_id, account.username, account.email,
+ last_run.started_at AS last_run_at,
+ last_run.status AS last_result,
+ CASE WHEN job.user_id IS NOT NULL THEN 'user'
+ WHEN job.namespace = 'core' THEN 'core'
+ ELSE 'extension' END AS scope
+ FROM scheduled_jobs AS job
+ LEFT JOIN accounts AS account ON account.id = job.user_id
+ LEFT JOIN scheduled_job_runs AS last_run ON last_run.id = (
+ SELECT id FROM scheduled_job_runs
+ WHERE job_id = job.id AND namespace = job.namespace
+ ORDER BY started_at DESC, id DESC LIMIT 1
+ )
+ ) AS jobs
+ """,
+ filters=filters,
+ model=ScheduledJobSummary,
+ )
+
+
+async def get_scheduled_job_sources() -> list[str]:
+ rows: list[dict] = await db.fetchall(
+ "SELECT DISTINCT namespace FROM scheduled_jobs ORDER BY namespace"
+ )
+ return [row["namespace"] for row in rows]
+
+
+async def delete_scheduled_job(
+ job_id: str, namespace: str, user_id: str | None, now: int
+) -> bool:
+ # Preserve an active claim: deleting and recreating the ID could overlap it.
+ result = await db.execute(
+ """
+ DELETE FROM scheduled_jobs WHERE id = :id AND namespace = :namespace
+ AND (user_id = :user_id
+ OR (user_id IS NULL AND CAST(:user_id AS TEXT) IS NULL))
+ AND (lease_token IS NULL OR lease_until <= :now)
+ """,
+ {"id": job_id, "namespace": namespace, "user_id": user_id, "now": now},
+ )
+ return result.rowcount == 1
+
+
+async def delete_namespace_schedules(namespace: str) -> None:
+ await db.execute(
+ "DELETE FROM scheduled_jobs WHERE namespace = :namespace",
+ {"namespace": namespace},
+ )
+
+
+async def disable_user_schedules(user_id: str) -> None:
+ await db.execute(
+ """
+ UPDATE scheduled_jobs SET enabled = false
+ WHERE user_id = :user_id AND enabled = true
+ """,
+ {"user_id": user_id},
+ )
+
+
+async def get_due_scheduled_jobs(now: int, limit: int) -> list[ScheduledJob]:
+ return await db.fetchall(
+ """
+ SELECT * FROM scheduled_jobs
+ WHERE enabled = true AND next_run_at <= :now
+ AND (lease_token IS NULL OR lease_until <= :now)
+ ORDER BY next_run_at, id LIMIT :limit
+ """,
+ {"now": now, "limit": limit},
+ ScheduledJob,
+ )
+
+
+async def claim_scheduled_job(
+ job_id: str, token: str, now: int, lease_until: int
+) -> ScheduledJob | None:
+ result = await db.execute(
+ """
+ UPDATE scheduled_jobs SET lease_token = :token, lease_until = :lease_until
+ WHERE id = :id AND enabled = true AND next_run_at <= :now
+ AND (lease_token IS NULL OR lease_until <= :now)
+ """,
+ {"id": job_id, "token": token, "now": now, "lease_until": lease_until},
+ )
+ if result.rowcount != 1:
+ return None
+ job = await get_scheduled_job(job_id)
+ return job if job and job.lease_token == token else None
+
+
+async def renew_scheduled_job(job_id: str, token: str, now: int, until: int) -> bool:
+ result = await db.execute(
+ """
+ UPDATE scheduled_jobs SET lease_until = :until
+ WHERE id = :id AND lease_token = :token AND lease_until > :now
+ AND enabled = true
+ """,
+ {"id": job_id, "token": token, "now": now, "until": until},
+ )
+ return result.rowcount == 1
+
+
+async def finish_scheduled_job(job: ScheduledJob, next_run: int | None) -> None:
+ await db.execute(
+ """
+ UPDATE scheduled_jobs
+ SET next_run_at = CASE
+ WHEN cron_expression = :cron_expression AND timezone = :timezone
+ THEN :next_run ELSE next_run_at END,
+ lease_token = NULL, lease_until = 0
+ WHERE id = :id AND lease_token = :lease_token
+ """,
+ {**job.dict(), "next_run": next_run},
+ )
+
+
+async def create_scheduled_job_run(job: ScheduledJob, now: float) -> ScheduledJobRun:
+ assert job.lease_token
+ run = ScheduledJobRun(
+ job_id=job.id,
+ namespace=job.namespace,
+ handler=job.handler,
+ scope=(
+ "user"
+ if job.user_id
+ else "core" if job.namespace == "core" else "extension"
+ ),
+ timezone=job.timezone,
+ scheduled_at=job.next_run_at,
+ started_at=now,
+ )
+ await db.execute(
+ """
+ INSERT INTO scheduled_job_runs
+ (id, job_id, namespace, handler, scope, timezone, scheduled_at,
+ started_at, status, lease_token, user_id)
+ VALUES (:id, :job_id, :namespace, :handler, :scope, :timezone,
+ :scheduled_at, :started_at, :status, :lease_token, :user_id)
+ """,
+ {**run.dict(), "lease_token": job.lease_token, "user_id": job.user_id},
+ )
+ return run
+
+
+async def finish_scheduled_job_run(
+ run_id: str,
+ status: ScheduledJobRunStatus,
+ now: float,
+ error_summary: str | None = None,
+) -> None:
+ await db.execute(
+ """
+ UPDATE scheduled_job_runs
+ SET status = :status, finished_at = :now, error_summary = :error_summary
+ WHERE id = :id AND status = 'running'
+ """,
+ {"id": run_id, "status": status, "now": now, "error_summary": error_summary},
+ )
+
+
+async def get_scheduled_job_runs_paginated(
+ filters: Filters[ScheduledJobRunFilters],
+) -> Page[ScheduledJobRun]:
+ if not filters.sortby:
+ filters.sortby = "started_at"
+ filters.direction = "desc"
+ return await db.fetch_page(
+ """
+ SELECT id, job_id, namespace, handler, scope, timezone, scheduled_at,
+ started_at, finished_at, status, error_summary
+ FROM scheduled_job_runs
+ """,
+ filters=filters,
+ model=ScheduledJobRun,
+ table_name="scheduled_job_runs",
+ )
+
+
+async def interrupt_expired_scheduled_job_runs(now: float) -> None:
+ # Check the durable claim, not local tasks: another process may own this run.
+ # The actual finish time is unknown after a crash, so leave it unset.
+ await db.execute(
+ """
+ UPDATE scheduled_job_runs
+ SET status = 'interrupted', error_summary = :error_summary
+ WHERE status = 'running' AND NOT EXISTS (
+ SELECT 1 FROM scheduled_jobs
+ WHERE scheduled_jobs.id = scheduled_job_runs.job_id
+ AND scheduled_jobs.lease_token = scheduled_job_runs.lease_token
+ AND scheduled_jobs.lease_until > :now
+ )
+ """,
+ {
+ "now": now,
+ "error_summary": "Execution ended without a recorded result; "
+ "its lease is no longer active.",
+ },
+ )
+
+
+async def delete_expired_scheduled_job_runs(
+ cutoff: float, failed_cutoff: float
+) -> None:
+ await db.execute(
+ """
+ DELETE FROM scheduled_job_runs
+ WHERE (status NOT IN ('running', 'failed')
+ AND COALESCE(finished_at, started_at) < :cutoff)
+ OR (status = 'failed'
+ AND COALESCE(finished_at, started_at) < :failed_cutoff)
+ """,
+ {"cutoff": cutoff, "failed_cutoff": failed_cutoff},
+ )
+
+
+async def delete_excess_scheduled_job_runs(
+ max_runs_per_user: int,
+ max_runs_per_extension: int,
+ preferred_status: ScheduledJobRunStatus,
+) -> None:
+ await db.execute(
+ """
+ DELETE FROM scheduled_job_runs WHERE id IN (
+ SELECT id FROM (
+ SELECT id, scope, ROW_NUMBER() OVER (
+ PARTITION BY scope,
+ CASE WHEN scope = 'user' THEN user_id ELSE namespace END
+ ORDER BY CASE WHEN status = :preferred_status THEN 0 ELSE 1 END,
+ COALESCE(finished_at, started_at) DESC, id DESC
+ ) AS position
+ FROM scheduled_job_runs
+ WHERE status != 'running'
+ AND scope IN ('user', 'extension')
+ ) AS ranked_runs
+ WHERE (scope = 'user' AND position > :max_runs_per_user)
+ OR (scope = 'extension' AND position > :max_runs_per_extension)
+ )
+ """,
+ {
+ "max_runs_per_user": max_runs_per_user,
+ "max_runs_per_extension": max_runs_per_extension,
+ "preferred_status": preferred_status,
+ },
+ )
diff --git a/lnbits/core/migrations.py b/lnbits/core/migrations.py
index 7d65f57..4ab8567 100644
--- a/lnbits/core/migrations.py
+++ b/lnbits/core/migrations.py
@@ -968,3 +968,54 @@ async def m053_balances_view_include_onchain(db: Connection):
AND (wallets.deleted = false OR wallets.deleted is NULL)
GROUP BY wallets.id
""")
+
+
+async def m054_create_scheduled_jobs(db: Connection):
+ """One shared schedule store for core, Python and WASM callbacks."""
+ await db.execute("""
+ CREATE TABLE scheduled_jobs (
+ id TEXT PRIMARY KEY,
+ namespace TEXT NOT NULL,
+ handler TEXT NOT NULL,
+ user_id TEXT,
+ cron_expression TEXT NOT NULL,
+ timezone TEXT NOT NULL DEFAULT 'UTC',
+ payload_json TEXT NOT NULL DEFAULT '{}',
+ enabled BOOLEAN NOT NULL DEFAULT true,
+ next_run_at BIGINT,
+ lease_token TEXT,
+ lease_until BIGINT NOT NULL DEFAULT 0
+ )
+ """)
+ await db.execute("""
+ CREATE INDEX idx_scheduled_jobs_due ON scheduled_jobs (enabled, next_run_at)
+ """)
+
+
+async def m055_create_scheduled_job_runs(db: Connection):
+ # No foreign key: history survives deletion of its job until retention expires.
+ await db.execute("""
+ CREATE TABLE scheduled_job_runs (
+ id TEXT PRIMARY KEY,
+ job_id TEXT NOT NULL,
+ namespace TEXT NOT NULL,
+ user_id TEXT,
+ handler TEXT NOT NULL,
+ scope TEXT NOT NULL,
+ timezone TEXT NOT NULL,
+ scheduled_at BIGINT,
+ started_at DOUBLE PRECISION NOT NULL,
+ finished_at DOUBLE PRECISION,
+ status TEXT NOT NULL,
+ error_summary TEXT,
+ lease_token TEXT NOT NULL
+ )
+ """)
+ await db.execute("""
+ CREATE INDEX idx_scheduled_job_runs_job
+ ON scheduled_job_runs (job_id, started_at DESC, id DESC)
+ """)
+ await db.execute("""
+ CREATE INDEX idx_scheduled_job_runs_status
+ ON scheduled_job_runs (status, started_at)
+ """)
diff --git a/lnbits/core/models/scheduler.py b/lnbits/core/models/scheduler.py
new file mode 100644
index 0000000..77167ad
--- /dev/null
+++ b/lnbits/core/models/scheduler.py
@@ -0,0 +1,158 @@
+import json
+from typing import Any, Literal
+from uuid import uuid4
+from zoneinfo import ZoneInfo
+
+from pydantic import BaseModel, Field, validator
+
+from lnbits.db import FilterModel
+from lnbits.utils.cron import normalize_cron
+
+ScheduledJobRunStatus = Literal[
+ "running", "succeeded", "failed", "cancelled", "interrupted", "skipped"
+]
+
+
+class SchedulePolicy(BaseModel):
+ handler: str = Field(..., regex=r"^[A-Za-z0-9_-]{1,128}$")
+ cron_expression: str = Field(..., min_length=1, max_length=256)
+ timezone: str = Field(default="UTC", max_length=128)
+
+ class Config:
+ extra = "forbid"
+
+ @validator("cron_expression")
+ def validate_cron(cls, expression: str) -> str:
+ return normalize_cron(expression)
+
+ @validator("timezone")
+ def validate_timezone(cls, zone: str) -> str:
+ try:
+ ZoneInfo(zone)
+ except (KeyError, ValueError) as exc:
+ raise ValueError("Unknown IANA timezone.") from exc
+ return zone
+
+ @staticmethod
+ def parse_policies(
+ policies: list[Any] | None, *, user_scope: bool = False
+ ) -> dict[str, "SchedulePolicy"]:
+ if not policies:
+ raise ValueError(
+ "Scheduling permission requires per-handler cron policies."
+ )
+ parsed: dict[str, SchedulePolicy] = {}
+ for policy in policies:
+ if not isinstance(policy, dict):
+ raise ValueError("Schedule policy must be an object.")
+ model = UserSchedulePolicy if user_scope else SchedulePolicy
+ schedule = model.parse_obj(policy)
+ if schedule.handler in parsed:
+ raise ValueError(
+ "Schedule policies must have unique handlers per scope."
+ )
+ parsed[schedule.handler] = schedule
+ return parsed
+
+
+class UserSchedulePolicy(SchedulePolicy):
+ max_jobs_per_user: int = Field(default=10, ge=1)
+
+ @validator("max_jobs_per_user", pre=True)
+ def validate_job_limit(cls, value: Any) -> int:
+ if isinstance(value, bool) or not isinstance(value, int):
+ raise ValueError("Max jobs per user must be a positive integer.")
+ return value
+
+
+class ScheduleConfig(SchedulePolicy):
+ id: str = Field(
+ default_factory=lambda: uuid4().hex, regex=r"^[A-Za-z0-9_.:-]{1,128}$"
+ )
+ payload_json: str = Field(default="{}", max_length=8192)
+ enabled: bool = True
+
+ @validator("payload_json")
+ def validate_payload(cls, value: str) -> str:
+ payload = json.loads(value)
+ if not isinstance(payload, dict):
+ raise ValueError("Schedule payload must be a JSON object.")
+ # Escape HTML-sensitive characters before the database's generic string
+ # sanitization; decoding the JSON must preserve the caller's data.
+ value = json.dumps(payload, ensure_ascii=False, allow_nan=False)
+ for character in "<>&":
+ value = value.replace(character, f"\\u{ord(character):04x}")
+ if len(value.encode()) > 8192:
+ raise ValueError("Schedule payload must not exceed 8192 bytes.")
+ return value
+
+
+class ScheduledJob(ScheduleConfig):
+ namespace: str
+ user_id: str | None = None
+ next_run_at: int | None = None
+ lease_token: str | None = None
+ lease_until: int = 0
+
+ def public_data(self) -> dict:
+ return self.dict(exclude={"namespace", "user_id", "lease_token", "lease_until"})
+
+
+class ScheduledJobRun(BaseModel):
+ id: str = Field(default_factory=lambda: uuid4().hex)
+ job_id: str
+ namespace: str
+ handler: str
+ scope: Literal["core", "extension", "user"]
+ timezone: str
+ scheduled_at: int | None = None
+ started_at: float
+ finished_at: float | None = None
+ status: ScheduledJobRunStatus = "running"
+ error_summary: str | None = None
+
+
+class ScheduledJobRunFilters(FilterModel):
+ __search_fields__ = ["job_id", "namespace", "handler"]
+ __sort_fields__ = ["started_at", "finished_at", "status"]
+
+ job_id: str | None = None
+ namespace: str | None = None
+ user_id: str | None = None
+ status: ScheduledJobRunStatus | None = None
+
+
+class ScheduledJobSummary(BaseModel):
+ id: str
+ namespace: str
+ handler: str
+ scope: Literal["core", "extension", "user"]
+ user_id: str | None = None
+ username: str | None = None
+ email: str | None = None
+ cron_expression: str
+ timezone: str
+ enabled: bool
+ next_run_at: int | None = None
+ last_run_at: float | None = None
+ last_result: ScheduledJobRunStatus | None = None
+
+
+class ScheduledJobFilters(FilterModel):
+ __search_fields__ = ["id", "namespace", "handler"]
+ __sort_fields__ = [
+ "id",
+ "namespace",
+ "handler",
+ "scope",
+ "enabled",
+ "next_run_at",
+ "last_run_at",
+ "last_result",
+ ]
+
+ namespace: str | None = None
+ handler: str | None = None
+ enabled: bool | None = None
+ scope: Literal["core", "extension", "user"] | None = None
+ user_id: str | None = None
diff --git a/lnbits/core/services/extensions.py b/lnbits/core/services/extensions.py
index f3ab6db..2b33161 100644
--- a/lnbits/core/services/extensions.py
+++ b/lnbits/core/services/extensions.py
@@ -1,6 +1,5 @@
import asyncio
import importlib
-import re
from collections.abc import Mapping
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
@@ -35,12 +34,16 @@ from lnbits.core.crud.extensions import (
from lnbits.core.crud.extensions import (
get_wasm_invocations as get_wasm_invocations_crud,
)
+from lnbits.core.crud.scheduler import delete_namespace_schedules
from lnbits.core.helpers import migrate_extension_database
+from lnbits.core.services.scheduler import scheduler
from lnbits.core.wasm_ext.api.permissions import validate_wasm_extension_permissions
from lnbits.core.wasm_ext.wasm.component import warm_wasm_extension
from lnbits.core.wasm_ext.wasm.loader import is_wasm_extension_id, load_wasm_extension
+from lnbits.core.wasm_ext.wasm.scheduler import ensure_wasm_extension_schedules
from lnbits.db import Connection
from lnbits.settings import WasmRuntimeLimits, settings
+from lnbits.utils.error import safe_error_message
from ..models.extensions import (
Extension,
@@ -451,7 +454,7 @@ async def finish_wasm_invocation(
invocation.response_bytes = response_bytes
invocation.memory_peak_bytes = memory_peak_bytes
invocation.error_type = error_type
- invocation.error_message = _safe_wasm_error_message(error_message)
+ invocation.error_message = safe_error_message(error_message)
invocation.stop_reason = reason
await update_wasm_invocation(invocation)
@@ -619,31 +622,13 @@ def _safe_wasm_invocation_context(context: dict) -> dict:
return safe_context
-def _safe_wasm_error_message(message: str | None) -> str | None:
- if not message:
- return None
-
- safe_message = message[:500]
- redactions = [
- (
- r"(?i)(api[-_ ]?key|token|authorization|password|secret|preimage)"
- r"\s*[:=]\s*[^\s,;]+",
- r"\1=[redacted]",
- ),
- (r"(?i)bearer\s+[A-Za-z0-9._~+/=-]+", "Bearer [redacted]"),
- (r"\b[a-fA-F0-9]{64}\b", "[redacted-hex]"),
- ]
- for pattern, replacement in redactions:
- safe_message = re.sub(pattern, replacement, safe_message)
- return safe_message
-
-
def _now() -> datetime:
return datetime.now(timezone.utc)
async def uninstall_extension(ext_id: str):
await stop_extension_background_work(ext_id)
+ await delete_namespace_schedules(f"extension:{ext_id}")
core_app_extra.unregister_wasm_ext_routes(ext_id)
settings.deactivate_extension_paths(ext_id)
@@ -659,9 +644,10 @@ async def uninstall_extension(ext_id: str):
async def activate_extension(ext: Extension):
if ext.is_wasm:
+
core_app_extra.register_new_wasm_ext_routes(ext.code)
await update_installed_extension_state(ext_id=ext.code, active=True)
- return
+ return await _ensure_wasm_extension_schedules(ext)
core_app_extra.register_new_ext_routes(ext)
await update_installed_extension_state(ext_id=ext.code, active=True)
@@ -681,6 +667,7 @@ async def stop_extension_background_work(ext_id: str) -> bool:
Stop background work for extension (like asyncio.Tasks, WebSockets, etc).
Extension must expose a `myextension_stop()` function if it is starting tasks.
"""
+ await scheduler.stop_namespace(f"extension:{ext_id}")
if is_wasm_extension_id(ext_id):
return True
@@ -778,3 +765,13 @@ async def get_valid_extension(
return None
return Extension.from_installable_ext(ext)
+
+
+async def _ensure_wasm_extension_schedules(ext):
+ try:
+ await ensure_wasm_extension_schedules(ext.code)
+ except Exception:
+ await update_installed_extension_state(ext_id=ext.code, active=False)
+ await scheduler.stop_namespace(f"extension:{ext.code}")
+ raise
+ return
diff --git a/lnbits/core/services/notifications.py b/lnbits/core/services/notifications.py
index 6348aee..ad2be9c 100644
--- a/lnbits/core/services/notifications.py
+++ b/lnbits/core/services/notifications.py
@@ -121,20 +121,23 @@ async def send_notification(
await send_telegram_notification(telegram_chat_id, message)
logger.debug(f"Sent telegram notification: {message_type}")
except Exception as e:
- logger.error(f"Error sending telegram notification {message_type}: {e}")
+ logger.warning(
+ f"Error sending telegram notification {message_type}: "
+ f"{_telegram_error_message(e)}"
+ )
try:
if nostr_identifiers and settings.is_nostr_notifications_configured():
await send_nostr_notifications(nostr_identifiers, message)
- logger.debug(f"Sent nostr notification: {message_type}")
+ logger.debug(f"Sent nostr notification: {message_type or 'plain text'}")
except Exception as e:
- logger.error(f"Error sending nostr notification {message_type}: {e}")
+ logger.warning(f"Error sending nostr notification {message_type}: {e}")
try:
if email_addresses and settings.lnbits_email_notifications_enabled:
await send_email_notification(email_addresses, message)
logger.debug(f"Sent email notification: {message_type}")
except Exception as e:
- logger.error(f"Error sending email notification {message_type}: {e}")
+ logger.warning(f"Error sending email notification {message_type}: {e}")
async def send_nostr_notifications(identifiers: list[str], message: str) -> list[str]:
@@ -524,3 +527,30 @@ async def _resolve_webhook_host(
if not addresses:
raise ValueError("Webhook target could not be resolved.")
return addresses
+
+
+def _telegram_error_message(error: Exception) -> str:
+ if isinstance(error, httpx.HTTPStatusError):
+ response = error.response
+ try:
+ body = response.json()
+ except ValueError:
+ body = None
+ description = body.get("description") if isinstance(body, dict) else None
+ if not isinstance(description, str) or not description.strip():
+ description = response.reason_phrase or "Telegram request failed"
+ detail = f"HTTP {response.status_code}: {description.strip()}"
+ else:
+ fallbacks: dict[type[Exception], str] = {
+ httpx.ReadTimeout: "Timed out waiting for Telegram",
+ httpx.ConnectTimeout: "Timed out connecting to Telegram",
+ httpx.WriteTimeout: "Timed out sending to Telegram",
+ httpx.PoolTimeout: "Timed out waiting for an available HTTP connection",
+ httpx.TimeoutException: "Telegram request timed out",
+ }
+ description = str(error).strip() or fallbacks.get(
+ type(error), "No error message provided"
+ )
+ detail = f"{type(error).__name__}: {description}"
+ token = settings.lnbits_telegram_notifications_access_token
+ return detail.replace(token, "[redacted]") if token else detail
diff --git a/lnbits/core/services/scheduler.py b/lnbits/core/services/scheduler.py
new file mode 100644
index 0000000..8ca2cac
--- /dev/null
+++ b/lnbits/core/services/scheduler.py
@@ -0,0 +1,437 @@
+import asyncio
+import time
+from collections.abc import Awaitable, Callable
+from uuid import uuid4
+
+from loguru import logger
+
+from lnbits.core.crud.extensions import get_installed_extension, get_user_extension
+from lnbits.core.crud.scheduler import (
+ claim_scheduled_job,
+ create_scheduled_job_run,
+ delete_excess_scheduled_job_runs,
+ delete_expired_scheduled_job_runs,
+ delete_scheduled_job,
+ disable_user_schedules,
+ finish_scheduled_job,
+ finish_scheduled_job_run,
+ get_due_scheduled_jobs,
+ get_scheduled_job,
+ get_scheduled_jobs_count,
+ get_scheduled_jobs_paginated,
+ interrupt_expired_scheduled_job_runs,
+ renew_scheduled_job,
+ save_scheduled_job,
+)
+from lnbits.core.crud.users import get_account
+from lnbits.core.models.extensions import ExtensionPermission
+from lnbits.core.models.scheduler import (
+ ScheduleConfig,
+ ScheduledJob,
+ ScheduledJobRun,
+ ScheduledJobRunStatus,
+ SchedulePolicy,
+ UserSchedulePolicy,
+)
+from lnbits.db import Page
+from lnbits.settings import settings
+from lnbits.utils.cron import next_run_at
+from lnbits.utils.error import safe_error_message
+
+SCHEDULER_USER_PERMISSION = "scheduler.user"
+SCHEDULER_EXTENSION_PERMISSION = "scheduler.extension"
+ScheduleHandler = Callable[[ScheduledJob], Awaitable[None]]
+
+
+async def maintain_scheduled_job_runs(now: float) -> None:
+ await delete_expired_scheduled_job_runs(
+ now - settings.lnbits_scheduler_history_retention_days * 86400,
+ now - settings.lnbits_scheduler_history_failed_retention_days * 86400,
+ )
+ await delete_excess_scheduled_job_runs(
+ settings.lnbits_scheduler_history_max_runs_per_user,
+ settings.lnbits_scheduler_history_max_runs_per_extension,
+ preferred_status="failed",
+ )
+
+
+async def check_schedule_access(
+ namespace: str, user_id: str | None, config: SchedulePolicy
+) -> int | None:
+ """Check current grants, including on executions after the user logs out."""
+ if user_id:
+ account = await get_account(user_id)
+ if not account or not account.activated:
+ raise PermissionError("Schedule owner is not active.")
+ if namespace == "core":
+ return None
+ if (
+ not namespace.startswith("extension:")
+ or settings.lnbits_extensions_deactivate_all
+ ):
+ raise PermissionError("Extension scheduling is unavailable.")
+ extension_id = namespace.removeprefix("extension:")
+ extension = await get_installed_extension(extension_id)
+ if not extension or not extension.active:
+ raise PermissionError("Scheduled extension is not active.")
+ permission = (
+ SCHEDULER_USER_PERMISSION if user_id else SCHEDULER_EXTENSION_PERMISSION
+ )
+ # Python extensions are trusted application code; WASM grants are host-enforced.
+ approved = None
+ if extension.is_wasm:
+ approved = _check_wasm_schedule_policy(
+ extension.permissions, permission, config
+ )
+ if user_id:
+ user_extension = await get_user_extension(user_id, extension_id)
+ if not user_extension or not user_extension.active:
+ raise PermissionError("Scheduled extension is not active for this user.")
+ return (
+ approved.max_jobs_per_user if isinstance(approved, UserSchedulePolicy) else None
+ )
+
+
+class Scheduler:
+ """Persistent cron jobs dispatched to explicitly registered async callbacks.
+
+ Registration and direct access are trusted Python APIs. WASM callers use the
+ scoped host API, which never accepts a namespace or user ID from the guest.
+ """
+
+ def __init__(self, *, concurrency: int = 4, lease_seconds: int = 60):
+ if concurrency < 1 or lease_seconds < 3:
+ raise ValueError("Invalid scheduler concurrency or lease duration.")
+ self.concurrency = concurrency
+ self.lease_seconds = lease_seconds
+ self.handlers: dict[tuple[str, str], ScheduleHandler] = {}
+ self.running: dict[str, tuple[ScheduledJob, asyncio.Task]] = {}
+ self.stopping = False
+ self._next_interrupted_run_check = 0.0
+ self._next_history_maintenance = 0.0
+
+ def register(self, namespace: str, handler: str, callback: ScheduleHandler) -> None:
+ if namespace != "core" and not namespace.startswith("extension:"):
+ raise ValueError("Use the core or extension:<id> namespace.")
+ self.handlers[(namespace, handler)] = callback
+
+ def unregister(self, namespace: str) -> None:
+ self.handlers = {
+ key: callback
+ for key, callback in self.handlers.items()
+ if key[0] != namespace
+ }
+ for job, task in self.running.values():
+ if job.namespace == namespace:
+ task.cancel()
+
+ async def stop_namespace(self, namespace: str, timeout: float = 5.0) -> None:
+ """Cancel this namespace's jobs and bound the wait for their cleanup."""
+ self.unregister(namespace)
+ tasks = [
+ task for job, task in self.running.values() if job.namespace == namespace
+ ]
+ if not tasks:
+ return
+ # Keep unfinished jobs tracked; timing out must not cancel their cleanup.
+ done, pending = await asyncio.wait(tasks, timeout=timeout)
+ for task in done:
+ if not task.cancelled():
+ task.exception()
+ if pending:
+ logger.warning(
+ "Scheduler stop for {} exceeded {} seconds; {} jobs remain unfinished.",
+ namespace,
+ timeout,
+ len(pending),
+ )
+
+ async def save(
+ self, namespace: str, config: ScheduleConfig, *, user_id: str | None = None
+ ) -> ScheduledJob:
+ max_jobs_per_user = await check_schedule_access(namespace, user_id, config)
+ if (namespace, config.handler) not in self.handlers:
+ raise ValueError("Schedule handler is not registered.")
+ now = int(time.time())
+ next_run = next_run_at(config.cron_expression, config.timezone, now)
+ if next_run is None:
+ raise ValueError("Cron expression has no occurrence within eight years.")
+ # Updates remain allowed above the limit. Concurrent creates may exceed it.
+ if (
+ user_id
+ and max_jobs_per_user is not None
+ and not await get_scheduled_job(config.id)
+ ):
+ count = await get_scheduled_jobs_count(namespace, user_id, config.handler)
+ if count >= max_jobs_per_user:
+ raise ValueError(
+ "Scheduled job limit reached for this handler "
+ f"({max_jobs_per_user} per user)."
+ )
+ return await save_scheduled_job(
+ ScheduledJob(
+ **config.dict(),
+ namespace=namespace,
+ user_id=user_id,
+ next_run_at=next_run,
+ )
+ )
+
+ async def list_paginated(
+ self,
+ namespace: str,
+ *,
+ user_id: str | None = None,
+ limit: int = 100,
+ offset: int = 0,
+ ) -> Page[ScheduledJob]:
+ if not 1 <= limit <= 100 or offset < 0:
+ raise ValueError("Invalid schedule pagination.")
+ return await get_scheduled_jobs_paginated(
+ namespace, user_id, limit=limit, offset=offset
+ )
+
+ async def delete(
+ self, namespace: str, job_id: str, *, user_id: str | None = None
+ ) -> bool:
+ job = await get_scheduled_job(job_id)
+ if not job or job.namespace != namespace or job.user_id != user_id:
+ return False
+ if job.lease_token and job.lease_until > int(time.time()):
+ raise ValueError(
+ "Job is running. Pause it and wait for it to stop before deleting."
+ )
+ return await delete_scheduled_job(job_id, namespace, user_id, int(time.time()))
+
+ async def tick(self) -> None:
+ if not settings.lnbits_scheduler_enabled:
+ return
+ now = time.time()
+ if now >= self._next_interrupted_run_check:
+ self._next_interrupted_run_check = now + 60
+ try:
+ await interrupt_expired_scheduled_job_runs(now)
+ except Exception:
+ logger.warning("Scheduler interrupted run check failed.")
+ if now >= self._next_history_maintenance:
+ self._next_history_maintenance = now + 15 * 60
+ try:
+ await maintain_scheduled_job_runs(now)
+ except Exception:
+ logger.warning("Scheduler history maintenance failed.")
+ for job_id, (_, task) in list(self.running.items()):
+ if task.done():
+ # Workers handle callback errors, but database failures may escape.
+ if not task.cancelled() and task.exception():
+ logger.warning("Scheduled job {} failed to finalize.", job_id)
+ self.running.pop(job_id)
+ available = self.concurrency - len(self.running)
+ if available <= 0 or self.stopping or not settings.lnbits_scheduler_enabled:
+ return
+ await self._start_due_jobs(int(time.time()), available)
+
+ async def run(self) -> None:
+ self.stopping = False
+ try:
+ while settings.lnbits_running and not self.stopping:
+ await self.tick()
+ await asyncio.sleep(1)
+ finally:
+ await self.stop()
+
+ async def stop(self) -> None:
+ tasks = [task for _, task in self.running.values()]
+ if not self.stopping:
+ self.stopping = True
+ for task in tasks:
+ task.cancel()
+ await asyncio.gather(*tasks, return_exceptions=True)
+ self.running.clear()
+
+ async def _start_due_jobs(self, now: int, limit: int) -> None:
+ for candidate in await get_due_scheduled_jobs(now, limit):
+ if not settings.lnbits_scheduler_enabled:
+ return
+ if self.stopping or candidate.id in self.running:
+ continue
+ job = await claim_scheduled_job(
+ candidate.id, uuid4().hex, now, now + self.lease_seconds
+ )
+ if job and not self.stopping:
+ if not settings.lnbits_scheduler_enabled:
+ # The toggle may change while claiming; keep this job due.
+ await finish_scheduled_job(job, job.next_run_at)
+ return
+ self.running[job.id] = (
+ job,
+ asyncio.create_task(self._run_job(job), name=f"schedule_{job.id}"),
+ )
+
+ async def _execute(self, job: ScheduledJob) -> bool:
+ current = await get_scheduled_job(job.id)
+ if not current or not current.enabled or current.lease_token != job.lease_token:
+ return False
+ await _check_scheduled_job_access(current)
+ callback = self.handlers.get((current.namespace, current.handler))
+ if callback:
+ await callback(current)
+ return True
+ return False
+
+ async def _heartbeat(self, job: ScheduledJob) -> None:
+ assert job.lease_token
+ while settings.lnbits_running:
+ await asyncio.sleep(self.lease_seconds / 3)
+ await _check_scheduled_job_access(job)
+ now = int(time.time())
+ if not await renew_scheduled_job(
+ job.id, job.lease_token, now, now + self.lease_seconds
+ ):
+ raise RuntimeError("Schedule claim lost or job paused.")
+
+ async def _record_run_start(self, job: ScheduledJob) -> ScheduledJobRun | None:
+ try:
+ return await create_scheduled_job_run(job, time.time())
+ except Exception:
+ # Observability must not change whether a scheduled callback runs.
+ logger.warning("Could not record scheduled job {} start.", job.id)
+ return None
+
+ async def _run_job(self, job: ScheduledJob) -> None:
+ run = None
+ work = None
+ heartbeat = None
+ cancelled = False
+ status: ScheduledJobRunStatus = "succeeded"
+ error_summary = None
+ try:
+ run = await self._record_run_start(job)
+ work = asyncio.create_task(self._execute(job))
+ heartbeat = asyncio.create_task(self._heartbeat(job))
+ done, _ = await asyncio.wait(
+ (work, heartbeat), return_when=asyncio.FIRST_COMPLETED
+ )
+ for task in done:
+ task.result()
+ # The heartbeat only finishes by raising, so work is done here.
+ if not work.result():
+ status = "skipped"
+ error_summary = (
+ "Job is unavailable, paused, or its handler is not registered."
+ )
+ except asyncio.CancelledError:
+ cancelled = True
+ status = "cancelled"
+ error_summary = "Execution was cancelled."
+ raise
+ except Exception as exc:
+ if heartbeat is not None and heartbeat.done():
+ status = "cancelled"
+ error_summary = "Scheduling access or the execution lease was lost."
+ else:
+ status = "failed"
+ message = safe_error_message(str(exc))
+ error_summary = (
+ f"{type(exc).__name__}: {message}"
+ if message
+ else type(exc).__name__
+ )[:500]
+ logger.warning(
+ "Scheduled job {} failed ({}); next attempt follows its cron schedule.",
+ job.id,
+ error_summary,
+ )
+ finally:
+ tasks: list[asyncio.Task] = [
+ task for task in (work, heartbeat) if task is not None
+ ]
+ for task in tasks:
+ task.cancel()
+ await asyncio.gather(*tasks, return_exceptions=True)
+ if run:
+ try:
+ await finish_scheduled_job_run(
+ run.id, status, time.time(), error_summary
+ )
+ except Exception:
+ logger.warning("Could not record scheduled job {} result.", job.id)
+ # On shutdown leave the durable lease to expire, so interrupted jobs
+ # are recovered once on restart. Successful/failed jobs skip overlap.
+ if not cancelled:
+ following = next_run_at(
+ job.cron_expression, job.timezone, int(time.time())
+ )
+ await finish_scheduled_job(job, following)
+
+
+scheduler = Scheduler()
+_stop_tasks: set[asyncio.Task[None]] = set()
+
+
+async def stop_scheduler_safely(timeout: float = 5.0) -> None:
+ """Bound the shutdown wait while allowing in-flight cleanup to finish.
+
+ Stop failures and caller cancellation are logged and suppressed.
+ The deadline requires a responsive event loop and cannot kill native threads.
+ """
+
+ async def stop() -> None:
+ try:
+ await scheduler.stop()
+ except asyncio.CancelledError:
+ logger.warning("Scheduler shutdown was cancelled.")
+ except Exception:
+ logger.warning("Scheduler shutdown failed.")
+
+ try:
+ task = asyncio.create_task(stop(), name="scheduler_shutdown")
+ # Retain cleanup after the caller returns, and consume failures inside stop().
+ _stop_tasks.add(task)
+ task.add_done_callback(_stop_tasks.discard)
+ # wait() does not cancel or wait for uncooperative cleanup on timeout.
+ _, pending = await asyncio.wait({task}, timeout=timeout)
+ if pending:
+ unfinished = sum(not task.done() for _, task in scheduler.running.values())
+ logger.warning(
+ "Scheduler shutdown exceeded {} seconds; {} jobs remain unfinished.",
+ timeout,
+ unfinished,
+ )
+ except asyncio.CancelledError:
+ logger.warning(
+ "Scheduler shutdown wait was cancelled; "
+ "cleanup continues in the background."
+ )
+ except Exception:
+ logger.warning("Scheduler shutdown failed.")
+
+
+def _check_wasm_schedule_policy(
+ permissions: list[ExtensionPermission], permission_id: str, config: SchedulePolicy
+) -> SchedulePolicy:
+ grant = next((item for item in permissions if item.id == permission_id), None)
+ if not grant:
+ raise PermissionError("Extension scheduling permission has been revoked.")
+ try:
+ approved = SchedulePolicy.parse_policies(
+ grant.policies, user_scope=permission_id == SCHEDULER_USER_PERMISSION
+ ).get(config.handler)
+ except ValueError as exc:
+ raise PermissionError("Invalid approved schedule policies.") from exc
+ if not approved or (
+ approved.cron_expression != config.cron_expression
+ or approved.timezone != config.timezone
+ ):
+ raise PermissionError("Schedule does not match an admin-approved policy.")
+ return approved
+
+
+async def _check_scheduled_job_access(job: ScheduledJob) -> None:
+ try:
+ await check_schedule_access(job.namespace, job.user_id, job)
+ except PermissionError:
+ if job.user_id:
+ account = await get_account(job.user_id)
+ if not account or not account.activated:
+ await disable_user_schedules(job.user_id)
+ raise
diff --git a/lnbits/core/views/generic.py b/lnbits/core/views/generic.py
index 353a494..da72784 100644
--- a/lnbits/core/views/generic.py
+++ b/lnbits/core/views/generic.py
@@ -189,6 +189,8 @@ admin_ui_checks = [Depends(check_admin), Depends(check_admin_ui)]
@generic_router.get("/extensions")
@generic_router.get("/users", dependencies=admin_ui_checks)
@generic_router.get("/audit", dependencies=admin_ui_checks)
+@generic_router.get("/scheduler", dependencies=admin_ui_checks)
+@generic_router.get("/scheduler/runs", dependencies=admin_ui_checks)
@generic_router.get("/node", dependencies=admin_ui_checks)
@generic_router.get("/admin", dependencies=admin_ui_checks)
@generic_router.get("/admin/extensions/wasm", dependencies=admin_ui_checks)
diff --git a/lnbits/core/views/scheduler_api.py b/lnbits/core/views/scheduler_api.py
new file mode 100644
index 0000000..cf06166
--- /dev/null
+++ b/lnbits/core/views/scheduler_api.py
@@ -0,0 +1,59 @@
+from fastapi import APIRouter, Depends, Query
+
+from lnbits.core.crud.scheduler import (
+ get_scheduled_job_runs_paginated,
+ get_scheduled_job_sources,
+ get_scheduled_jobs_overview_paginated,
+)
+from lnbits.core.models.scheduler import (
+ ScheduledJobFilters,
+ ScheduledJobRun,
+ ScheduledJobRunFilters,
+ ScheduledJobSummary,
+)
+from lnbits.db import Filters, Page
+from lnbits.decorators import check_admin, check_admin_ui, parse_filters
+from lnbits.helpers import generate_filter_params_openapi
+
+scheduler_router = APIRouter(
+ prefix="/scheduler/api/v1",
+ dependencies=[Depends(check_admin), Depends(check_admin_ui)],
+ tags=["Scheduler"],
+)
+
+
+@scheduler_router.get(
+ "",
+ summary="List scheduled jobs across core and extensions",
+ openapi_extra=generate_filter_params_openapi(ScheduledJobFilters),
+)
+async def api_get_scheduled_jobs(
+ filters: Filters[ScheduledJobFilters] = Depends(parse_filters(ScheduledJobFilters)),
+ limit: int = Query(default=10, ge=1, le=1000),
+ offset: int = Query(default=0, ge=0),
+) -> Page[ScheduledJobSummary]:
+ filters.limit = limit
+ filters.offset = offset
+ return await get_scheduled_jobs_overview_paginated(filters)
+
+
+@scheduler_router.get("/sources", summary="List scheduled job sources")
+async def api_get_scheduled_job_sources() -> list[str]:
+ return await get_scheduled_job_sources()
+
+
+@scheduler_router.get(
+ "/runs",
+ summary="List retained scheduler executions, including deleted jobs",
+ openapi_extra=generate_filter_params_openapi(ScheduledJobRunFilters),
+)
+async def api_get_scheduled_job_runs(
+ filters: Filters[ScheduledJobRunFilters] = Depends(
+ parse_filters(ScheduledJobRunFilters)
+ ),
+ limit: int = Query(default=10, ge=1, le=1000),
+ offset: int = Query(default=0, ge=0),
+) -> Page[ScheduledJobRun]:
+ filters.limit = limit
+ filters.offset = offset
+ return await get_scheduled_job_runs_paginated(filters)
diff --git a/lnbits/core/wasm_ext/api/host.py b/lnbits/core/wasm_ext/api/host.py
index 53d12f4..8e3949c 100644
--- a/lnbits/core/wasm_ext/api/host.py
+++ b/lnbits/core/wasm_ext/api/host.py
@@ -66,6 +66,7 @@ from .models import (
WebsocketPublishResponse,
)
from .registry import extension_api_method
+from .scheduler import ExtensionSchedulerAPI
from .websockets import scoped_websocket_item_id, wasm_extension_websocket_hub
PUBLIC_APPEND_DEFAULT_MAX_ROWS_PER_SOURCE = 10_000
@@ -94,6 +95,7 @@ class ExtensionHostAPI:
self.runtime_limits = runtime_limits or {}
from .utils import ExtensionAPIUtils
+ self.scheduler = ExtensionSchedulerAPI(self)
self.utils = ExtensionAPIUtils(
self.extension_id,
self.permissions,
@@ -534,11 +536,14 @@ class ExtensionHostAPI:
from lnbits.exceptions import PaymentError
wallet = await get_wallet(request.wallet_id)
- if wallet is None:
+ if wallet is None or (
+ self.context == "schedule"
+ and (not self.user_id or wallet.user != self.user_id)
+ ):
raise PermissionError("Paying invoices from this wallet is not allowed.")
try:
- if self.user_id:
+ if self.user_id and self.context != "schedule":
self.require_permission("wallet.pay_invoice")
if wallet.user != self.user_id:
raise PermissionError(
@@ -599,11 +604,14 @@ class ExtensionHostAPI:
)
wallet = await get_wallet(request.wallet_id)
- if wallet is None:
+ if wallet is None or (
+ self.context == "schedule"
+ and (not self.user_id or wallet.user != self.user_id)
+ ):
raise PermissionError("Paying from this wallet is not allowed.")
try:
- if self.user_id:
+ if self.user_id and self.context != "schedule":
self.require_permission("wallet.pay_invoice")
if wallet.user != self.user_id:
raise PermissionError("Paying from this wallet is not allowed.")
@@ -630,7 +638,7 @@ class ExtensionHostAPI:
extra["fiat_currency"] = unit
extra["fiat_amount"] = str(request.amount)
- if not self.user_id:
+ if not self.user_id or self.context == "schedule":
amount_msat = invoice_amount_msat(str(action.pr))
extra = {
**extra,
@@ -1032,7 +1040,7 @@ class ExtensionHostAPI:
)
def has_authenticated_context(self) -> bool:
- return bool(self.user_id) or self.context == "event"
+ return bool(self.user_id) or self.context in {"event", "schedule"}
def _require_owner_id(self) -> str:
if not self.owner_id:
diff --git a/lnbits/core/wasm_ext/api/permissions.py b/lnbits/core/wasm_ext/api/permissions.py
index 837e779..8b09339 100644
--- a/lnbits/core/wasm_ext/api/permissions.py
+++ b/lnbits/core/wasm_ext/api/permissions.py
@@ -2,6 +2,7 @@ from collections.abc import Iterable
from typing import Any
from lnbits.core.models.extensions import ExtensionPermission, InstallableExtension
+from lnbits.core.models.scheduler import SchedulePolicy, UserSchedulePolicy
from lnbits.core.wasm_ext.api.registry import extension_api_permission_ids
from lnbits.core.wasm_ext.api.websockets import (
WEBSOCKET_PUBLISH_MAX_MESSAGES_PER_SECOND_LIMIT,
@@ -17,6 +18,8 @@ _POLICY_AWARE_PERMISSION_IDS = {
"ext.storage.read_public",
"extension.api.request",
"http.request",
+ "scheduler.user",
+ "scheduler.extension",
"wallet.create_invoice_public",
"websocket.publish",
}
@@ -68,7 +71,12 @@ def validate_wasm_extension_permissions(
requested_permissions = validate_extension_permissions(
ext_info.id, config.permissions
)
- _validate_requested_permission_policies(ext_info.id, requested_permissions)
+ _validate_requested_permission_policies(
+ ext_info.id,
+ requested_permissions,
+ {export.name for export in config.wasm.exports if export.visibility == "event"},
+ )
+ _validate_automatic_schedules(config.schedules, requested_permissions)
if not requested_permissions:
return []
@@ -105,6 +113,7 @@ def validate_wasm_extension_permissions(
requested_permission.copy(update={"policies": granted_permission.policies})
)
+ _validate_automatic_schedules(config.schedules, effective_permissions)
return effective_permissions
@@ -140,34 +149,52 @@ def _permission_grant_is_subset(
return False
if requested.id not in _POLICY_AWARE_PERMISSION_IDS:
return True
- if requested.id == "http.request":
- return _http_request_grant_is_subset(requested.policies, granted.policies)
- if requested.id == "extension.api.request":
- return _extension_api_grant_is_subset(requested.policies, granted.policies)
if requested.id == "ext.storage.append_public":
return _public_storage_append_grant_is_subset(
requested.policies,
granted.policies,
allow_max_rows_per_source_override=allow_admin_policy_overrides,
)
- if requested.id == "ext.storage.read_public":
- return _public_storage_grant_is_subset(requested.policies, granted.policies)
- if requested.id == "wallet.create_invoice_public":
- return _public_invoice_grant_is_subset(requested.policies, granted.policies)
if requested.id == "websocket.publish":
return _websocket_publish_grant_is_subset(
requested.policies,
granted.policies,
allow_max_messages_per_second_override=allow_admin_policy_overrides,
)
- return False
+ if requested.id in {"scheduler.user", "scheduler.extension"}:
+ return _schedule_grant_is_subset(
+ requested.policies,
+ granted.policies,
+ user_scope=requested.id == "scheduler.user",
+ allow_job_limit_override=allow_admin_policy_overrides,
+ )
+ checker = {
+ "http.request": _http_request_grant_is_subset,
+ "extension.api.request": _extension_api_grant_is_subset,
+ "ext.storage.read_public": _public_storage_grant_is_subset,
+ "wallet.create_invoice_public": _public_invoice_grant_is_subset,
+ }.get(requested.id)
+ return checker(requested.policies, granted.policies) if checker else False
def _validate_requested_permission_policies(
ext_id: str,
permissions: Iterable[ExtensionPermission],
+ event_handlers: set[str],
) -> None:
for permission in permissions:
+ if permission.id in {"scheduler.user", "scheduler.extension"}:
+ try:
+ policies = SchedulePolicy.parse_policies(
+ permission.policies, user_scope=permission.id == "scheduler.user"
+ )
+ if not policies.keys() <= event_handlers:
+ raise ValueError("Scheduled handlers must be event exports.")
+ except ValueError as exc:
+ raise ValueError(
+ f"Extension '{ext_id}' requests invalid policies for permission "
+ f"'{permission.id}': {exc}"
+ ) from exc
if permission.id != "websocket.publish":
continue
if _websocket_publish_policy(permission.policies) is None:
@@ -410,3 +437,47 @@ def _websocket_publish_policy(policies: list[Any] | None) -> dict[str, int] | No
):
return None
return {"max_messages_per_second": max_messages_per_second}
+
+
+def _validate_automatic_schedules(
+ schedules: list[SchedulePolicy], permissions: list[ExtensionPermission]
+) -> None:
+ if not schedules:
+ return
+ grant = next((p for p in permissions if p.id == "scheduler.extension"), None)
+ approved = SchedulePolicy.parse_policies(grant.policies) if grant else {}
+ for schedule in schedules:
+ if approved.get(schedule.handler) != schedule:
+ raise ValueError(
+ "Automatic schedules require matching scheduler.extension policies."
+ )
+
+
+def _schedule_grant_is_subset(
+ requested_policies: list[Any] | None,
+ granted_policies: list[Any] | None,
+ *,
+ user_scope: bool = False,
+ allow_job_limit_override: bool = False,
+) -> bool:
+ try:
+ requested = SchedulePolicy.parse_policies(
+ requested_policies, user_scope=user_scope
+ )
+ granted = SchedulePolicy.parse_policies(granted_policies, user_scope=user_scope)
+ except ValueError:
+ return False
+ for handler, policy in granted.items():
+ declared = requested.get(handler)
+ if not declared or declared.dict(exclude={"max_jobs_per_user"}) != policy.dict(
+ exclude={"max_jobs_per_user"}
+ ):
+ return False
+ if (
+ isinstance(policy, UserSchedulePolicy)
+ and isinstance(declared, UserSchedulePolicy)
+ and policy.max_jobs_per_user > declared.max_jobs_per_user
+ and not allow_job_limit_override
+ ):
+ return False
+ return True
diff --git a/lnbits/core/wasm_ext/api/registry.py b/lnbits/core/wasm_ext/api/registry.py
index 2dcddc5..e1a322b 100644
--- a/lnbits/core/wasm_ext/api/registry.py
+++ b/lnbits/core/wasm_ext/api/registry.py
@@ -11,6 +11,8 @@ from .models import ExtensionAPIMethod, ExtensionAPIMethodExport
_EXTENSION_API_METHOD_ATTR = "__lnbits_extension_api_method__"
_EXTENSION_RUNTIME_PERMISSION_IDS = {
+ "scheduler.user",
+ "scheduler.extension",
"ui.camera.scan_qr",
"wallet.pay_invoice",
"wallet.pay_invoice_background",
@@ -165,8 +167,11 @@ def _extension_api_method_sources(
from .host import ExtensionHostAPI
if issubclass(api_cls, ExtensionHostAPI):
+ # Keep local: scheduler imports this module's extension_api_method decorator.
+ from .scheduler import ExtensionSchedulerAPI
from .utils import extension_api_utils_method_classes
+ sources.append(("scheduler", ExtensionSchedulerAPI))
sources.extend(extension_api_utils_method_classes().items())
return sources
diff --git a/lnbits/core/wasm_ext/api/scheduler.py b/lnbits/core/wasm_ext/api/scheduler.py
new file mode 100644
index 0000000..c61c2ab
--- /dev/null
+++ b/lnbits/core/wasm_ext/api/scheduler.py
@@ -0,0 +1,161 @@
+from __future__ import annotations
+
+import json
+import re
+from typing import TYPE_CHECKING, Literal
+
+from pydantic import BaseModel, Field, root_validator
+
+from lnbits.core.crud.users import get_account
+from lnbits.core.models.scheduler import ScheduleConfig
+from lnbits.core.services.scheduler import (
+ SCHEDULER_EXTENSION_PERMISSION,
+ SCHEDULER_USER_PERMISSION,
+ scheduler,
+)
+from lnbits.helpers import sha256s
+
+from .registry import extension_api_method
+
+if TYPE_CHECKING:
+ from .host import ExtensionHostAPI
+
+
+class ScheduleScopeRequest(BaseModel):
+ scope: Literal["user", "extension"] = "user"
+
+ class Config:
+ extra = "forbid"
+
+
+class ScheduleSetRequest(ScheduleConfig):
+ scope: Literal["user", "extension"] = "user"
+
+ @root_validator(pre=True)
+ def omit_empty_id(cls, values: dict) -> dict:
+ # WIT represents an omitted ID as option<string> / None.
+ if values.get("id") is None:
+ values = {key: value for key, value in values.items() if key != "id"}
+ return values
+
+
+class ScheduleListRequest(ScheduleScopeRequest):
+ limit: int = Field(default=100, ge=1, le=100)
+ offset: int = Field(default=0, ge=0)
+
+
+class ScheduleDeleteRequest(ScheduleScopeRequest):
+ id: str = Field(..., min_length=1, max_length=128)
+
+
+class ScheduleResponse(BaseModel):
+ schedule_json: str
+
+
+class ScheduleListResponse(BaseModel):
+ schedules_json: str
+
+
+class ScheduleDeleteResponse(BaseModel):
+ deleted: bool
+
+
+class ExtensionSchedulerAPI:
+ def __init__(self, api: ExtensionHostAPI):
+ self.api = api
+
+ @extension_api_method(
+ method_id="scheduler.set",
+ namespace="scheduler",
+ name="Save schedule",
+ host_interface="scheduler",
+ host_name="set_schedule",
+ sdk_name="set",
+ description=(
+ "Create or update a five-field cron job. "
+ "User scope requires scheduler.user; "
+ "extension scope requires scheduler.extension and an administrator. "
+ "The handler, cron expression and timezone must match an "
+ "admin-approved schedule policy. The handler must be an event export. "
+ "User jobs are limited per handler by the approved max_jobs_per_user "
+ "(default 10), including paused jobs. Omit the ID to create a user job; "
+ "reuse its ID to update it. A job's handler cannot change."
+ ),
+ )
+ async def set(self, request: ScheduleSetRequest) -> ScheduleResponse:
+ owner = await self._owner(request.scope)
+ self.api.require_permission(
+ SCHEDULER_USER_PERMISSION if owner else SCHEDULER_EXTENSION_PERMISSION
+ )
+ job_id = request.id
+ if owner is None:
+ # Shared jobs retain their stable IDs, including automatic schedules.
+ job_id = sha256s(
+ json.dumps([self.api.extension_id, owner, request.handler])
+ )
+ if "id" in request.__fields_set__ and request.id != job_id:
+ raise ValueError("Schedule ID does not match this handler and owner.")
+ elif re.fullmatch(r"[0-9a-f]{64}", job_id):
+ # IDs are global: reserve shared hashes across all handlers/extensions.
+ raise ValueError("Schedule ID is reserved for extension-wide schedules.")
+ job = await scheduler.save(
+ f"extension:{self.api.extension_id}",
+ ScheduleConfig.parse_obj({**request.dict(exclude={"scope"}), "id": job_id}),
+ user_id=owner,
+ )
+ return ScheduleResponse(schedule_json=json.dumps(job.public_data()))
+
+ @extension_api_method(
+ method_id="scheduler.list",
+ namespace="scheduler",
+ name="List schedules",
+ host_interface="scheduler",
+ host_name="list_schedules",
+ sdk_name="list",
+ description="List user-owned jobs, or shared jobs for an administrator.",
+ )
+ async def list(self, request: ScheduleListRequest) -> ScheduleListResponse:
+ owner = await self._owner(request.scope)
+ page = await scheduler.list_paginated(
+ f"extension:{self.api.extension_id}",
+ user_id=owner,
+ limit=request.limit,
+ offset=request.offset,
+ )
+ return ScheduleListResponse(
+ schedules_json=json.dumps([j.public_data() for j in page.data])
+ )
+
+ @extension_api_method(
+ method_id="scheduler.delete",
+ namespace="scheduler",
+ name="Delete schedule",
+ host_interface="scheduler",
+ host_name="delete_schedule",
+ sdk_name="delete",
+ description="Delete an owned, idle schedule. Pause running jobs first.",
+ )
+ async def delete(self, request: ScheduleDeleteRequest) -> ScheduleDeleteResponse:
+ owner = await self._owner(request.scope)
+ deleted = await scheduler.delete(
+ f"extension:{self.api.extension_id}", request.id, user_id=owner
+ )
+ return ScheduleDeleteResponse(deleted=deleted)
+
+ async def _owner(self, scope: str) -> str | None:
+ # A scheduled callback must not impersonate an interactive user, even if
+ # it has that user's storage/notification context.
+ if self.api.context != "user" or not self.api.user_id:
+ raise PermissionError(
+ "Managing schedules requires an authenticated request."
+ )
+ account = await get_account(self.api.user_id)
+ if not account or not account.activated:
+ raise PermissionError("Schedule owner is not active.")
+ if scope == "extension":
+ if not account.is_admin:
+ raise PermissionError(
+ "Extension-wide schedules require an administrator."
+ )
+ return None
+ return self.api.user_id
diff --git a/lnbits/core/wasm_ext/routes/register.py b/lnbits/core/wasm_ext/routes/register.py
index a6c43b6..424b5fd 100644
--- a/lnbits/core/wasm_ext/routes/register.py
+++ b/lnbits/core/wasm_ext/routes/register.py
@@ -6,10 +6,12 @@ from fastapi import FastAPI
from loguru import logger
from lnbits.core.db import core_app_extra
+from lnbits.core.services.scheduler import scheduler
from lnbits.settings import settings
from ..wasm.component import warm_wasm_extension
from ..wasm.loader import WasmExtension, load_wasm_extension
+from ..wasm.scheduler import register_wasm_schedule_handlers
from .api import (
register_wasm_extension_api_routes,
unregister_wasm_extension_api_routes,
@@ -29,6 +31,7 @@ def register_wasm_extension(app: FastAPI, ext_id: str) -> WasmExtension:
register_wasm_extension_api_routes(app, loaded)
core_app_extra.wasm_extension_registry.register(loaded)
+ register_wasm_schedule_handlers(loaded)
settings.activate_extension_paths(ext_id, [])
module_size = _format_wasm_extension_size(loaded.module_path.stat().st_size)
@@ -41,6 +44,7 @@ def register_wasm_extension(app: FastAPI, ext_id: str) -> WasmExtension:
def unregister_wasm_extension(app: FastAPI, ext_id: str) -> None:
+ scheduler.unregister(f"extension:{ext_id}")
routes_removed = unregister_wasm_extension_api_routes(app, ext_id)
core_app_extra.wasm_extension_registry.unregister(ext_id)
if routes_removed:
diff --git a/lnbits/core/wasm_ext/wasm/config.py b/lnbits/core/wasm_ext/wasm/config.py
index 947b3a5..8daeb21 100644
--- a/lnbits/core/wasm_ext/wasm/config.py
+++ b/lnbits/core/wasm_ext/wasm/config.py
@@ -9,9 +9,11 @@ from pydantic import (
StrictBool,
StrictStr,
ValidationError,
+ root_validator,
)
from lnbits.core.models.extensions import ExtensionPermission
+from lnbits.core.models.scheduler import SchedulePolicy
_EXTENSION_ID_RE = re.compile(r"^[A-Za-z0-9_-]+$")
@@ -88,6 +90,20 @@ class WasmExtensionConfig(_StrictWasmModel):
ui_routes: list[WasmUIRouteConfig] = Field(default_factory=list)
api_routes: list[WasmAPIRouteConfig] = Field(default_factory=list)
permissions: list[ExtensionPermission] = Field(default_factory=list)
+ schedules: list[SchedulePolicy] = Field(default_factory=list, max_items=100)
+
+ @root_validator
+ def validate_schedules(cls, values: dict[str, Any]) -> dict[str, Any]:
+ schedules = values.get("schedules", [])
+ wasm = values.get("wasm")
+ handlers = [schedule.handler for schedule in schedules]
+ if len(set(handlers)) != len(handlers):
+ raise ValueError("Automatic schedules must have unique handlers.")
+ if wasm and not set(handlers).issubset(
+ export.name for export in wasm.exports if export.visibility == "event"
+ ):
+ raise ValueError("Automatic schedule handlers must be event exports.")
+ return values
def parse_wasm_extension_config(
diff --git a/lnbits/core/wasm_ext/wasm/invoke.py b/lnbits/core/wasm_ext/wasm/invoke.py
index f21e49e..417828e 100644
--- a/lnbits/core/wasm_ext/wasm/invoke.py
+++ b/lnbits/core/wasm_ext/wasm/invoke.py
@@ -111,16 +111,21 @@ async def invoke_wasm_extension_export(
timeout=max_execution_ms / 1000,
)
else:
- result = await thread_task
+ result = await asyncio.shield(thread_task)
except asyncio.TimeoutError as exc:
timed_out = True
stop_reason = "WASM execution time limit exceeded."
await stop_wasm_invocation(invocation.id, reason=stop_reason)
try:
- result = await asyncio.wait_for(
- asyncio.shield(thread_task),
- timeout=2,
- )
+ if context == "schedule":
+ # Keep renewing the schedule lease until the native runtime
+ # exits; a slow host call must not overlap the next run.
+ result = await asyncio.shield(thread_task)
+ else:
+ result = await asyncio.wait_for(
+ asyncio.shield(thread_task),
+ timeout=2,
+ )
except asyncio.TimeoutError:
await finish_wasm_invocation(
invocation.id,
@@ -149,6 +154,16 @@ async def invoke_wasm_extension_export(
)
finished = True
return result
+ except asyncio.CancelledError:
+ # A scheduled coroutine can be cancelled while its WASM thread is still
+ # running. Stop and drain the runtime before releasing its schedule claim.
+ await stop_wasm_invocation(invocation.id, reason="Invocation cancelled.")
+ await asyncio.gather(thread_task, return_exceptions=True)
+ if not finished:
+ await finish_wasm_invocation(
+ invocation.id, status="stopped", stop_reason="Invocation cancelled."
+ )
+ raise
except Exception as exc:
if not finished:
await finish_wasm_invocation(
diff --git a/lnbits/core/wasm_ext/wasm/scheduler.py b/lnbits/core/wasm_ext/wasm/scheduler.py
new file mode 100644
index 0000000..6a65b76
--- /dev/null
+++ b/lnbits/core/wasm_ext/wasm/scheduler.py
@@ -0,0 +1,73 @@
+import json
+
+from lnbits.core.crud.scheduler import get_scheduled_job
+from lnbits.core.crud.users import get_account
+from lnbits.core.db import core_app_extra
+from lnbits.core.models.scheduler import ScheduleConfig, ScheduledJob
+from lnbits.core.services.scheduler import check_schedule_access, scheduler
+from lnbits.helpers import sha256s
+
+from .invoke import invoke_wasm_extension_export
+from .loader import WasmExtension
+
+
+def register_wasm_schedule_handlers(extension: WasmExtension) -> None:
+ namespace = f"extension:{extension.id}"
+ scheduler.unregister(namespace)
+ for export in extension.exports:
+ if export.visibility == "event":
+ scheduler.register(namespace, export.name, dispatch_wasm_schedule)
+
+
+async def ensure_wasm_extension_schedules(ext_id: str) -> None:
+ extension = core_app_extra.wasm_extension_registry.get(ext_id)
+ if not extension:
+ raise ValueError("WASM extension must be registered before starting schedules.")
+ namespace = f"extension:{ext_id}"
+ for policy in extension.config.schedules:
+ await check_schedule_access(namespace, None, policy)
+ job_id = sha256s(json.dumps([ext_id, None, policy.handler]))
+ existing = await get_scheduled_job(job_id)
+ if existing and (
+ existing.cron_expression == policy.cron_expression
+ and existing.timezone == policy.timezone
+ ):
+ # Preserve the next run, any running lease, and administrator pauses.
+ continue
+ await scheduler.save(
+ namespace,
+ ScheduleConfig(
+ **policy.dict(),
+ id=job_id,
+ enabled=existing.enabled if existing else True,
+ ),
+ )
+
+
+async def dispatch_wasm_schedule(job: ScheduledJob) -> None:
+ extension_id = job.namespace.removeprefix("extension:")
+ extension = core_app_extra.wasm_extension_registry.get(extension_id)
+ if not extension or not any(
+ export.name == job.handler and export.visibility == "event"
+ for export in extension.exports
+ ):
+ raise PermissionError("Scheduled WASM handler is not an event export.")
+ user = await get_account(job.user_id) if job.user_id else None
+ if job.user_id and (not user or not user.activated):
+ raise PermissionError("Scheduled user is no longer active.")
+ await invoke_wasm_extension_export(
+ extension_id,
+ job.handler,
+ {
+ "scheduleId": job.id,
+ "scheduledAt": job.next_run_at,
+ "data": json.loads(job.payload_json),
+ },
+ user=user,
+ # Extension jobs own a separate partition, never an administrator's data.
+ # Users can read selected fields through the existing public-storage API.
+ owner_id=f"extension:{extension_id}" if not job.user_id else None,
+ context="schedule",
+ trigger_type="schedule",
+ context_data={"schedule_id": job.id},
+ )
diff --git a/lnbits/db.py b/lnbits/db.py
index dc50b36..86cc52c 100644
--- a/lnbits/db.py
+++ b/lnbits/db.py
@@ -255,7 +255,7 @@ class Connection(Compat):
self.rewrite_values(parsed_values),
model,
)
- if rows:
+ if rows or filters.offset:
# no need for extra query if no pagination is specified
if filters.offset or filters.limit:
if table_name:
diff --git a/lnbits/settings.py b/lnbits/settings.py
index 850e0ca..be040c3 100644
--- a/lnbits/settings.py
+++ b/lnbits/settings.py
@@ -999,6 +999,14 @@ class TwoFactorSettings(LNbitsSettings):
return list(dict.fromkeys(methods))
+class SchedulerSettings(LNbitsSettings):
+ lnbits_scheduler_enabled: bool = True
+ lnbits_scheduler_history_retention_days: int = Field(default=7, ge=1)
+ lnbits_scheduler_history_failed_retention_days: int = Field(default=30, ge=1)
+ lnbits_scheduler_history_max_runs_per_user: int = Field(default=1000, ge=1)
+ lnbits_scheduler_history_max_runs_per_extension: int = Field(default=1000, ge=1)
+
+
class AuditSettings(LNbitsSettings):
lnbits_audit_enabled: bool = Field(default=True)
@@ -1103,6 +1111,7 @@ class EditableSettings(
NodeUISettings,
BlockExplorerSettings,
AuditSettings,
+ SchedulerSettings,
TwoFactorSettings,
AuthSettings,
NostrAuthSettings,
diff --git a/lnbits/static/bundle-components.min.js b/lnbits/static/bundle-components.min.js
index c3baf90..50a46e3 100644
--- a/lnbits/static/bundle-components.min.js
+++ b/lnbits/static/bundle-components.min.js
@@ -1 +1 @@
-window.PageError={template:"#page-error"},window.PageHome={template:"#page-home",data:()=>({lnurl:"",authAction:"login",authMethod:"username-password",usr:"",username:"",reset_key:"",email:"",password:"",passwordRepeat:"",invitationCode:"",walletName:"",signup:!1}),computed:{showClaimLnurl(){return""!==this.lnurl&&this.g.settings.allowRegister&&this.g.settings.authMethods.includes("user-id-only")},formatDescription(){return LNbits.utils.convertMarkdown(this.g.settings.siteDescription)},isAccessTokenExpired(){return this.$q.cookies.get("is_access_token_expired")}},methods:{showLogin(e){this.authAction="login",this.authMethod=e},showRegister(e){this.user="",this.username=null,this.password=null,this.passwordRepeat=null,this.invitationCode=null,this.authAction="register",this.authMethod=e},async register(){try{await LNbits.api.register(this.username,this.email,this.password,this.passwordRepeat,this.invitationCode),this.refreshAuthUser()}catch(e){LNbits.utils.notifyApiError(e)}},async reset(){try{await LNbits.api.reset(this.reset_key,this.password,this.passwordRepeat),this.refreshAuthUser()}catch(e){LNbits.utils.notifyApiError(e)}},async login(){try{await LNbits.api.login(this.username,this.password),this.refreshAuthUser()}catch(e){LNbits.utils.notifyApiError(e)}},async loginUsr(){try{await LNbits.api.loginUsr(this.usr),this.refreshAuthUser()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}},async refreshAuthUser(){try{const e=await LNbits.api.getAuthUser();this.g.user=LNbits.map.user(e.data),this.g.isPublicPage=!1,this.$router.push(`/wallet/${this.g.user.wallets[0].id}`)}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}},createWallet(){LNbits.api.createAccount(this.walletName).then(e=>{this.$router.push(`/wallet/${e.data.id}`)})},processing(){Quasar.Notify.create({timeout:0,message:"Processing...",icon:null})}},created(){if(this.g.isUserAuthorized)return this.refreshAuthUser();const e=new URLSearchParams(window.location.search);this.reset_key=e.get("reset_key"),this.reset_key&&(this.authAction="reset"),e.has("lightning")&&(this.lnurl=e.get("lightning"))}},window.PageExtensionBuilder={template:"#page-extension-builder",data:()=>({step:1,previewStepNames:{2:"settings",3:"owner_data",4:"client_data",5:"public_page"},extensionDataCleanString:"",extensionData:{id:"",name:"",stub_version:"",short_description:"",description:"",public_page:{has_public_page:!0,owner_data_fields:{name:"",description:""},client_data_fields:{public_inputs:[]},action_fields:{generate_action:!0,generate_payment_logic:!1,wallet_id:"",currency:"",amount:"",paid_flag:""}},preview_action:{is_preview_mode:!1,is_settings_preview:!1,is_owner_data_preview:!1,is_client_data_preview:!1,is_public_page_preview:!1},settings_data:{name:"Settings",enabled:!0,type:"user",fields:[]},owner_data:{name:"OwnerData",fields:[]},client_data:{enabled:!0,name:"ClientData",fields:[]}},sampleField:{name:"name",type:"str",label:"Name",hint:"",optional:!0,editable:!0,searchable:!0,sortable:!0},settingsTypes:[{label:"User Settings",value:"user"},{label:"Admin Settings",value:"admin"}],amountSource:[{label:"Client Data",value:"client_data"},{label:"Owner Data",value:"owner_data"}],extensionStubVersions:[]}),watch:{"extensionData.public_page.action_fields.amount_source":function(e,t){t&&e!==t&&(this.extensionData.public_page.action_fields.amount="")}},computed:{paymentActionAmountFields(){const e=this.extensionData.public_page.action_fields.amount_source;return e?"owner_data"===e?[""].concat(this.extensionData.owner_data.fields.filter(e=>"int"===e.type||"float"===e.type).map(e=>e.name)):"client_data"===e?[""].concat(this.extensionData.client_data.fields.filter(e=>"int"===e.type||"float"===e.type).map(e=>e.name)):void 0:[""]}},methods:{saveState(){this.$q.localStorage.set("lnbits.extension.builder.data",JSON.stringify(this.extensionData)),this.$q.localStorage.set("lnbits.extension.builder.step",this.step)},nextStep(){this.saveState(),this.$refs.stepper.next(),this.refreshPreview()},previousStep(){this.saveState(),this.$refs.stepper.previous(),this.refreshPreview()},onStepChange(){this.saveState(),this.refreshPreview()},clearAllData(){LNbits.utils.confirmDialog("Are you sure you want to clear all data? This action cannot be undone.").onOk(()=>{this.extensionData=JSON.parse(this.extensionDataCleanString),this.$q.localStorage.remove("lnbits.extension.builder.data"),this.$refs.stepper.set(1)})},exportJsonData(){!0!==Quasar.exportFile(`${this.extensionData.id||"data-export"}.json`,JSON.stringify(this.extensionData,null,2),"text/json")?Quasar.Notify.create({message:"Browser denied file download...",color:"negative",icon:null}):Quasar.Notify.create({message:"File downloaded!",color:"positive",icon:"file_download"})},onJsonDataInput(e){const t=e.target.files[0],s=new FileReader;s.onload=e=>{this.extensionData={...this.extensionData,...JSON.parse(e.target.result)},this.$refs.extensionDataInput.value=null,Quasar.Notify.create({message:"File loaded!",color:"positive",icon:"file_upload"})},s.readAsText(t)},async buildExtension(){try{const e={responseType:"blob"},t=await LNbits.api.request("POST","/api/v1/extension/builder/zip",null,this.extensionData,e),s=window.URL.createObjectURL(new Blob([t.data])),i=document.createElement("a");i.href=s,i.download=`${this.extensionData.id||"lnbits-extension"}.zip`,document.body.appendChild(i),i.click(),i.remove(),window.URL.revokeObjectURL(s)}catch(e){LNbits.utils.notifyApiError(e)}},async buildExtensionAndDeploy(){try{const{data:e}=await LNbits.api.request("POST","/api/v1/extension/builder/deploy",null,this.extensionData);Quasar.Notify.create({message:e.message||"Extension deployed!",color:"positive"})}catch(e){LNbits.utils.notifyApiError(e)}},async cleanCacheData(){LNbits.utils.confirmDialog("Are you sure you want to clean the cache data? This action cannot be undone.","Clean Cache Data").onOk(async()=>{try{const{data:e}=await LNbits.api.request("DELETE","/api/v1/extension/builder",null,{});Quasar.Notify.create({message:e.message||"Cache data cleaned!",color:"positive"})}catch(e){LNbits.utils.notifyApiError(e)}})},async previewExtension(e){this.saveState();try{await LNbits.api.request("POST","/api/v1/extension/builder/preview",null,{...this.extensionData,preview_action:{is_preview_mode:!!e,is_settings_preview:"settings"===e,is_owner_data_preview:"owner_data"===e,is_client_data_preview:"client_data"===e,is_public_page_preview:"public_page"===e}}),this.refreshIframe(e)}catch(e){LNbits.utils.notifyApiError(e)}},async refreshPreview(){setTimeout(()=>{const e=this.previewStepNames[`${this.step}`]||"";e&&this.previewExtension(e)},100)},async getStubExtensionReleases(){try{const e="extension_builder_stub",{data:t}=await LNbits.api.request("GET",`/api/v1/extension/${e}/releases`);this.extensionStubVersions=t;const s=t.filter(e=>e.is_version_compatible);this.extensionData.stub_version=s[0]?s[0].version:""}catch(e){LNbits.utils.notifyApiError(e)}},refreshIframe(e=""){const t=this.$refs[`iframeStep${this.step}`];if(!t)return void console.warn("Extension Builder Preview iframe not loaded yet.");t.onload=()=>{const e=t.contentDocument||t.contentWindow.document;e.body.style.transform="scale(0.8)",e.body.style.transformOrigin="center top"};let s="Page"+this.extensionData.id.toLowerCase().split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("");"public_page"===e&&(s+="Public"),t.src=`/extensions/builder/preview?ext_id=${this.extensionData.id}&page=${e}&component=${s}`},initBasicData(){this.extensionData.owner_data.fields=[JSON.parse(JSON.stringify(this.sampleField))],this.extensionData.client_data.fields=[JSON.parse(JSON.stringify(this.sampleField))],this.extensionData.settings_data.fields=[JSON.parse(JSON.stringify(this.sampleField))],this.extensionDataCleanString=JSON.stringify(this.extensionData)}},created(){this.initBasicData();const e=this.$q.localStorage.getItem("lnbits.extension.builder.data");e&&(this.extensionData={...this.extensionData,...JSON.parse(e)});const t=+this.$q.localStorage.getItem("lnbits.extension.builder.step");t&&(this.step=t),this.g.user.admin&&this.getStubExtensionReleases(),setTimeout(()=>{this.refreshIframe()},1e3)}},window.PageExtensionBuilder={template:"#page-extension-builder",data:()=>({step:1,previewStepNames:{2:"settings",3:"owner_data",4:"client_data",5:"public_page"},extensionDataCleanString:"",extensionData:{id:"",name:"",stub_version:"",short_description:"",description:"",public_page:{has_public_page:!0,owner_data_fields:{name:"",description:""},client_data_fields:{public_inputs:[]},action_fields:{generate_action:!0,generate_payment_logic:!1,wallet_id:"",currency:"",amount:"",paid_flag:""}},preview_action:{is_preview_mode:!1,is_settings_preview:!1,is_owner_data_preview:!1,is_client_data_preview:!1,is_public_page_preview:!1},settings_data:{name:"Settings",enabled:!0,type:"user",fields:[]},owner_data:{name:"OwnerData",fields:[]},client_data:{enabled:!0,name:"ClientData",fields:[]}},sampleField:{name:"name",type:"str",label:"Name",hint:"",optional:!0,editable:!0,searchable:!0,sortable:!0},settingsTypes:[{label:"User Settings",value:"user"},{label:"Admin Settings",value:"admin"}],amountSource:[{label:"Client Data",value:"client_data"},{label:"Owner Data",value:"owner_data"}],extensionStubVersions:[]}),watch:{"extensionData.public_page.action_fields.amount_source":function(e,t){t&&e!==t&&(this.extensionData.public_page.action_fields.amount="")}},computed:{paymentActionAmountFields(){const e=this.extensionData.public_page.action_fields.amount_source;return e?"owner_data"===e?[""].concat(this.extensionData.owner_data.fields.filter(e=>"int"===e.type||"float"===e.type).map(e=>e.name)):"client_data"===e?[""].concat(this.extensionData.client_data.fields.filter(e=>"int"===e.type||"float"===e.type).map(e=>e.name)):void 0:[""]}},methods:{saveState(){this.$q.localStorage.set("lnbits.extension.builder.data",JSON.stringify(this.extensionData)),this.$q.localStorage.set("lnbits.extension.builder.step",this.step)},nextStep(){this.saveState(),this.$refs.stepper.next(),this.refreshPreview()},previousStep(){this.saveState(),this.$refs.stepper.previous(),this.refreshPreview()},onStepChange(){this.saveState(),this.refreshPreview()},clearAllData(){LNbits.utils.confirmDialog("Are you sure you want to clear all data? This action cannot be undone.").onOk(()=>{this.extensionData=JSON.parse(this.extensionDataCleanString),this.$q.localStorage.remove("lnbits.extension.builder.data"),this.$refs.stepper.set(1)})},exportJsonData(){!0!==Quasar.exportFile(`${this.extensionData.id||"data-export"}.json`,JSON.stringify(this.extensionData,null,2),"text/json")?Quasar.Notify.create({message:"Browser denied file download...",color:"negative",icon:null}):Quasar.Notify.create({message:"File downloaded!",color:"positive",icon:"file_download"})},onJsonDataInput(e){const t=e.target.files[0],s=new FileReader;s.onload=e=>{this.extensionData={...this.extensionData,...JSON.parse(e.target.result)},this.$refs.extensionDataInput.value=null,Quasar.Notify.create({message:"File loaded!",color:"positive",icon:"file_upload"})},s.readAsText(t)},async buildExtension(){try{const e={responseType:"blob"},t=await LNbits.api.request("POST","/api/v1/extension/builder/zip",null,this.extensionData,e),s=window.URL.createObjectURL(new Blob([t.data])),i=document.createElement("a");i.href=s,i.download=`${this.extensionData.id||"lnbits-extension"}.zip`,document.body.appendChild(i),i.click(),i.remove(),window.URL.revokeObjectURL(s)}catch(e){LNbits.utils.notifyApiError(e)}},async buildExtensionAndDeploy(){try{const{data:e}=await LNbits.api.request("POST","/api/v1/extension/builder/deploy",null,this.extensionData);Quasar.Notify.create({message:e.message||"Extension deployed!",color:"positive"})}catch(e){LNbits.utils.notifyApiError(e)}},async cleanCacheData(){LNbits.utils.confirmDialog("Are you sure you want to clean the cache data? This action cannot be undone.","Clean Cache Data").onOk(async()=>{try{const{data:e}=await LNbits.api.request("DELETE","/api/v1/extension/builder",null,{});Quasar.Notify.create({message:e.message||"Cache data cleaned!",color:"positive"})}catch(e){LNbits.utils.notifyApiError(e)}})},async previewExtension(e){this.saveState();try{await LNbits.api.request("POST","/api/v1/extension/builder/preview",null,{...this.extensionData,preview_action:{is_preview_mode:!!e,is_settings_preview:"settings"===e,is_owner_data_preview:"owner_data"===e,is_client_data_preview:"client_data"===e,is_public_page_preview:"public_page"===e}}),this.refreshIframe(e)}catch(e){LNbits.utils.notifyApiError(e)}},async refreshPreview(){setTimeout(()=>{const e=this.previewStepNames[`${this.step}`]||"";e&&this.previewExtension(e)},100)},async getStubExtensionReleases(){try{const e="extension_builder_stub",{data:t}=await LNbits.api.request("GET",`/api/v1/extension/${e}/releases`);this.extensionStubVersions=t;const s=t.filter(e=>e.is_version_compatible);this.extensionData.stub_version=s[0]?s[0].version:""}catch(e){LNbits.utils.notifyApiError(e)}},refreshIframe(e=""){const t=this.$refs[`iframeStep${this.step}`];if(!t)return void console.warn("Extension Builder Preview iframe not loaded yet.");t.onload=()=>{const e=t.contentDocument||t.contentWindow.document;e.body.style.transform="scale(0.8)",e.body.style.transformOrigin="center top"};let s="Page"+this.extensionData.id.toLowerCase().split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("");"public_page"===e&&(s+="Public"),t.src=`/extensions/builder/preview?ext_id=${this.extensionData.id}&page=${e}&component=${s}`},initBasicData(){this.extensionData.owner_data.fields=[JSON.parse(JSON.stringify(this.sampleField))],this.extensionData.client_data.fields=[JSON.parse(JSON.stringify(this.sampleField))],this.extensionData.settings_data.fields=[JSON.parse(JSON.stringify(this.sampleField))],this.extensionDataCleanString=JSON.stringify(this.extensionData)}},created(){this.initBasicData();const e=this.$q.localStorage.getItem("lnbits.extension.builder.data");e&&(this.extensionData={...this.extensionData,...JSON.parse(e)});const t=+this.$q.localStorage.getItem("lnbits.extension.builder.step");t&&(this.step=t),this.g.user.admin&&this.getStubExtensionReleases(),setTimeout(()=>{this.refreshIframe()},1e3)}},window.PageExtensionBuilderPreview={template:"#page-extension-builder-preview",mixins:[windowMixin],watch:{name:"reload"},data:()=>({extId:"",pageName:"",componentName:null}),methods:{async reload(){await LNbits.utils.loadTemplate(`/extensions/builder/preview/${this.extId}/template?page_name=${this.pageName}`),await LNbits.utils.loadScript(`/extensions/builder/preview/${this.extId}/component?page_name=${this.pageName}`),this._component=window[this.componentName],console.log("LNbits preview reloaded componentName:",this.componentName,!!this._component),this.$forceUpdate()}},async created(){const e=new URLSearchParams(window.location.search);this.extId=e.get("ext_id")||"",this.pageName=e.get("page")||"",this.componentName=e.get("component")||"",await this.reload()},render(){return this._component?Vue.h(this._component):Vue.h("div","Loading...")}};const EXTENSION_PERMISSION_DEFAULT_MAX_ROWS_PER_SOURCE=1e4,EXTENSION_PERMISSION_MAX_ROWS_PER_SOURCE_LIMIT=1e6,EXTENSION_PERMISSION_MAX_MESSAGES_PER_SECOND_LIMIT=100;window.PageExtensions={template:"#page-extensions",data(){return{extbuilderEnabled:!1,slide:0,fullscreen:!1,autoplay:!0,searchTerm:"",tab:"installed",manageExtensionTab:"releases",filteredExtensions:[],categories:new Set,updatableExtensions:[],showUninstallDialog:!1,showManageExtensionDialog:!1,showExtensionDetailsDialog:!1,showDropDbDialog:!1,showPayToEnableDialog:!1,showUpdateAllDialog:!1,dropDbExtensionId:"",selectedExtension:null,selectedImage:null,selectedExtensionDetails:null,selectedExtensionDetailsDescription:"",selectedExtensionRepos:null,selectedRelease:null,permissionGrant:{show:!1,permissions:[],resolve:null},extensionPermissionMaxRowsPerSourceLimit:1e6,extensionPermissionMaxMessagesPerSecondLimit:100,managedExtensionPermissions:{loading:!1,extensionPermissions:[],userPermissions:{},savingExtensionPermissions:!1,savingKey:"",deletingKey:""},backgroundPaymentDestinationOptions:[{label:"Only transfers to my wallets",value:"own_wallets_only"},{label:"Allow external payments",value:"external_allowed"}],uninstallAndDropDb:!1,maxStars:5,paylinkWebsocket:null,searchToggle:!1,reviewsUrl:null,reviewsDialog:{show:!1,extension:null,loading:!1,submitting:!1,form:{name:"",rating:0,comment:""},error:null},reviews:[],reviewsTable:{loading:!1,columns:[{name:"name",align:"left",label:this.$t("Name"),field:"name",sortable:!0},{name:"comment",align:"left",label:this.$t("Comment"),field:"comment"},{name:"created_at",align:"left",label:this.$t("Date"),field:"created_at"},{name:"rating",align:"right",label:"Rating",field:"rating"}],pagination:{rowsPerPage:5,sortBy:"created_at",descending:!0,page:1}},paymentDialog:{show:!1,invoice:"",hash:""}}},watch:{searchTerm(e){this.filterExtensions(e,this.tab)},tab(e){this.filterExtensions(this.searchTerm,e)}},computed:{managedUserPermissionRows(){const e=[],t=this.managedExtensionPermissions.userPermissions||{};return Object.entries(t).forEach(([t,s])=>{Array.isArray(s)&&s.forEach(s=>{if(!s||"object"!=typeof s)return;const i=String(s.id||""),a=String(s.wallet_id||"");i&&a&&e.push({key:i,permissionId:t,label:this.permissionLabelById(t),grantId:i,walletId:a,walletName:this.walletName(a),grant:s})})}),e}},methods:{filterExtensions(e,t){const s=!["installed","all","featured"].includes(t);var i;this.filteredExtensions=this.extensions.filter(e=>"all"!==t||!e.isInstalled).filter(e=>"installed"!==t||e.isInstalled).filter(e=>"installed"!==t||(!!e.isActive||!!this.g.user.admin)).filter(e=>"featured"!==t||e.isFeatured).filter(e=>!s||(e=>e.categories?.includes(t)??!1)(e)).filter((i=e,function(e){return e.name.toLowerCase().includes(i.toLowerCase())||e.shortDescription?.toLowerCase().includes(i.toLowerCase())})).map(e=>({...e,details_link:e.installedRelease?.details_link||e.latestRelease?.details_link}))},async installExtension(e){this.unsubscribeFromPaylinkWs();const t=await this.resolveExtensionPermissionGrant(e);null!==t&&(this.selectedExtension.inProgress=!0,this.showManageExtensionDialog=!1,e.payment_hash=e.payment_hash||this.getPaylinkHash(e.pay_link),LNbits.api.request("POST","/api/v1/extension",this.g.user.wallets[0].adminkey,{ext_id:this.selectedExtension.id,archive:e.archive,source_repo:e.source_repo,payment_hash:e.payment_hash,version:e.version,permissions:t}).then(t=>{this.selectedExtension.inProgress=!1;const s=this.extensions.find(e=>e.id===this.selectedExtension.id);s.isAvailable=!0,s.isInstalled=!0,s.isWasm=!0===t.data.is_wasm||!0===t.data.isWasm||"wasm"===e.extension_type||!0===s.isWasm,s.icon=t.data.icon||s.icon,s.installedRelease=e,this.toggleExtension(s),s.inProgress=!1,this.selectedExtension=s,this.extensions=this.extensions.concat([]),this.tab="installed"}).catch(e=>{console.warn(e),this.selectedExtension.inProgress=!1,LNbits.utils.notifyApiError(e)}))},async uninstallExtension(){this.showManageExtensionDialog=!1,this.showUninstallDialog=!1,this.selectedExtension.inProgress=!0,LNbits.api.request("DELETE",`/api/v1/extension/${this.selectedExtension.id}`,this.g.user.wallets[0].adminkey).then(e=>{const t=this.extensions.find(e=>e.id===this.selectedExtension.id);t.isAvailable=!1,t.isInstalled=!1,t.inProgress=!1,t.installedRelease=null,this.filteredExtensions=this.filteredExtensions.filter(e=>e.id!==t.id),Quasar.Notify.create({type:"positive",message:"Extension uninstalled!"}),this.uninstallAndDropDb&&this.showDropDb()}).catch(e=>{LNbits.utils.notifyApiError(e),extension.inProgress=!1})},async dropExtensionDb(){const e=this.selectedExtension;this.showManageExtensionDialog=!1,this.showDropDbDialog=!1,this.dropDbExtensionId="",e.inProgress=!0,LNbits.api.request("DELETE",`/api/v1/extension/${e.id}/db`,this.g.user.wallets[0].adminkey).then(t=>{e.installedRelease=null,e.inProgress=!1,e.hasDatabaseTables=!1,Quasar.Notify.create({type:"positive",message:"Extension DB deleted!"})}).catch(t=>{LNbits.utils.notifyApiError(t),e.inProgress=!1})},toggleExtension(e){const t=e.isActive?"activate":"deactivate";LNbits.api.request("PUT",`/api/v1/extension/${e.id}/${t}`,this.g.user.wallets[0].adminkey).then(s=>{Quasar.Notify.create({timeout:2e3,type:"positive",message:`Extension '${e.id}' ${t}d!`})}).catch(t=>{LNbits.utils.notifyApiError(t),e.isActive=!1,e.inProgress=!1})},async enableExtensionForUser(e){e.isPaymentRequired?this.showPayToEnable(e):this.enableExtension(e)},async enableExtension(e){LNbits.api.request("PUT",`/api/v1/extension/${e.id}/enable`,this.g.user.wallets[0].adminkey).then(t=>{this.g.user.extensions=this.g.user.extensions.concat([e.id]),Quasar.Notify.create({type:"positive",message:"Extension enabled!"})}).catch(e=>{console.warn(e),LNbits.utils.notifyApiError(e)})},disableExtension(e){LNbits.api.request("PUT",`/api/v1/extension/${e.id}/disable`,this.g.user.wallets[0].adminkey).then(t=>{this.g.user.extensions=this.g.user.extensions.filter(t=>t!==e.id),Quasar.Notify.create({type:"positive",message:"Extension disabled!"})}).catch(e=>{console.warn(error),LNbits.utils.notifyApiError(e)})},showPayToEnable(e){this.selectedExtension=e,this.selectedExtension.payToEnable.paidAmount=e.payToEnable.amount,this.selectedExtension.payToEnable.showQRCode=!1,this.showPayToEnableDialog=!0},updatePayToInstallData(e){LNbits.api.request("PUT",`/api/v1/extension/${e.id}/sell`,this.g.user.wallets[0].adminkey,{required:e.payToEnable.required,amount:e.payToEnable.amount,wallet:e.payToEnable.wallet}).then(e=>{Quasar.Notify.create({type:"positive",message:"Payment info updated!"}),this.showManageExtensionDialog=!1}).catch(t=>{LNbits.utils.notifyApiError(t),e.inProgress=!1})},showUninstall(){this.showManageExtensionDialog=!1,this.showUninstallDialog=!0,this.uninstallAndDropDb=!1},showDropDb(){this.showDropDbDialog=!0},async showManageExtension(e){if(this.selectedExtension=e,this.selectedRelease=null,this.selectedExtensionRepos=null,this.resetManagedExtensionPermissions(),this.manageExtensionTab=this.g.user.admin?"releases":"extension-permissions",this.showManageExtensionDialog=!0,this.canManageExtensionPermissions(e)&&this.loadManagedExtensionPermissions(e),this.g.user.admin)try{const{data:t}=await LNbits.api.request("GET",`/api/v1/extension/${e.id}/releases`);this.selectedExtensionRepos=t.reduce((e,t)=>(e[t.source_repo]=e[t.source_repo]||{releases:[],isInstalled:!1,repo:t.repo},t.inProgress=!1,t.error=null,t.loaded=!1,t.isInstalled=this.isInstalledVersion(this.selectedExtension,t),t.isInstalled&&(e[t.source_repo].isInstalled=!0),t.pay_link&&(t.requiresPayment=!0,t.paidAmount=t.cost_sats,t.payment_hash=this.getPaylinkHash(t.pay_link)),e[t.source_repo].releases.push(t),e),{})}catch(t){LNbits.utils.notifyApiError(t),e.inProgress=!1}},canShowManageExtensionButton(e){return this.g.user.admin||!0===e?.isWasm&&!0===e?.isInstalled},canManageExtensionPermissions(e=this.selectedExtension){return!0===e?.isWasm&&!0===e?.isInstalled},canShowAdminManageTabs(){return!0===this.g.user.admin},resetManagedExtensionPermissions(){this.managedExtensionPermissions={loading:!1,extensionPermissions:[],userPermissions:{},savingExtensionPermissions:!1,savingKey:"",deletingKey:""}},async loadManagedExtensionPermissions(e=this.selectedExtension){if(this.canManageExtensionPermissions(e)){this.managedExtensionPermissions.loading=!0;try{const{data:t}=await LNbits.api.request("GET",`/api/v1/extension/${e.id}/permissions`);this.managedExtensionPermissions.extensionPermissions=this.cloneEditableExtensionPermissions(t.extension_permissions||[]),this.managedExtensionPermissions.userPermissions=this.cloneUserPermissions(t.user_permissions||{})}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}finally{this.managedExtensionPermissions.loading=!1}}},cloneEditableExtensionPermissions(e){return(e||[]).filter(e=>e&&"object"==typeof e).map(e=>({...e,policies:Array.isArray(e.policies)?e.policies.map(t=>this.cloneEditablePermissionPolicy(e.id,t)):e.policies}))},cloneEditablePermissionPolicy(e,t){if(!t||"object"!=typeof t||Array.isArray(t))return t;const s=Object.entries(t).reduce((e,[t,s])=>({...e,[t]:Array.isArray(s)?s.slice():s}),{});return"ext.storage.append_public"===e&&(s.max_rows_per_source=this.maxRowsPerSourceValue(s.max_rows_per_source,1e4)),"websocket.publish"===e&&(s.max_messages_per_second=Number(s.max_messages_per_second)),s},maxRowsPerSourceValue(e,t){const s=Number(e);return!Number.isInteger(s)||s<=0?t:Math.min(s,1e6)},extensionPermissionLimitError(e){const t=(e||[]).find(e=>"ext.storage.append_public"===e?.id);if(!t||!Array.isArray(t.policies))return this.websocketPublishLimitError(e);for(const e of t.policies){if(!e||"object"!=typeof e)continue;const t=Number(e.max_rows_per_source);if(!Number.isInteger(t)||t<=0)return"Max rows per source must be a positive integer.";if(t>1e6)return"Max rows per source cannot exceed 1000000."}return this.websocketPublishLimitError(e)},websocketPublishLimitError(e){const t=(e||[]).find(e=>"websocket.publish"===e?.id);if(!t)return"";if(!Array.isArray(t.policies)||1!==t.policies.length)return"Websocket publish requires a max messages per second policy.";const s=t.policies[0];if(!s||"object"!=typeof s)return"Websocket publish requires a max messages per second policy.";const i=Number(s.max_messages_per_second);return!Number.isInteger(i)||i<=0?"Max messages per second must be a positive integer.":i>100?"Max messages per second cannot exceed 100.":""},validateExtensionPermissionLimits(e){const t=this.extensionPermissionLimitError(e);return!t||(Quasar.Notify.create({type:"negative",message:t}),!1)},extensionPermissionsHaveEditableLimits:e=>(e||[]).some(e=>"ext.storage.append_public"===e?.id&&Array.isArray(e.policies)&&e.policies.length>0||"websocket.publish"===e?.id),async saveManagedExtensionPermissions(){const e=this.managedExtensionPermissions.extensionPermissions;if(this.validateExtensionPermissionLimits(e)){this.managedExtensionPermissions.savingExtensionPermissions=!0;try{const{data:t}=await LNbits.api.request("PUT",`/api/v1/extension/${this.selectedExtension.id}/permissions`,this.g.user.wallets[0].adminkey,{permissions:this.cloneEditableExtensionPermissions(e)});this.managedExtensionPermissions.extensionPermissions=this.cloneEditableExtensionPermissions(t.extension_permissions||[]),Quasar.Notify.create({type:"positive",message:"Permission updated."})}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}finally{this.managedExtensionPermissions.savingExtensionPermissions=!1}}},cloneUserPermissions(e){const t={};return Object.entries(e||{}).forEach(([e,s])=>{Array.isArray(s)&&(t[e]=s.filter(e=>e&&"object"==typeof e).map(e=>({...e,_original:{...e}})))}),t},async showExtensionDetails(e,t){if(t){this.selectedExtension=this.extensions.find(t=>t.id===e)||this.selectedExtension,this.selectedExtensionDetails=null,this.selectedExtensionDetailsDescription="",this.showExtensionDetailsDialog=!0,this.slide=0,this.fullscreen=!1;try{const{data:s}=await LNbits.api.request("GET",`/api/v1/extension/${e}/details?details_link=${t}`);this.selectedExtensionDetails=s,this.selectedExtensionDetailsDescription=this.extensionDescriptionDocument(s.description_md)}catch(e){console.warn(e)}}},extensionDescriptionDocument(e){const t="string"==typeof e?e:"",s=LNbits.utils.convertMarkdown(t),i=(new DOMParser).parseFromString(s,"text/html");i.body.querySelectorAll("applet, base, embed, form, frame, iframe, link, meta, object, portal, script").forEach(e=>e.remove()),i.body.querySelectorAll("*").forEach(e=>{for(const t of[...e.attributes]){const s=t.name.toLowerCase();(s.startsWith("on")||"srcdoc"===s||"xlink:href"===s)&&e.removeAttribute(t.name)}}),i.body.querySelectorAll("a[href], area[href]").forEach(e=>{try{const t=new URL(e.getAttribute("href"),window.location.origin);if(!["http:","https:"].includes(t.protocol)||t.username||t.password)return void e.removeAttribute("href");e.setAttribute("href",t.href),e.setAttribute("target","_blank"),e.setAttribute("rel","noopener noreferrer")}catch(t){e.removeAttribute("href")}});return`<!doctype html>\n <html>\n <head>\n <meta charset="utf-8">\n <meta http-equiv="Content-Security-Policy" content="${["default-src 'none'","img-src https: data:","style-src 'unsafe-inline'","script-src 'none'","script-src-attr 'none'","base-uri 'none'","form-action 'none'","frame-src 'none'","object-src 'none'"].join("; ")}">\n <meta name="referrer" content="no-referrer">\n <meta name="viewport" content="width=device-width, initial-scale=1">\n <style>\n :root { color-scheme: light dark; font-family: Roboto, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }\n body { margin: 0; color: CanvasText; background: Canvas; line-height: 1.5; overflow-wrap: anywhere; }\n img { max-width: 100%; height: auto; }\n pre { overflow: auto; padding: 0.75rem; background: color-mix(in srgb, CanvasText 8%, Canvas); }\n code { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; }\n table { display: block; max-width: 100%; overflow-x: auto; border-collapse: collapse; }\n th, td { padding: 0.35rem 0.6rem; border: 1px solid color-mix(in srgb, CanvasText 20%, Canvas); }\n a[href] { color: LinkText; cursor: pointer; }\n </style>\n </head>\n <body>\n ${i.body.innerHTML}\n </body>\n </html>`},async payAndInstall(e){try{if(null===await this.resolveExtensionPermissionGrant(e))return;this.selectedExtension.inProgress=!0,this.showManageExtensionDialog=!1;const t=await this.requestPaymentForInstall(this.selectedExtension.id,e);this.rememberPaylinkHash(e.pay_link,t.payment_hash);const s=this.g.user.wallets.find(t=>t.id===e.wallet),{data:i}=await LNbits.api.payInvoice(s,t.payment_request);e.payment_hash=i.payment_hash,await this.installExtension(e)}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}finally{this.selectedExtension.inProgress=!1}},async payAndEnable(e){try{const t=await this.requestPaymentForEnable(e.id,e.payToEnable.paidAmount),s=this.g.user.wallets.find(t=>t.id===e.payToEnable.paymentWallet),{data:i}=await LNbits.api.payInvoice(s,t.payment_request);this.enableExtension(e),this.showPayToEnableDialog=!1}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}},async showInstallQRCode(e){if(null!==await this.resolveExtensionPermissionGrant(e)){this.selectedRelease=e,this.showManageExtensionDialog=!0;try{const t=await this.requestPaymentForInstall(this.selectedExtension.id,e);this.selectedRelease.paymentRequest=t.payment_request,this.selectedRelease.payment_hash=t.payment_hash,this.selectedRelease=_.clone(this.selectedRelease),this.rememberPaylinkHash(this.selectedRelease.pay_link,this.selectedRelease.payment_hash),this.subscribeToPaylinkWs(this.selectedRelease.pay_link,t.payment_hash)}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}}},async showEnableQRCode(e){try{e.payToEnable.showQRCode=!0,this.selectedExtension=_.clone(e);const t=await this.requestPaymentForEnable(e.id,e.payToEnable.paidAmount);e.payToEnable.paymentRequest=t.payment_request,this.selectedExtension=_.clone(e);const s=new URL(window.location);s.protocol="https:"===s.protocol?"wss":"ws",s.pathname=`/api/v1/ws/${t.payment_hash}`;const i=new WebSocket(s);i.addEventListener("message",async({data:t})=>{!1===JSON.parse(t).pending&&(Quasar.Notify.create({type:"positive",message:"Invoice Paid!"}),this.enableExtension(e),i.close())})}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}},async requestPaymentForInstall(e,t){const{data:s}=await LNbits.api.request("PUT",`/api/v1/extension/${e}/invoice/install`,null,{ext_id:e,archive:t.archive,source_repo:t.source_repo,cost_sats:t.paidAmount,version:t.version});return s},async requestPaymentForEnable(e,t){const{data:s}=await LNbits.api.request("PUT",`/api/v1/extension/${e}/invoice/enable`,null,{amount:t});return s},clearHangingInvoice(e){this.forgetPaylinkHash(e.pay_link),e.payment_hash=null},rememberPaylinkHash(e,t){this.$q.localStorage.set(`lnbits.extensions.paylink.${e}`,t)},getPaylinkHash(e){return this.$q.localStorage.getItem(`lnbits.extensions.paylink.${e}`)},forgetPaylinkHash(e){this.$q.localStorage.remove(`lnbits.extensions.paylink.${e}`)},subscribeToPaylinkWs(e,t){const s=new URL(`${e}/${t}`);s.protocol="https:"===s.protocol?"wss":"ws",this.paylinkWebsocket=new WebSocket(s),this.paylinkWebsocket.addEventListener("message",async({data:e})=>{JSON.parse(e).paid?(Quasar.Notify.create({type:"positive",message:"Invoice Paid!"}),this.installExtension(this.selectedRelease)):Quasar.Notify.create({type:"warning",message:"Invoice tracking lost!"})})},unsubscribeFromPaylinkWs(){try{this.paylinkWebsocket&&this.paylinkWebsocket.close()}catch(e){console.warn(e)}},hasNewVersion(e){if(e.installedRelease&&e.latestRelease)return e.installedRelease.version!==e.latestRelease.version},isInstalledVersion(e,t){if(e.installedRelease)return e.installedRelease.source_repo===t.source_repo&&e.installedRelease.version===t.version},getReleaseIcon:e=>e.is_version_compatible?e.isInstalled?"download_done":"download":"block",getReleaseIconColor:e=>e.is_version_compatible?e.isInstalled?"text-green":"":"text-red",extensionOpenUrl:e=>e.isWasm?`/ext/${e.id}`:`/${e.id}`,permissionLabelById(e){const t=`extension_permission_${String(e).replace(/[^A-Za-z0-9]/g,"_")}`,s=this.$t(t);return s===t?e:s},walletName(e){const t=(this.g.user.wallets||[]).find(t=>t.id===e);return t?t.name||t.id:e},userPermissionRowCaption:e=>`${e.walletName} (${e.walletId.slice(0,8)}...)`,isBackgroundPaymentPermission:e=>"wallet.pay_invoice_background"===e.permissionId,userPermissionGrantPayload(e){return{wallet_id:e.walletId,max_amount:this.positiveInteger(e.grant.max_amount,0),destination_policy:this.backgroundPaymentDestinationPolicy(e.grant.destination_policy)}},positiveInteger(e,t){const s=Number(e);return!Number.isFinite(s)||s<=0?t:Math.floor(s)},backgroundPaymentDestinationPolicy:e=>"external_allowed"===e?"external_allowed":"own_wallets_only",backgroundPaymentGrantIncreased(e,t){const s=e.grant._original||{},i=this.positiveInteger(s.max_amount,0),a=this.backgroundPaymentDestinationPolicy(s.destination_policy);return t.max_amount>i||"own_wallets_only"===a&&"external_allowed"===t.destination_policy},confirmUserPermissionIncrease:()=>new Promise(e=>{let t=!1;const s=s=>{t||(t=!0,e(s))};LNbits.utils.confirmDialog("This increases what the extension can do with this wallet. Continue?").onOk(()=>s(!0)).onCancel(()=>s(!1)).onDismiss(()=>s(!1))}),async saveUserPermissionGrant(e){if(!this.isBackgroundPaymentPermission(e))return;const t=this.userPermissionGrantPayload(e);if(t.max_amount){if(!this.backgroundPaymentGrantIncreased(e,t)||await this.confirmUserPermissionIncrease()){this.managedExtensionPermissions.savingKey=e.key;try{await LNbits.api.request("POST",`/api/v1/extension/${this.selectedExtension.id}/permissions/background-payment`,null,t),Quasar.Notify.create({type:"positive",message:"Permission updated."}),await this.loadManagedExtensionPermissions()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}finally{this.managedExtensionPermissions.savingKey=""}}}else Quasar.Notify.create({type:"negative",message:"Max payment amount must be greater than zero."})},deleteUserPermissionGrant(e){LNbits.utils.confirmDialog("Remove this permission grant?").onOk(async()=>{this.managedExtensionPermissions.deletingKey=e.key;try{const t=encodeURIComponent(e.grantId);await LNbits.api.request("DELETE",`/api/v1/extension/${this.selectedExtension.id}/permissions/user/${t}`),Quasar.Notify.create({type:"positive",message:"Permission removed."}),await this.loadManagedExtensionPermissions()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}finally{this.managedExtensionPermissions.deletingKey=""}})},async getGitHubReleaseDetails(e){if(!e.is_github_release||e.loaded)return;const[t,s]=e.source_repo.split("/");e.inProgress=!0;try{const{data:i}=await LNbits.api.request("GET",`/api/v1/extension/release/${t}/${s}/${e.version}`);e.loaded=!0,e.is_version_compatible=i.is_version_compatible,e.min_lnbits_version=i.min_lnbits_version,e.warning=i.warning,e.extension_type=i.extension_type,e.permissions=i.permissions||[]}catch(t){console.warn(t),e.error=t,LNbits.utils.notifyApiError(t)}finally{e.inProgress=!1}},async resolveExtensionPermissionGrant(e){const t=this.extensionPermissionsForRelease(e);if(!this.releaseRequiresPermissionGrant(e)||!t.length)return[];if(e.grantedPermissions)return e.grantedPermissions;const s=await this.confirmExtensionPermissions(t);return s?(e.grantedPermissions=s,s):null},extensionPermissionsForRelease(e){return e.permissions||this.selectedExtension?.permissions||[]},releaseRequiresPermissionGrant(e){return"wasm"===e.extension_type||!0===this.selectedExtension?.isWasm},confirmExtensionPermissions(e){return new Promise(t=>{this.selectedRelease=null,this.permissionGrant={show:!0,permissions:this.cloneEditableExtensionPermissions(e),resolve:t},this.showManageExtensionDialog=!0})},grantExtensionPermissions(){this.validateExtensionPermissionLimits(this.permissionGrant.permissions)&&this.resolveExtensionPermissionDialog(this.cloneEditableExtensionPermissions(this.permissionGrant.permissions))},cancelExtensionPermissions(){this.resolveExtensionPermissionDialog(null)},onManageExtensionDialogHide(){this.permissionGrant.show&&this.resolveExtensionPermissionDialog(null)},resolveExtensionPermissionDialog(e){const t=this.permissionGrant.resolve;this.permissionGrant={show:!1,permissions:[],resolve:null},this.showManageExtensionDialog=!1,t&&t(e)},permissionGrantHasHighRisk(){return window.LNbitsExtensionPermissions.hasHighRisk({permissions:this.permissionGrant.permissions,extensions:this.extensions,translate:e=>this.$t(e)})},async selectAllUpdatableExtensionss(){this.updatableExtensions.forEach(e=>e.selectedForUpdate=!0)},async updateSelectedExtensions(){let e=0;for(const t of this.updatableExtensions)try{if(!t.selectedForUpdate)continue;if(t.isWasm){Quasar.Notify.create({type:"warning",message:`Skipping ${t.id}; this extension update requires permission approval.`});continue}t.inProgress=!0,await LNbits.api.request("POST","/api/v1/extension",null,{ext_id:t.id,archive:t.latestRelease.archive,source_repo:t.latestRelease.source_repo,payment_hash:t.latestRelease.payment_hash,version:t.latestRelease.version}),e++,t.isAvailable=!0,t.isInstalled=!0,t.isUpgraded=!0,t.inProgress=!1,t.installedRelease=t.latestRelease,t.isActive=!0,this.toggleExtension(t)}catch(e){console.warn(e),Quasar.Notify.create({type:"negative",message:`Failed to update ${t.id}!`})}finally{t.inProgress=!1}Quasar.Notify.create({type:e?"positive":"warning",message:`${e||"No"} extensions updated!`}),this.showUpdateAllDialog=!1},formatAvg(e){const t=Number(e||0);return Math.round(t/2/100*2)/2},async loadReviewStats(){if(this.reviewsUrl)try{const{data:e}=await LNbits.api.request("GET","/api/v1/extension/reviews/tags"),t={};e.forEach(e=>{t[e.tag]=e}),this.extensions.forEach(e=>{e.reviewStats=t[e.id]||null}),this.filterExtensions(this.searchTerm,this.tab)}catch(e){console.warn(e)}else console.info("Extension reviews are not configured")},async openReviews(e){const t=e||(this.selectedExtensionDetails?this.extensions.find(e=>e.id===this.selectedExtensionDetails.id):null);t&&(this.reviewsUrl?(this.reviewsDialog.extension=t,this.selectedExtension=e,this.reviewsDialog.show=!0,await this.getTagReviews()):Quasar.Notify.create({type:"warning",message:this.$t("reviews_url_not_configured")}))},async getTagReviews(e){if(this.reviewsUrl)try{this.reviewsTable.loading=!0;const t=LNbits.utils.prepareFilterQuery(this.reviewsTable,e),{data:s}=await LNbits.api.request("GET",`/api/v1/extension/reviews/${this.selectedExtension.id}?${t}`);this.reviews=s.data,this.reviewsTable.pagination.rowsNumber=s.total}catch(e){LNbits.utils.notifyApiError(e)}finally{this.reviewsTable.loading=!1}else Quasar.Notify.create({type:"warning",message:this.$t("reviews_url_not_configured")})},formatReviewDate(e){if(!e)return"";const t=Number(e);return Number.isNaN(t)?this.utils.formatDate(e):this.utils.formatTimestamp(t)},async submitReview(){if(this.reviewsDialog.extension&&this.reviewsUrl){this.reviewsDialog.submitting=!0;try{const e={tag:this.reviewsDialog.extension.id,name:this.reviewsDialog.form.name,rating:100*this.reviewsDialog.form.rating,comment:this.reviewsDialog.form.comment},{data:t}=await LNbits.api.request("PUT","/api/v1/extension/reviews",null,e);t.payment_request?this.openInvoiceDialog(t.payment_request,t.payment_hash):(Quasar.Notify.create({type:"positive",message:"Review submitted"}),this.resetReviewForm(),await this.getTagReviews(),await this.loadReviewStats())}catch(e){LNbits.utils.notifyApiError(e)}finally{this.reviewsDialog.submitting=!1}}},openInvoiceDialog(e,t){this.paymentDialog.invoice=e,this.paymentDialog.hash=t,this.paymentDialog.show=!0,this.listenForPayment(t)},resetReviewForm(){this.reviewsDialog.form={name:"",rating:0,comment:""},this.paymentDialog={show:!1,invoice:"",hash:""}},listenForPayment(e){try{const t=new URL(this.reviewsUrl);t.protocol="https:"===t.protocol?"wss:":"ws:",t.pathname=`/api/v1/ws/${e}`;const s=new WebSocket(t);s.addEventListener("message",async()=>{Quasar.Notify.create({type:"positive",message:this.$t("reviews_invoice_paid")}),this.paymentDialog.show=!1,this.resetReviewForm(),setTimeout(async()=>{await this.getTagReviews()},1e3),await this.loadReviewStats(),s.close()})}catch(e){console.warn(e)}},async fetchAllExtensions(){try{const{data:e}=await LNbits.api.request("GET","/api/v1/extension/all");return e.forEach(e=>{e.categories?.forEach(e=>this.categories.add(e))}),e}catch(e){return console.warn(e),LNbits.utils.notifyApiError(e),[]}}},async created(){this.extensions=await this.fetchAllExtensions(),this.extbuilderEnabled=this.g.user.admin||this.g.settings.extBuilder,this.reviewsUrl=this.g.settings.extensionsReviewsUrl,0===this.g.user.extensions.length&&(this.tab="all");const e=window.location.hash.replace("#",""),t=this.extensions.find(t=>t.id===e);t&&(this.searchTerm=t.id,t.isInstalled&&(this.tab="installed")),this.updatableExtensions=this.extensions.filter(e=>this.hasNewVersion(e)),await this.loadReviewStats(),this.filterExtensions(this.searchTerm,this.tab)}},window.PageFirstInstall={template:"#page-first-install",data:()=>({loginData:{isPwd:!0,isPwdRepeat:!0,username:"",password:"",passwordRepeat:"",firstInstallToken:""}}),computed:{checkPasswordsMatch(){return this.loginData.password!==this.loginData.passwordRepeat}},methods:{setPassword(){LNbits.api.request("PUT","/api/v1/auth/first_install",null,{username:this.loginData.username,password:this.loginData.password,password_repeat:this.loginData.passwordRepeat,first_install_token:this.loginData.firstInstallToken}).then(async()=>{const e=await LNbits.api.getAuthUser();this.g.user=LNbits.map.user(e.data),this.g.isPublicPage=!1,this.$router.push("/admin")}).catch(this.utils.notifyApiError)}},created(){const e=new URLSearchParams(window.location.search);this.loginData.firstInstallToken=e.get("token")||""}},window.PagePayments={template:"#page-payments",data:()=>({payments:[],dailyChartData:[],searchDate:{from:null,to:null},searchData:{wallet_id:null,payment_hash:null,memo:null,internal_memo:null},statusFilters:{success:!0,pending:!0,failed:!0,incoming:!0,outgoing:!0},chartData:{showPaymentStatus:!0,showPaymentTags:!0,showBalance:!0,showWalletsSize:!1,showBalanceInOut:!1,showPaymentCountInOut:!1},searchOptions:{status:[]},paymentsTable:{columns:[{name:"status",align:"left",label:"Status",field:"status",sortable:!1},{name:"created_at",align:"left",label:"Created At",field:"created_at",sortable:!0},{name:"amount",align:"right",label:"Amount",field:"amount",sortable:!0},{name:"amountFiat",align:"right",label:"Fiat",field:"amountFiat",sortable:!1},{name:"fee_sats",align:"left",label:"Fee",field:"fee_sats",sortable:!0},{name:"tag",align:"left",label:"Tag",field:"tag",sortable:!1},{name:"memo",align:"left",label:"Memo",field:"memo",sortable:!1,max_length:20},{name:"internal_memo",align:"left",label:"Internal Memo",field:"internal_memo",sortable:!1,max_length:20},{name:"wallet_id",align:"left",label:"Wallet (ID)",field:"wallet_id",sortable:!1},{name:"payment_hash",align:"left",label:"Payment Hash",field:"payment_hash",sortable:!1}],pagination:{sortBy:"created_at",rowsPerPage:25,page:1,descending:!0,rowsNumber:10},search:null,hideEmpty:!0,loading:!1},chartsReady:!1,showDetails:!1,formatJson:!1,paymentDetails:null,lnbitsBalance:0}),async mounted(){this.chartsReady=!0,await this.$nextTick(),this.initCharts(),await this.fetchPayments()},computed:{paymentDetailsJson(){return this.paymentDetails&&{...this.paymentDetails,extra:JSON.stringify(Object.fromEntries(Object.keys(this.paymentDetails.extra||{}).sort().map(e=>[e,this.paymentDetails.extra[e]])),null,this.formatJson?2:0)}}},methods:{async fetchPayments(e){const t=Object.entries(this.searchData).reduce((e,[t,s])=>s?(e[t]=s,e):e,{});delete t["time[ge]"],delete t["time[le]"],this.searchDate.from&&(t["time[ge]"]=this.searchDate.from+"T00:00:00"),this.searchDate.to&&(t["time[le]"]=this.searchDate.to+"T23:59:59"),this.paymentsTable.filter=t;try{const t=LNbits.utils.prepareFilterQuery(this.paymentsTable,e),{data:s}=await LNbits.api.request("GET",`/api/v1/payments/all/paginated?${t}`);this.paymentsTable.pagination.rowsNumber=s.total,this.payments=s.data.map(e=>(e.extra&&e.extra.tag&&(e.tag=e.extra.tag),e.timeFrom=moment.utc(e.created_at).local().fromNow(),e.outgoing=e.amount<0,e.amount=new Intl.NumberFormat(this.g.locale).format(e.amount/1e3)+" sats",e.extra?.wallet_fiat_amount&&(e.amountFiat=this.formatCurrency(e.extra.wallet_fiat_amount,e.extra.wallet_fiat_currency)),e.extra?.internal_memo&&(e.internal_memo=e.extra.internal_memo),e.fee_sats=new Intl.NumberFormat(this.g.locale).format(e.fee/1e3)+" sats",e))}catch(e){console.error(e),LNbits.utils.notifyApiError(e)}finally{this.updateCharts(e)}},async searchPaymentsBy(e,t){e&&(this.searchData[e]=t),await this.fetchPayments()},clearDateSeach(){this.searchDate={from:null,to:null},delete this.paymentsTable.filter["time[ge]"],delete this.paymentsTable.filter["time[le]"],this.fetchPayments()},searchByDate(){"string"==typeof this.searchDate&&(this.searchDate={from:this.searchDate,to:this.searchDate}),this.searchDate.from&&(this.paymentsTable.filter["time[ge]"]=this.searchDate.from+"T00:00:00"),this.searchDate.to&&(this.paymentsTable.filter["time[le]"]=this.searchDate.to+"T23:59:59"),this.fetchPayments()},handleFilterChanged(){const{success:e,pending:t,failed:s,incoming:i,outgoing:a}=this.statusFilters;delete this.searchData["status[ne]"],delete this.searchData["status[eq]"],e&&t&&s||(e&&t?this.searchData["status[ne]"]="failed":e&&s?this.searchData["status[ne]"]="pending":s&&t?this.searchData["status[ne]"]="success":e?this.searchData["status[eq]"]="success":t?this.searchData["status[eq]"]="pending":s&&(this.searchData["status[eq]"]="failed")),delete this.searchData["amount[ge]"],delete this.searchData["amount[le]"],i&&a||(i?this.searchData["amount[ge]"]="0":a&&(this.searchData["amount[le]"]="0")),this.fetchPayments()},showDetailsToggle(e){return this.paymentDetails=e,this.showDetails=!this.showDetails},formatCurrency(e,t){try{return LNbits.utils.formatCurrency(e,t)}catch(t){return console.error(t),`${e} ???`}},shortify:(e,t=10)=>(valueLength=(e||"").length,valueLength<=t?e:`${e.substring(0,5)}...${e.substring(valueLength-5,valueLength)}`),async updateCharts(e){let t=LNbits.utils.prepareFilterQuery(this.paymentsTable,e);try{const{data:e}=await LNbits.api.request("GET",`/api/v1/payments/stats/count?${t}&count_by=status`);e.sort((e,t)=>e.field-t.field).reverse(),this.searchOptions.status=e.map(e=>e.field),this.paymentsStatusChart.data.datasets[0].data=e.map(e=>e.total),this.paymentsStatusChart.data.labels=[...this.searchOptions.status],this.paymentsStatusChart.update()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}try{const{data:e}=await LNbits.api.request("GET",`/api/v1/payments/stats/wallets?${t}`),s=e.map(e=>e.balance/e.payments_count),i=Math.min(...s),a=Math.max(...s),n=e=>Math.floor(3+22*(e-i)/(a-i)),o=this.randomColors(20),r=e.map((e,t)=>({data:[{x:e.payments_count,y:e.balance,r:n(Math.max(e.balance/e.payments_count,5))}],label:e.wallet_name,wallet_id:e.wallet_id,backgroundColor:o[t%100],hoverOffset:4}));this.paymentsWalletsChart.data.datasets=r,this.paymentsWalletsChart.update()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}try{const{data:e}=await LNbits.api.request("GET",`/api/v1/payments/stats/count?${t}&count_by=tag`);this.searchOptions.tag=e.map(e=>e.field),this.searchOptions.status.sort(),this.paymentsTagsChart.data.datasets[0].data=e.map(e=>e.total),this.paymentsTagsChart.data.labels=e.map(e=>e.field||"core"),this.paymentsTagsChart.update()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}try{const t=Object.entries(this.searchData).reduce((e,[t,s])=>s?(e[t]=s,e):e,{}),s={...this.paymentsTable,filter:t},i=LNbits.utils.prepareFilterQuery(s,e);let{data:a}=await LNbits.api.request("GET",`/api/v1/payments/stats/daily?${i}`);const n=this.searchDate.from+"T00:00:00",o=this.searchDate.to+"T23:59:59";this.lnbitsBalance=a.length?a[a.length-1].balance:0,a=a.filter(e=>this.searchDate.from&&this.searchDate.to?e.date>=n&&e.date<=o:this.searchDate.from?e.date>=n:!this.searchDate.to||e.date<=o),this.paymentsDailyChart.data.datasets=[{label:"Balance",data:a.map(e=>e.balance),pointStyle:!1,borderWidth:2,tension:.7,fill:1},{label:"Fees",data:a.map(e=>e.fee),pointStyle:!1,borderWidth:1,tension:.4,fill:1}],this.paymentsDailyChart.data.labels=a.map(e=>e.date.substring(0,10)),this.paymentsDailyChart.update(),this.paymentsBalanceInOutChart.data.datasets=[{label:"Incoming Payments Balance",data:a.map(e=>e.balance_in)},{label:"Outgoing Payments Balance",data:a.map(e=>e.balance_out)}],this.paymentsBalanceInOutChart.data.labels=a.map(e=>e.date.substring(0,10)),this.paymentsBalanceInOutChart.update(),this.paymentsCountInOutChart.data.datasets=[{label:"Incoming Payments Count",data:a.map(e=>e.count_in)},{label:"Outgoing Payments Count",data:a.map(e=>-e.count_out)}],this.paymentsCountInOutChart.data.labels=a.map(e=>e.date.substring(0,10)),this.paymentsCountInOutChart.update()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}},async initCharts(){const e=this.$q.localStorage.getItem("lnbits.payments.chartData")||{};this.chartData={...this.chartData,...e},this.chartsReady?(this.paymentsStatusChart=new Chart(this.$refs.paymentsStatusChart.getContext("2d"),{type:"doughnut",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1}},onClick:(e,t,s)=>{if(t[0]){const e=t[0].index;this.searchPaymentsBy("status",s.data.labels[e])}}},data:{datasets:[{label:"",data:[],backgroundColor:["rgb(0, 205, 86)","rgb(64, 72, 78)","rgb(255, 99, 132)"],hoverOffset:4}]}}),this.paymentsWalletsChart=new Chart(this.$refs.paymentsWalletsChart.getContext("2d"),{type:"bubble",options:{responsive:!0,maintainAspectRatio:!1,plugins:{legend:{display:!1},title:{display:!1}},onClick:(e,t,s)=>{if(t[0]){const e=t[0].datasetIndex;this.searchPaymentsBy("wallet_id",s.data.datasets[e].wallet_id)}}},data:{datasets:[{label:"",data:[],backgroundColor:this.randomColors(20),hoverOffset:4}]}}),this.paymentsTagsChart=new Chart(this.$refs.paymentsTagsChart.getContext("2d"),{type:"pie",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1},legend:{display:!1,title:{display:!1,text:"Tags"}}},onClick:(e,t,s)=>{if(t[0]){const e=t[0].index;this.searchPaymentsBy("tag",s.data.labels[e])}}},data:{datasets:[{label:"",data:[],backgroundColor:this.randomColors(10),hoverOffset:4}]}}),this.paymentsDailyChart=new Chart(this.$refs.paymentsDailyChart.getContext("2d"),{type:"line",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1},legend:{display:!0,title:{display:!1,text:"Tags"}}}},data:{datasets:[{label:"",data:[],backgroundColor:this.randomColors(10),hoverOffset:4}]}}),this.paymentsBalanceInOutChart=new Chart(this.$refs.paymentsBalanceInOutChart.getContext("2d"),{type:"bar",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1},legend:{display:!0,title:{display:!1,text:"Tags"}}},scales:{x:{stacked:!0},y:{stacked:!0}}},data:{datasets:[{label:"",data:[],backgroundColor:this.randomColors(50),hoverOffset:4}]}}),this.paymentsCountInOutChart=new Chart(this.$refs.paymentsCountInOutChart.getContext("2d"),{type:"bar",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1},legend:{display:!0,title:{display:!1,text:""}}},scales:{x:{stacked:!0},y:{stacked:!0}}},data:{datasets:[{label:"",data:[],backgroundColor:this.randomColors(80),hoverOffset:4}]}})):console.warn("Charts are not ready yet. Initialization delayed.")},saveChartsPreferences(){this.$q.localStorage.set("lnbits.payments.chartData",this.chartData)},randomColors(e=1){const t=[];for(let s=1;s<=10;s++)for(let i=1;i<=10;i++)t.push(`rgb(${i*e*33%200}, ${71*(s+i+e)%255}, ${(s+30*e)%255})`);return t}}},window.PageNode={template:"#page-node",config:{globalProperties:{LNbits:LNbits,msg:"hello"}},data(){return{isSuperUser:!1,wallet:{},tab:"dashboard",payments:1e3,info:{},phoenixd:{capabilities:[]},phoenixdAmount:2e6,phoenixdEstimate:null,phoenixdReceive:"",phoenixdResult:"",phoenixdDialog:{show:!1,operation:"",data:{}},phoenixdBusy:!1,channel_stats:{},channels:{data:[],filter:""},activeBalance:{},ranks:{},peers:{data:[],filter:""},connectPeerDialog:{show:!1,data:{}},setFeeDialog:{show:!1,data:{fee_ppm:0,fee_base_msat:0}},openChannelDialog:{show:!1,data:{}},closeChannelDialog:{show:!1,data:{}},nodeInfoDialog:{show:!1,data:{}},transactionDetailsDialog:{show:!1,data:{}},states:[{label:"Active",value:"active",color:"green"},{label:"Pending",value:"pending",color:"orange"},{label:"Inactive",value:"inactive",color:"grey"},{label:"Closed",value:"closed",color:"red"}],stateFilters:[{label:"Active",value:"active"},{label:"Pending",value:"pending"}],paymentsTable:{data:[],columns:[{name:"pending",label:""},{name:"date",align:"left",label:this.$t("date"),field:"date",sortable:!0},{name:"sat",align:"right",label:this.$t("amount"),field:e=>this.formatMsat(e.amount),sortable:!0},{name:"fee",align:"right",label:this.$t("fee"),field:"fee"},{name:"destination",align:"right",label:"Destination",field:"destination"},{name:"memo",align:"left",label:this.$t("memo"),field:"memo"}],pagination:{rowsPerPage:10,page:1,rowsNumber:10},filter:null},invoiceTable:{data:[],columns:[{name:"pending",label:""},{name:"paid_at",field:"paid_at",align:"left",label:"Paid at",sortable:!0},{name:"expiry",label:this.$t("expiry"),field:"expiry",align:"left",sortable:!0},{name:"amount",label:this.$t("amount"),field:e=>this.formatMsat(e.amount),sortable:!0},{name:"memo",align:"left",label:this.$t("memo"),field:"memo"}],pagination:{rowsPerPage:10,page:1,rowsNumber:10},filter:null}}},created(){this.getInfo()},watch:{tab(e){"transactions"!==e||this.paymentsTable.data.length?"channels"!==e||this.channels.data.length||(this.getChannels(),this.managedChannels||this.getPeers()):(this.getPayments(),this.getInvoices())}},computed:{managedChannels(){return!0===this.info.managed_channels},canManage(){return!0===this.g.user?.super_user},checkChanges(){return!_.isEqual(this.settings,this.formData)},filteredChannels(){return this.stateFilters?this.channels.data.filter(e=>this.stateFilters.find(({value:t})=>t==e.state)):this.channels.data},totalBalance(){return this.filteredChannels.reduce((e,t)=>(e.local_msat+=t.balance.local_msat,e.remote_msat+=t.balance.remote_msat,e.total_msat+=t.balance.total_msat,e),{local_msat:0,remote_msat:0,total_msat:0})}},methods:{hasPhoenixdCapability(e){return this.phoenixd.capabilities.includes(e)},getPhoenixdStatus(){return this.nodeApi("GET","/phoenixd/status").then(e=>{this.phoenixd=e.data}).catch(()=>{})},estimatePhoenixdLiquidity(){return this.phoenixdEstimate=null,this.nodeApi("GET","/phoenixd/liquidity-fees",{query:{amount_sat:this.phoenixdAmount}}).then(e=>{this.phoenixdEstimate=e.data}).catch(()=>{})},getPhoenixdReceive(e){return this.phoenixdReceive="",this.nodeApi("GET",`/phoenixd/receive/${e}`).then(e=>{this.phoenixdReceive=e.data.value}).catch(()=>{})},showPhoenixdDialog(e,t={}){this.phoenixdDialog={show:!0,operation:e,data:{...t}},this.phoenixdResult=""},submitPhoenixd(){const{operation:e,data:t}=this.phoenixdDialog,s={close:`Close channel ${t.channel_id} and send its remaining balance to ${t.address} at ${t.fee_rate} sat/vB?`,send:`Withdraw ${t.amount_sat} sats to ${t.address} at ${t.fee_rate} sat/vB?`,bump:`Spend node funds to bump the funding transaction fee to a target of ${t.fee_rate} sat/vB?`};LNbits.utils.confirmDialog(s[e]+" This spends funds backing LNbits wallets and cannot be undone.").onOk(async()=>{this.phoenixdBusy=!0;try{const s=await this.nodeApi("POST",`/phoenixd/${e}`,{data:t});this.phoenixdResult=s.data.txid,this.phoenixdDialog.show=!1,await this.getInfo(),await this.getChannels()}catch(e){}finally{this.phoenixdBusy=!1}})},exportPhoenixdHistory(){this.nodeApi("POST","/phoenixd/export").then(e=>{Quasar.Notify.create({message:e.data.message})}).catch(()=>{})},formatMsat:e=>LNbits.utils.formatMsat(e),nodeApi(e,t,s){const i=new URLSearchParams(s?.query);return LNbits.api.request(e,`/node/api/v1${t}?${i}`,{},s?.data).catch(e=>{throw LNbits.utils.notifyApiError(e),e})},getChannel(e){return this.nodeApi("GET",`/channels/${e}`).then(e=>{this.setFeeDialog.data.fee_ppm=e.data.fee_ppm,this.setFeeDialog.data.fee_base_msat=e.data.fee_base_msat})},getChannels(){return this.nodeApi("GET","/channels").then(e=>{this.channels.data=e.data})},getInfo(){return this.nodeApi("GET","/info").then(e=>{const t=this.managedChannels;this.info=e.data,this.channel_stats=e.data.channel_stats,this.managedChannels?(this.getPhoenixdStatus(),t||(this.stateFilters=null)):this.get1MLStats()}).catch(()=>{this.info={},this.channel_stats={}})},get1MLStats(){return this.nodeApi("GET","/rank").then(e=>{this.ranks=e.data}).catch(()=>{this.ranks={}})},getPayments(e){e&&(this.paymentsTable.pagination=e.pagination);let t=this.paymentsTable.pagination;const s={limit:t.rowsPerPage,offset:(t.page-1)*t.rowsPerPage??0};return this.nodeApi("GET","/payments",{query:s}).then(e=>{this.paymentsTable.data=e.data.data,this.paymentsTable.pagination.rowsNumber=e.data.total})},getInvoices(e){e&&(this.invoiceTable.pagination=e.pagination);let t=this.invoiceTable.pagination;const s={limit:t.rowsPerPage,offset:(t.page-1)*t.rowsPerPage??0};return this.nodeApi("GET","/invoices",{query:s}).then(e=>{this.invoiceTable.data=e.data.data,this.invoiceTable.pagination.rowsNumber=e.data.total})},getPeers(){return this.nodeApi("GET","/peers").then(e=>{this.peers.data=e.data})},connectPeer(){this.nodeApi("POST","/peers",{data:this.connectPeerDialog.data}).then(()=>{this.connectPeerDialog.show=!1,this.getPeers()})},disconnectPeer(e){LNbits.utils.confirmDialog("Do you really wanna disconnect this peer?").onOk(()=>{this.nodeApi("DELETE",`/peers/${e}`).then(e=>{Quasar.Notify.create({message:"Disconnected",icon:null}),this.needsRestart=!0,this.getPeers()})})},setChannelFee(e){this.nodeApi("PUT",`/channels/${e}`,{data:this.setFeeDialog.data}).then(e=>{this.setFeeDialog.show=!1,this.getChannels()}).catch(LNbits.utils.notifyApiError)},openChannel(){this.nodeApi("POST","/channels",{data:this.openChannelDialog.data}).then(e=>{this.openChannelDialog.show=!1,this.getChannels()}).catch(e=>{console.log(e)})},showCloseChannelDialog(e){this.managedChannels?this.showPhoenixdDialog("close",{channel_id:e.id}):(this.closeChannelDialog.show=!0,this.closeChannelDialog.data={force:!1,short_id:e.short_id,...e.point})},closeChannel(){this.nodeApi("DELETE","/channels",{query:this.closeChannelDialog.data}).then(e=>{this.closeChannelDialog.show=!1,this.getChannels()})},showSetFeeDialog(e){this.setFeeDialog.show=!0,this.setFeeDialog.channel_id=e,this.getChannel(e)},showOpenChannelDialog(e){this.openChannelDialog.show=!0,this.openChannelDialog.data={peer_id:e,funding_amount:0}},showNodeInfoDialog(e){this.nodeInfoDialog.show=!0,this.nodeInfoDialog.data=e},showTransactionDetailsDialog(e){this.transactionDetailsDialog.show=!0,this.transactionDetailsDialog.data=e},shortenNodeId:e=>e?e.substring(0,5)+"..."+e.substring(e.length-5):"..."}},window.PageNodePublic={template:"#page-node-public",data:()=>({enabled:!1,isSuperUser:!1,wallet:{},tab:"dashboard",payments:1e3,info:{},channel_stats:{},channels:[],activeBalance:{},ranks:{},peers:[],connectPeerDialog:{show:!1,data:{}},openChannelDialog:{show:!1,data:{}},closeChannelDialog:{show:!1,data:{}},nodeInfoDialog:{show:!1,data:{}},states:[{label:"Active",value:"active",color:"green"},{label:"Pending",value:"pending",color:"orange"},{label:"Inactive",value:"inactive",color:"grey"},{label:"Closed",value:"closed",color:"red"}]}),created(){this.getInfo()},methods:{formatMsat:e=>LNbits.utils.formatMsat(e),api:(e,t,s)=>LNbits.api.request(e,"/node/public/api/v1"+t,{},s),getInfo(){this.api("GET","/info",{}).then(e=>{this.info=e.data,this.channel_stats=e.data.channel_stats,this.enabled=!0,this.info.managed_channels||this.get1MLStats()}).catch(()=>{this.info={},this.channel_stats={}})},get1MLStats(){this.api("GET","/rank",{}).then(e=>{this.ranks=e.data}).catch(()=>{this.ranks={}})}}},window.PageAudit={template:"#page-audit",data:()=>({chartsReady:!1,auditEntries:[],searchData:{user_id:"",ip_address:"",request_type:"",component:"",request_method:"",response_code:"",path:""},searchOptions:{component:[],request_method:[],response_code:[]},auditTable:{columns:[{name:"created_at",align:"center",label:"Date",field:"created_at",sortable:!0},{name:"duration",align:"left",label:"Duration (sec)",field:"duration",sortable:!0},{name:"component",align:"left",label:"Component",field:"component",sortable:!1},{name:"request_method",align:"left",label:"Method",field:"request_method",sortable:!1},{name:"response_code",align:"left",label:"Code",field:"response_code",sortable:!1},{name:"user_id",align:"left",label:"User Id",field:"user_id",sortable:!1},{name:"ip_address",align:"left",label:"IP Address",field:"ip_address",sortable:!1},{name:"path",align:"left",label:"Path",field:"path",sortable:!1}],pagination:{sortBy:"created_at",rowsPerPage:10,page:1,descending:!0,rowsNumber:10},search:null,hideEmpty:!0,loading:!1},auditDetailsDialog:{data:null,show:!1}}),async created(){},async mounted(){this.chartsReady=!0,await this.$nextTick(),this.initCharts(),await this.fetchAudit()},methods:{async fetchAudit(e){try{const t=LNbits.utils.prepareFilterQuery(this.auditTable,e),{data:s}=await LNbits.api.request("GET",`/audit/api/v1?${t}`);this.auditTable.pagination.rowsNumber=s.total,this.auditEntries=s.data,await this.fetchAuditStats(e)}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}finally{this.auditTable.loading=!1}},async fetchAuditStats(e){try{const t=LNbits.utils.prepareFilterQuery(this.auditTable,e),{data:s}=await LNbits.api.request("GET",`/audit/api/v1/stats?${t}`),i=s.request_method.map(e=>e.field);this.searchOptions.request_method=[...new Set(this.searchOptions.request_method.concat(i))],this.requestMethodChart.data.labels=i,this.requestMethodChart.data.datasets[0].data=s.request_method.map(e=>e.total),this.requestMethodChart.update();const a=s.response_code.map(e=>e.field);this.searchOptions.response_code=[...new Set(this.searchOptions.response_code.concat(a))],this.responseCodeChart.data.labels=a,this.responseCodeChart.data.datasets[0].data=s.response_code.map(e=>e.total),this.responseCodeChart.update();const n=s.component.map(e=>e.field);this.searchOptions.component=[...new Set(this.searchOptions.component.concat(n))],this.componentUseChart.data.labels=n,this.componentUseChart.data.datasets[0].data=s.component.map(e=>e.total),this.componentUseChart.update(),this.longDurationChart.data.labels=s.long_duration.map(e=>e.field),this.longDurationChart.data.datasets[0].data=s.long_duration.map(e=>e.total),this.longDurationChart.update()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}},async searchAuditBy(e,t){e&&(this.searchData[e]=t),this.auditTable.filter=Object.entries(this.searchData).reduce((e,[t,s])=>s?(e[t]=s,e):e,{}),await this.fetchAudit()},showDetailsDialog(e){const t=JSON.parse(e?.request_details||"");try{t.body&&(t.body=JSON.parse(t.body))}catch(e){}this.auditDetailsDialog.data=JSON.stringify(t,null,4),this.auditDetailsDialog.show=!0},shortify:e=>(valueLength=(e||"").length,valueLength<=10?e:`${e.substring(0,5)}...${e.substring(valueLength-5,valueLength)}`),async initCharts(){this.chartsReady?(this.responseCodeChart=new Chart(this.$refs.responseCodeChart.getContext("2d"),{type:"doughnut",options:{responsive:!0,plugins:{legend:{position:"bottom"},title:{display:!1,text:"HTTP Response Codes"}},onClick:(e,t,s)=>{if(t[0]){const e=t[0].index;this.searchAuditBy("response_code",s.data.labels[e])}}},data:{datasets:[{label:"",data:[20,10],backgroundColor:["rgb(100, 99, 200)","rgb(54, 162, 235)","rgb(255, 205, 86)","rgb(255, 5, 86)","rgb(25, 205, 86)","rgb(255, 205, 250)"]}],labels:[]}}),this.requestMethodChart=new Chart(this.$refs.requestMethodChart.getContext("2d"),{type:"bar",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1}},onClick:(e,t,s)=>{if(t[0]){const e=t[0].index;this.searchAuditBy("request_method",s.data.labels[e])}}},data:{datasets:[{label:"",data:[],backgroundColor:["rgb(255, 99, 132)","rgb(54, 162, 235)","rgb(255, 205, 86)","rgb(255, 5, 86)","rgb(25, 205, 86)","rgb(255, 205, 250)"],hoverOffset:4}]}}),this.componentUseChart=new Chart(this.$refs.componentUseChart.getContext("2d"),{type:"pie",options:{responsive:!0,plugins:{legend:{position:"xxx"},title:{display:!1,text:"Components"}},onClick:(e,t,s)=>{if(t[0]){const e=t[0].index;this.searchAuditBy("component",s.data.labels[e])}}},data:{datasets:[{data:[],backgroundColor:["rgb(255, 99, 132)","rgb(54, 162, 235)","rgb(255, 205, 86)","rgb(255, 5, 86)","rgb(25, 205, 86)","rgb(255, 205, 250)","rgb(100, 205, 250)","rgb(120, 205, 250)","rgb(140, 205, 250)","rgb(160, 205, 250)"],hoverOffset:4}]}}),this.longDurationChart=new Chart(this.$refs.longDurationChart.getContext("2d"),{type:"bar",options:{responsive:!0,indexAxis:"y",maintainAspectRatio:!1,plugins:{legend:{title:{display:!1,text:"Long Duration"}}},onClick:(e,t,s)=>{if(t[0]){const e=t[0].index;this.searchAuditBy("path",s.data.labels[e])}}},data:{datasets:[{label:"",data:[],backgroundColor:["rgb(255, 99, 132)","rgb(54, 162, 235)","rgb(255, 205, 86)","rgb(255, 5, 86)","rgb(25, 205, 86)","rgb(255, 205, 250)","rgb(100, 205, 250)","rgb(120, 205, 250)","rgb(140, 205, 250)","rgb(160, 205, 250)"],hoverOffset:4}]}})):console.warn("Charts are not ready yet. Initialization delayed.")}}},window.PageWallet={template:"#page-wallet",data:()=>({onchainPaymentFilter:{},parse:{show:!1,invoice:null,lnurlpay:null,lnurlauth:null,sending:!1,decoding:!1,decodeId:0,data:{request:"",amount:0,comment:"",memo:"",internalMemo:null,unit:"sat"},paymentChecker:null,copy:{show:!1},camera:{show:!1,camera:"auto"}},receive:{show:!1,status:"pending",paymentReq:null,paymentHash:null,amountMsat:null,minMax:[0,21e14],lnurl:null,units:[],unit:"sat",fiatProvider:"",data:{amount:null,memo:"",internalMemo:null,payment_hash:null}},update:{name:null,currency:null},hasNfc:!1,nfcReaderAbortController:null,formattedFiatAmount:0,totalBreakdown:{show:!1,loading:!1,rows:[],selectedTypes:["bitcoin","fiat"],selectedTags:[]},paymentFilter:{"status[ne]":"failed"},chartConfig:Quasar.LocalStorage.getItem("lnbits.wallets.chartConfig")||{showPaymentInOutChart:!0,showBalanceChart:!0,showBalanceInOutChart:!0}}),computed:{isFiatWallet(){return"fiat"===this.g.wallet.walletType},isCashPayment(){return this.isFiatWallet&&"cash"===this.receive.fiatProvider},bolt12AmountMissing(){return!(!this.parse.invoice||!this.parse.invoice.isBolt12Offer||Number(this.parse.data.amount)>0)},canPay(){return!!this.parse.invoice&&(this.parse.invoice.expired?(Quasar.Notify.create({message:"Invoice has expired",color:"negative"}),!1):this.parse.invoice.isBolt12Offer?!!this.bolt12AmountMissing||Number(this.parse.data.amount)<=this.g.wallet.sat:this.parse.invoice.sat<=this.g.wallet.sat)},lnurlpayInfo(){const e=this.parse.lnurlpay;if(!e)return{};const t={domain:e.callback.split("/")[2],fixed:e.minSendable===e.maxSendable};try{JSON.parse(e.metadata).forEach(([e,s])=>{"text/plain"===e?t.description=s:"image/png;base64"===e||"image/jpeg;base64"===e?t.image=`data:${e},${s}`:"text/identifier"!==e&&"text/email"!==e||(t.targetUser=s)})}catch{}return t},formattedAmount(){return this.isFiatWallet?LNbits.utils.formatCurrency(this.receive.data.amount,this.receive.unit):"sat"==this.receive.unit&&this.g.isSatsDenomination?LNbits.utils.formatMsat(this.receive.amountMsat)+" sat":LNbits.utils.formatCurrency(Number(this.receive.data.amount).toFixed(2),this.g.isSatsDenomination?this.receive.unit:this.g.denomination)},formattedSatAmount(){return LNbits.utils.formatMsat(this.receive.amountMsat)+" sat"},totalBreakdownTags(){const e=this.totalBreakdown.rows.map(e=>e.tag||null);return[...new Set(e)].sort((e,t)=>this.totalBreakdownTagLabel(e).localeCompare(this.totalBreakdownTagLabel(t)))},hasFiatTotalBreakdown(){return this.totalBreakdown.rows.some(e=>e.is_fiat)},selectedTotalBreakdownRows(){return this.totalBreakdown.rows.filter(e=>{const t=e.is_fiat?"fiat":"bitcoin";return this.totalBreakdown.selectedTypes.includes(t)&&this.totalBreakdown.selectedTags.includes(this.totalBreakdownTagKey(e.tag))})},selectedTotalBreakdownMsat(){return this.selectedTotalBreakdownRows.reduce((e,t)=>e+t.total,0)},selectedTotalBreakdownSat(){return Math.round(this.selectedTotalBreakdownMsat/1e3)},selectedTotalBreakdownCount(){return this.selectedTotalBreakdownRows.reduce((e,t)=>e+t.payments_count,0)},formattedTotalBreakdown(){return this.utils.formatBalance(this.selectedTotalBreakdownSat,this.g.denomination)},formattedTotalBreakdownFiat(){if(!this.g.fiatTracking)return null;const e=this.selectedTotalBreakdownSat/1e8*this.g.exchangeRate;return LNbits.utils.formatCurrency(e,this.g.wallet.currency)},primaryTotalBreakdownValue(){return this.g.isFiatPriority&&this.g.fiatTracking&&this.formattedTotalBreakdownFiat||this.formattedTotalBreakdown},secondaryTotalBreakdownValue(){return this.g.fiatTracking?this.g.isFiatPriority?this.formattedTotalBreakdown:this.formattedTotalBreakdownFiat:null}},methods:{showWalletTotalBreakdown(){this.totalBreakdown.show=!0,this.totalBreakdown.rows.length||this.fetchTotalBreakdown()},fetchTotalBreakdown(){this.totalBreakdown.loading=!0,LNbits.api.getPaymentTotalBreakdown(this.g.wallet).then(e=>{this.totalBreakdown.rows=e.data,this.totalBreakdown.selectedTypes=["bitcoin","fiat"],this.totalBreakdown.selectedTags=this.totalBreakdownTags.map(this.totalBreakdownTagKey),this.totalBreakdown.loading=!1}).catch(e=>{this.totalBreakdown.loading=!1,LNbits.utils.notifyApiError(e)})},totalBreakdownTagLabel:e=>e||"No tag",totalBreakdownTagKey:e=>e||"__untagged__",totalBreakdownTagCount(e){return this.totalBreakdown.rows.filter(t=>(t.tag||null)===e).reduce((e,t)=>e+t.payments_count,0)},totalBreakdownTagMsat(e){return this.totalBreakdown.rows.filter(t=>(t.tag||null)===e).reduce((e,t)=>e+t.total,0)},formatTotalBreakdownMsat(e){return this.utils.formatBalance(Math.round(e/1e3),this.g.denomination)},handleSendLnurl(e){this.parse.data.request=e,this.parse.show=!0,this.lnurlScan()},msatoshiFormat:e=>LNbits.utils.formatSat(e/1e3),showReceiveDialog(){this.receive.show=!0,this.receive.status="pending",this.receive.paymentReq=null,this.receive.paymentHash=null,this.receive.fiatPaymentReq=null,this.receive.fiatProvider=this.isFiatWallet?"cash":"",this.receive.data.amount=null,this.receive.data.memo=null,this.receive.data.internalMemo=null,this.receive.data.payment_hash=null,this.receive.units=[...this.isFiatWallet?[]:["sat"],...this.g.allowedCurrencies.length>0?this.g.allowedCurrencies:this.g.currencies],this.receive.unit=this.g.isFiatPriority&&this.g.wallet.currency||"sat",this.isFiatWallet&&(this.receive.unit=this.receive.units.includes(this.g.wallet.currency)?this.g.wallet.currency:this.receive.units[0]),this.receive.minMax=[0,21e14],this.receive.lnurl=null,this.receive.lnurlWithdraw=null},onReceiveDialogHide(){this.hasNfc&&this.nfcReaderAbortController?.abort()},showParseDialog(){this.parse.show=!0,this.parse.invoice=null,this.parse.lnurlpay=null,this.parse.lnurlauth=null,this.parse.copy.show=window.isSecureContext&&void 0!==navigator.clipboard?.readText,this.parse.data.request="",this.parse.data.comment="",this.parse.data.amount=0,this.parse.data.internalMemo=null,this.parse.data.memo="",this.parse.sending=!1,this.parse.data.paymentChecker=null,this.parse.camera.show=!1},closeParseDialog(){this.parse.decodeId++,this.parse.decoding=!1,setTimeout(()=>{clearInterval(this.parse.paymentChecker)},1e4)},handleBalanceUpdate(e){this.g.wallet.sat=this.g.wallet.sat+e},createInvoice(){if("loading"===this.receive.status)return;this.receive.status="loading",this.isFiatWallet||this.g.isSatsDenomination||(this.receive.data.amount=100*this.receive.data.amount);const e=this.isCashPayment;(e?LNbits.api.request("POST","/api/v1/fiat/cash",this.g.wallet.adminkey,{amount:this.receive.data.amount,unit:this.receive.unit,memo:this.receive.data.memo,internal_memo:this.receive.data.internalMemo}):LNbits.api.createInvoice(this.g.wallet,this.receive.data.amount,this.receive.data.memo,this.receive.unit,this.receive.lnurlWithdraw,this.receive.fiatProvider,this.receive.data.internalMemo,this.receive.data.payment_hash)).then(t=>{if(this.g.updatePayments=!this.g.updatePayments,this.receive.status="success",e)return this.receive.show=!1,void Quasar.Notify.create({type:"positive",message:"Cash payment validated."});if(this.receive.paymentReq=t.data.bolt11,this.receive.fiatPaymentReq=t.data.extra?.fiat_payment_request,this.receive.amountMsat=t.data.amount,this.receive.paymentHash=t.data.payment_hash,this.isFiatWallet||this.receive.lnurl||this.readNfcTag(),this.receive.lnurl&&null!==t.data.extra?.lnurl_response){!1===t.data.extra.lnurl_response&&(t.data.extra.lnurl_response="Unable to connect");const e=this.receive.lnurl.callback.split("/")[2];if("string"==typeof t.data.extra.lnurl_response)return void Quasar.Notify.create({timeout:5e3,type:"warning",message:`${e} lnurl-withdraw call failed.`,caption:t.data.extra.lnurl_response});!0===t.data.extra.lnurl_response&&Quasar.Notify.create({timeout:3e3,message:`Invoice sent to ${e}!`,spinner:!0})}}).catch(e=>{LNbits.utils.notifyApiError(e),this.receive.status="pending"})},lnurlScan(){LNbits.api.request("POST","/api/v1/lnurlscan",this.g.wallet.adminkey,{lnurl:this.parse.data.request}).then(e=>{const t=e.data;if("ERROR"!==t.status){if("payRequest"===t.tag)this.parse.lnurlpay=Object.freeze(t),this.parse.data.amount=t.minSendable/1e3,this.receive.units=["sats",...this.g.allowedCurrencies.length>0?this.g.allowedCurrencies:this.g.currencies];else if("login"===t.tag)this.parse.lnurlauth=Object.freeze(t);else if("withdrawRequest"===t.tag){this.parse.show=!1,this.receive.show=!0,this.receive.lnurlWithdraw=Object.freeze(t),this.receive.status="pending",this.receive.paymentReq=null,this.receive.paymentHash=null,this.receive.data.amount=t.maxWithdrawable/1e3,this.receive.data.memo=t.defaultDescription,this.receive.minMax=[t.minWithdrawable/1e3,t.maxWithdrawable/1e3];const e=t.callback.split("/")[2];this.receive.lnurl={domain:e,callback:t.callback,fixed:t.fixed}}}else Quasar.Notify.create({timeout:5e3,type:"warning",message:"lnurl scan failed.",caption:t.reason})}).catch(e=>{LNbits.utils.notifyApiError(e)})},decodeQR(e){this.parse.data.request=e,this.decodeRequest(),this.parse.camera.show=!1},isLnurl:e=>e.toLowerCase().startsWith("lnurl1")||e.startsWith("lnurlp://")||e.startsWith("lnurlw://")||e.startsWith("lnurlauth://")||e.match(/[\w.+-~_]+@[\w.+-~_]/),isBolt12Offer:e=>(e||"").trim().toLowerCase().startsWith("lno1"),async decodeRequest(){if(this.parse.decoding)return;this.parse.show=!0,this.parse.data.request=this.parse.data.request.trim();const e=this.parse.data.request.toLowerCase();if(e.startsWith("lightning:")?(this.parse.data.request=this.parse.data.request.slice(10),this.parse.data.request.startsWith("//")&&(this.parse.data.request=this.parse.data.request.slice(2))):e.startsWith("lnurl:")?this.parse.data.request=this.parse.data.request.slice(6):e.includes("lightning=lnurl1")&&(this.parse.data.request=this.parse.data.request.split("lightning=")[1].split("&")[0]),this.isLnurl(this.parse.data.request))return void this.lnurlScan();if(this.isBolt12Offer(this.parse.data.request)){const e=this.parse.data.request.trim().split("?")[0].split("#")[0];this.parse.data.request=e,this.parse.data.amount=0,this.parse.invoice=null,this.parse.decoding=!0;const t=++this.parse.decodeId;try{const{data:s}=await LNbits.api.request("post","/api/v1/payments/decode",null,{data:e});if(t!==this.parse.decodeId||!this.parse.show)return;const i=null==s.currency&&Number.isSafeInteger(s.amount)&&s.amount>0&&s.amount%1e3==0?s.amount/1e3:0;this.parse.data.request=s.offer,this.parse.data.amount=i,this.parse.invoice=Object.freeze({msat:null==s.currency?s.amount:null,sat:i,fsat:"offer",bolt11:s.offer,description:s.description,hash:null,isBolt12Offer:!0,expired:!1})}catch(e){t===this.parse.decodeId&&this.parse.show&&Quasar.Notify.create({type:"warning",message:e.response?.data?.message||e.message})}finally{t===this.parse.decodeId&&(this.parse.decoding=!1)}return}let t;this.parse.data.request.toLowerCase().includes("lightning")&&(this.parse.data.request=this.parse.data.request.split("lightning=")[1],this.parse.data.request.includes("&")&&(this.parse.data.request=this.parse.data.request.split("&")[0]));try{t=decode(this.parse.data.request)}catch(e){return Quasar.Notify.create({timeout:3e3,type:"warning",message:e+".",caption:"400 BAD REQUEST"}),void(this.parse.show=!1)}let s={msat:t.human_readable_part.amount,sat:t.human_readable_part.amount/1e3,fsat:LNbits.utils.formatSat(t.human_readable_part.amount/1e3),bolt11:this.parse.data.request};_.each(t.data.tags,e=>{if(_.isObject(e)&&_.has(e,"description"))if("payment_hash"===e.description)s.hash=e.value;else if("description"===e.description)s.description=e.value;else if("expiry"===e.description){const i=new Date(1e3*(t.data.time_stamp+e.value)),a=new Date(1e3*t.data.time_stamp);s.expireDate=Quasar.date.formatDate(i,"YYYY-MM-DDTHH:mm:ss.SSSZ"),s.createdDate=Quasar.date.formatDate(a,"YYYY-MM-DDTHH:mm:ss.SSSZ"),s.expireDateFrom=moment.utc(i).local().fromNow(),s.createdDateFrom=moment.utc(a).local().fromNow(),s.expired=!1}}),this.g.wallet.currency&&(s.fiatAmount=LNbits.utils.formatCurrency((s.sat/1e8*this.g.exchangeRate).toFixed(2),this.g.wallet.currency)),this.parse.invoice=Object.freeze(s)},payInvoice(){if(this.parse.sending)return;if(this.parse.invoice?.isBolt12Offer&&!(Number(this.parse.data.amount)>0))return;this.parse.sending=!0;const e=Quasar.Notify.create({timeout:0,message:this.$t("payment_processing")}),t=this.parse.invoice.isBolt12Offer?this.parse.data.amount:null;LNbits.api.payInvoice(this.g.wallet,this.parse.data.request,this.parse.data.internalMemo,t,this.parse.invoice.isBolt12Offer?this.parse.data.memo:null).then(t=>{this.parse.sending=!1,e(),this.g.updatePayments=!this.g.updatePayments,this.parse.show=!1,"success"==t.data.status&&Quasar.Notify.create({type:"positive",message:this.$t("payment_successful")}),"pending"==t.data.status&&Quasar.Notify.create({type:"info",message:this.$t("payment_pending")})}).catch(t=>{this.parse.sending=!1,e(),LNbits.utils.notifyApiError(t),this.g.updatePayments=!this.g.updatePayments})},payLnurl(){this.parse.sending||(this.parse.sending=!0,LNbits.api.request("post","/api/v1/payments/lnurl",this.g.wallet.adminkey,{res:this.parse.lnurlpay,lnurl:this.parse.data.request,unit:this.parse.data.unit,amount:1e3*this.parse.data.amount,comment:this.parse.data.comment,internalMemo:this.parse.data.internalMemo}).then(e=>{if(this.parse.sending=!1,this.parse.show=!1,e.data.extra.success_action){const t=JSON.parse(e.data.extra.success_action);switch(t.tag){case"url":Quasar.Notify.create({message:t.url,caption:t.description,html:!1,type:"positive",timeout:0,closeBtn:!0,actions:[{label:"Open link",color:"white",handler:()=>this.utils.openUrlInNewTab(t.url)}]});break;case"message":Quasar.Notify.create({message:t.message,type:"positive",timeout:0,closeBtn:!0});break;case"aes":this.utils.decryptLnurlPayAES(t,e.data.preimage).then(e=>{Quasar.Notify.create({message:e,caption:t.description,html:!1,type:"positive",timeout:0,closeBtn:!0})}).catch(e=>{Quasar.Notify.create({message:t.description||"Payment successful.",caption:"Could not decrypt success action.",html:!1,type:"warning",timeout:0,closeBtn:!0})})}}}).catch(e=>{this.parse.sending=!1,LNbits.utils.notifyApiError(e)}))},authLnurl(){const e=Quasar.Notify.create({timeout:10,message:"Performing authentication..."});LNbits.api.request("post","/api/v1/lnurlauth",wallet.adminkey,this.parse.lnurlauth).then(t=>{e(),Quasar.Notify.create({message:"Authentication successful.",type:"positive",timeout:3500}),this.parse.show=!1}).catch(e=>{e.response.data.reason?Quasar.Notify.create({message:`Authentication failed. ${this.parse.lnurlauth.callback} says:`,caption:e.response.data.reason,type:"warning",timeout:5e3}):LNbits.utils.notifyApiError(e)})},updateWallet(e){LNbits.api.request("PATCH","/api/v1/wallet",this.g.wallet.adminkey,e).then(e=>{const t={...e.data};t.lightning_address&&(t.lightningAddress=t.lightning_address,t.lightningAddressFull=`${t.lightning_address}@${window.location.host}`),this.g.wallet={...this.g.wallet,...t};const s=this.g.user.wallets.findIndex(t=>t.id===e.data.id);-1!==s&&(this.g.user.wallets[s]={...this.g.user.wallets[s],...t}),Quasar.Notify.create({message:"Wallet updated.",type:"positive",timeout:3500})}).catch(e=>{LNbits.utils.notifyApiError(e)})},pasteToTextArea(){this.$refs.textArea.focus(),navigator.clipboard.readText().then(e=>{this.parse.data.request=e.trim()})},readNfcTag(){try{if("undefined"==typeof NDEFReader)return void console.debug("NFC not supported on this device or browser.");const e=new NDEFReader;this.nfcReaderAbortController=new AbortController,this.nfcReaderAbortController.signal.onabort=e=>{console.debug("All NFC Read operations have been aborted.")},this.hasNfc=!0;const t=Quasar.Notify.create({message:"Tap your NFC tag to pay this invoice with LNURLw."});return e.scan({signal:this.nfcReaderAbortController.signal}).then(()=>{e.onreadingerror=()=>{Quasar.Notify.create({type:"negative",message:"There was an error reading this NFC tag."})},e.onreading=({message:e})=>{const s=new TextDecoder("utf-8"),i=e.records.find(e=>-1!==s.decode(e.data).toUpperCase().indexOf("LNURLW"));if(i){t(),Quasar.Notify.create({type:"positive",message:"NFC tag read successfully."});const e=s.decode(i.data);this.payInvoiceWithNfc(e)}else Quasar.Notify.create({type:"warning",message:"NFC tag does not have LNURLw record."})}})}catch(e){Quasar.Notify.create({type:"negative",message:e?e.toString():"An unexpected error has occurred."})}},payInvoiceWithNfc(e){const t=Quasar.Notify.create({timeout:0,spinner:!0,message:this.$t("payment_processing")});LNbits.api.request("POST",`/api/v1/payments/${this.receive.paymentReq}/pay-with-nfc`,this.g.wallet.adminkey,{lnurl_w:e}).then(e=>{t(),e.data.success?Quasar.Notify.create({type:"positive",message:"Payment successful"}):Quasar.Notify.create({type:"negative",message:e.data.detail||"Payment failed"})}).catch(e=>{t(),LNbits.utils.notifyApiError(e)})}},created(){const e=new URLSearchParams(window.location.search),t=this.g.user.wallets.find(e=>e.id===this.$route.params.id);t?(this.g.wallet=t,this.g.lastActiveWallet=t.id,this.$q.localStorage.setItem("lnbits.lastActiveWallet",t.id),this.$router.replace(`/wallet/${t.id}`).then(()=>{"onchain"!==t.walletType&&(e.has("lightning")||e.has("lnurl"))&&(this.parse.data.request=e.get("lightning")||e.get("lnurl"),this.decodeRequest(),this.parse.show=!0)})):(this.g.errorCode=404,this.g.errorMessage="Wallet not found.",this.$router.push("/error"))},watch:{"g.updatePaymentsHash"(){this.receive.show=!1},"g.updatePayments"(){this.parse.show=!1,this.g.wallet.currency&&this.$q.localStorage.getItem("lnbits.exchangeRate."+this.g.wallet.currency)&&(this.g.exchangeRate=this.$q.localStorage.getItem("lnbits.exchangeRate."+this.g.wallet.currency),this.g.fiatBalance=this.g.exchangeRate/1e8*this.g.wallet.sat)},"g.wallet"(){this.g.wallet.currency?(this.g.fiatTracking=!0,this.g.fiatBalance=this.g.exchangeRate/1e8*this.g.wallet.sat):(this.g.fiatBalance=0,this.g.fiatTracking=!1)},"g.isFiatPriority"(){this.receive.unit=this.g.isFiatPriority?this.g.wallet.currency:"sat"},"g.fiatBalance"(){this.formattedFiatAmount=LNbits.utils.formatCurrency(this.g.fiatBalance.toFixed(2),this.g.wallet.currency)},"g.exchangeRate"(){this.g.fiatTracking&&this.g.wallet.currency&&(this.g.fiatBalance=this.g.exchangeRate/1e8*this.g.wallet.sat)}}},window.PageWallets={template:"#page-wallets",data:()=>({user:null,tab:"wallets",wallets:[],addWalletDialog:{show:!1},walletsTable:{columns:[{name:"name",align:"left",label:"Name",field:"name",sortable:!0},{name:"currency",align:"center",label:"Currency",field:"currency",sortable:!0},{name:"updated_at",align:"right",label:"Last Updated",field:"updated_at",sortable:!0}],pagination:{sortBy:"updated_at",rowsPerPage:12,page:1,descending:!0,rowsNumber:10},search:"",hideEmpty:!0,loading:!1}}),watch:{"walletsTable.search":{handler(){const e={};this.walletsTable.search&&(e.search=this.walletsTable.search),this.getUserWallets()}}},methods:{async getUserWallets(e){try{this.walletsTable.loading=!0;const t=LNbits.utils.prepareFilterQuery(this.walletsTable,e),{data:s}=await LNbits.api.request("GET",`/api/v1/wallet/paginated?${t}`,null);this.wallets=s.data,this.walletsTable.pagination.rowsNumber=s.total}catch(e){LNbits.utils.notifyApiError(e)}finally{this.walletsTable.loading=!1}},goToWallet(e){this.$router.push({path:"/wallet",query:{wal:e}})},formattedFiatAmount:(e,t)=>LNbits.utils.formatCurrency(Number(e).toFixed(2),t),formattedSatAmount:e=>LNbits.utils.formatMsat(e)+" sat"},async created(){await this.getUserWallets()}},window.PageUsers={template:"#page-users",data(){return{paymentsWallet:{},cancel:{},users:[],wallets:[],searchData:{user:"",username:"",email:"",pubkey:""},paymentPage:{show:!1},activeWallet:{userId:null,show:!1},activeUser:{data:null,showUserId:!1,show:!1},createWalletDialog:{data:{},show:!1},lightningAddressDialog:{wallet:null,lightningAddress:"",show:!1},walletTable:{columns:[{name:"name",align:"left",label:"Name",field:"name"},{name:"id",align:"left",label:"Wallet Id",field:"id"},{name:"currency",align:"left",label:"Currency",field:"currency"},{name:"balance_msat",align:"left",label:"Balance",field:"balance_msat"}],pagination:{sortBy:"name",rowsPerPage:10,page:1,descending:!0,rowsNumber:10},search:null,hideEmpty:!0,loading:!1},usersTable:{columns:[{name:"activated",align:"left",label:this.$t("activated"),field:"activated",sortable:!1},{name:"wallet_id",align:"left",label:"Wallets",field:"wallet_id",sortable:!1},{name:"id",align:"left",label:"User Id",field:"id",sortable:!1},{name:"username",align:"left",label:"Username",field:"username",sortable:!1},{name:"email",align:"left",label:"Email",field:"email",sortable:!1},{name:"pubkey",align:"left",label:"Public Key",field:"pubkey",sortable:!1},{name:"balance_msat",align:"left",label:"Balance",field:"balance_msat",sortable:!1},{name:"transaction_count",align:"left",label:"Payments",field:"transaction_count",sortable:!1},{name:"last_payment",align:"left",label:"Last Payment",field:"last_payment",sortable:!1}],pagination:{sortBy:"created_at",rowsPerPage:10,page:1,descending:!0,rowsNumber:10},sortFields:[{name:"id",label:"User ID"},{name:"username",label:"Username"},{name:"email",label:"Email"},{name:"pubkey",label:"Public Key"},{name:"created_at",label:"Creation Date"},{name:"updated_at",label:"Last Updated"}],search:null,hideEmpty:!0,loading:!1}}},watch:{"usersTable.hideEmpty":function(e,t){this.usersTable.filter=e?{"transaction_count[gt]":0}:{},this.fetchUsers()}},created(){this.fetchUsers()},computed:{lightningAddressSuffix:()=>`@${window.location.host}`},methods:{formatSat:e=>LNbits.utils.formatSat(Math.floor(e/1e3)),backToUsersPage(){this.activeUser.show=!1,this.paymentPage.show=!1,this.activeWallet.show=!1,this.fetchUsers()},handleBalanceUpdate(){this.fetchWallets(this.activeWallet.userId)},resetPassword(e){return LNbits.api.request("PUT",`/users/api/v1/user/${e}/reset_password`).then(e=>{LNbits.utils.confirmDialog(this.$t("reset_key_generated")+" "+this.$t("reset_key_copy")).onOk(()=>{const t=window.location.origin+"?reset_key="+e.data;this.utils.copyText(t)})}).catch(LNbits.utils.notifyApiError)},sortByColumn(e){this.usersTable.pagination.sortBy===e?this.usersTable.pagination.descending=!this.usersTable.pagination.descending:(this.usersTable.pagination.sortBy=e,this.usersTable.pagination.descending=!1),this.fetchUsers()},createUser(){LNbits.api.request("POST","/users/api/v1/user",null,this.activeUser.data).then(e=>{Quasar.Notify.create({type:"positive",message:"User created!",icon:null}),this.activeUser.setPassword=!0,this.activeUser.data=e.data,this.fetchUsers()}).catch(LNbits.utils.notifyApiError)},updateUser(){LNbits.api.request("PUT",`/users/api/v1/user/${this.activeUser.data.id}`,null,this.activeUser.data).then(()=>{Quasar.Notify.create({type:"positive",message:"User updated!",icon:null}),this.activeUser.data=null,this.activeUser.show=!1,this.fetchUsers()}).catch(LNbits.utils.notifyApiError)},createWallet(){const e=this.activeWallet.userId;e?LNbits.api.request("POST",`/users/api/v1/user/${e}/wallet`,null,this.createWalletDialog.data).then(()=>{this.fetchWallets(e),Quasar.Notify.create({type:"positive",message:"Wallet created!"})}).catch(LNbits.utils.notifyApiError):Quasar.Notify.create({type:"warning",message:"No user selected!",icon:null})},deleteUser(e){LNbits.utils.confirmDialog("Are you sure you want to delete this user?").onOk(()=>{LNbits.api.request("DELETE",`/users/api/v1/user/${e}`).then(()=>{this.fetchUsers(),Quasar.Notify.create({type:"positive",message:"User deleted!",icon:null}),this.activeUser.data=null,this.activeUser.show=!1}).catch(LNbits.utils.notifyApiError)})},undeleteUserWallet(e,t){LNbits.api.request("PUT",`/users/api/v1/user/${e}/wallet/${t}/undelete`).then(()=>{this.fetchWallets(e),Quasar.Notify.create({type:"positive",message:"Undeleted user wallet!",icon:null})}).catch(LNbits.utils.notifyApiError)},deleteUserWallet(e,t,s){const i=s?"Wallet is already deleted, are you sure you want to permanently delete this user wallet?":"Are you sure you want to delete this user wallet?";LNbits.utils.confirmDialog(i).onOk(()=>{LNbits.api.request("DELETE",`/users/api/v1/user/${e}/wallet/${t}`).then(()=>{this.fetchWallets(e),Quasar.Notify.create({type:"positive",message:"User wallet deleted!",icon:null})}).catch(LNbits.utils.notifyApiError)})},deleteAllUserWallets(e){LNbits.utils.confirmDialog(this.$t("confirm_delete_all_wallets")).onOk(()=>{LNbits.api.request("DELETE",`/users/api/v1/user/${e}/wallets`).then(t=>{Quasar.Notify.create({type:"positive",message:t.data.message,icon:null}),this.fetchWallets(e)}).catch(LNbits.utils.notifyApiError)})},copyWalletLink(e){const t=`${window.location.origin}/wallet?usr=${this.activeWallet.userId}&wal=${e}`;this.utils.copyText(t)},showLightningAddressDialog(e){this.lightningAddressDialog.wallet=e,this.lightningAddressDialog.lightningAddress=e.lightning_address||"",this.lightningAddressDialog.show=!0},saveLightningAddress(){const e=this.lightningAddressDialog.wallet;e&&LNbits.api.request("PUT",`/users/api/v1/user/${e.user}/wallet/${e.id}/lightning-address`,null,{lightning_address:this.lightningAddressDialog.lightningAddress}).then(t=>{Object.assign(e,t.data),this.lightningAddressDialog.show=!1,Quasar.Notify.create({type:"positive",message:this.$t("lightning_address_updated"),icon:null})}).catch(LNbits.utils.notifyApiError)},fetchUsers(e){this.relaxFilterForFields(["username","email"]);const t=LNbits.utils.prepareFilterQuery(this.usersTable,e);LNbits.api.request("GET",`/users/api/v1/user?${t}`).then(e=>{this.usersTable.loading=!1,this.usersTable.pagination.rowsNumber=e.data.total,this.users=e.data.data}).catch(LNbits.utils.notifyApiError)},fetchWallets(e){return LNbits.api.request("GET",`/users/api/v1/user/${e}/wallet`).then(t=>{this.wallets=t.data,this.activeWallet.userId=e,this.activeWallet.show=!0}).catch(LNbits.utils.notifyApiError)},relaxFilterForFields(e=[]){e.forEach(e=>{const t=this.usersTable?.filter?.[e];t&&this.usersTable.filter[e]&&(this.usersTable.filter[`${e}[like]`]=t,delete this.usersTable.filter[e])})},updateWallet(e){LNbits.api.request("PATCH","/api/v1/wallet",e.adminkey,{name:e.name}).then(()=>{e.editable=!1,Quasar.Notify.create({message:"Wallet name updated.",type:"positive",timeout:3500})}).catch(e=>{LNbits.utils.notifyApiError(e)})},toggleAdmin(e){LNbits.api.request("PUT",`/users/api/v1/user/${e}/admin`).then(()=>{this.fetchUsers(),Quasar.Notify.create({type:"positive",message:"Toggled admin!",icon:null})}).catch(LNbits.utils.notifyApiError)},toggleUserActivated(e){LNbits.api.request("PUT",`/users/api/v1/user/${e}/activate`).then(e=>{this.fetchUsers(),Quasar.Notify.create({type:"positive",message:e.data.message,icon:null})}).catch(LNbits.utils.notifyApiError)},async showAccountPage(e){if(this.activeUser.showPassword=!1,this.activeUser.showUserId=!1,this.activeUser.setPassword=!1,!e)return this.activeUser.data={extra:{}},void(this.activeUser.show=!0);try{const{data:t}=await LNbits.api.request("GET",`/users/api/v1/user/${e}`);this.activeUser.data=t,this.activeUser.show=!0}catch(e){console.warn(e),Quasar.Notify.create({type:"warning",message:"Failed to get user!"}),this.activeUser.show=!1}},async impersonateUser(e){try{await LNbits.api.impersonateUser(e),LNbits.utils.backupLocalStorage("impersonation",!0),this.$q.localStorage.setItem("lnbits.disclaimerShown",!0),window.location="/wallet"}catch(e){console.warn(e),Quasar.Notify.create({type:"warning",message:"Failed to impersonate user!"})}},async showWalletPayments(e){this.activeUser.show=!1,await this.fetchWallets(this.users[0].id),await this.showPayments(e)},showPayments(e){this.paymentsWallet=this.wallets.find(t=>t.id===e),this.paymentPage.show=!0},searchUserBy(e){const t=this.searchData[e];this.usersTable.filter={},t&&(this.usersTable.filter[e]=t),this.fetchUsers()},shortify:e=>(valueLength=(e||"").length,valueLength<=10?e:`${e.substring(0,5)}...${e.substring(valueLength-5,valueLength)}`)}},window.PageAccount={template:"#page-account",data(){return{untouchedUser:null,hasUsername:!1,showUserId:!1,themeOptions:[{name:"bitcoin",color:"deep-orange"},{name:"classic",color:"purple"},{name:"mint",color:"green"},{name:"autumn",color:"brown"},{name:"monochrome",color:"grey"},{name:"salvador",color:"blue-10"},{name:"freedom",color:"pink-13"},{name:"cyber",color:"light-green-9"},{name:"flamingo",color:"pink-3"}],defaultSiteCustomisation:{locale:"en"},reactionOptions:["None","confettiBothSides","confettiFireworks","confettiStars","confettiTop","lightningStrike"],borderOptions:["retro-border","hard-border","neon-border","no-border"],tab:"user",credentialsData:{show:!1,oldPassword:null,newPassword:null,newPasswordRepeat:null,username:null,pubkey:null},apiAcl:{showNewAclDialog:!1,showPasswordDialog:!1,showNewTokenDialog:!1,data:[],passwordGuardedFunction:null,newAclName:"",newTokenName:"",password:"",apiToken:null,selectedTokenId:null,columns:[{name:"Name",align:"left",label:this.$t("Name"),field:"Name",sortable:!1},{name:"path",align:"left",label:this.$t("path"),field:"path",sortable:!1},{name:"read",align:"left",label:this.$t("read"),field:"read",sortable:!1},{name:"write",align:"left",label:this.$t("write"),field:"write",sortable:!1}],pagination:{rowsPerPage:100,page:1}},selectedApiAcl:{id:null,name:null,endpoints:[],token_id_list:[],allRead:!1,allWrite:!1},assets:[],assetsTable:{loading:!1,columns:[{name:"name",align:"left",label:this.$t("Name"),field:"name",sortable:!0},{name:"created_at",align:"left",label:this.$t("created_at"),field:"created_at",sortable:!0}],pagination:{rowsPerPage:6,page:1}},assetsUploadToPublic:!1,notifications:{nostr:{identifier:""}},labels:[],labelsDialog:{show:!1,data:{name:"",description:"",color:"#000000"}},labelsTable:{loading:!1,columns:[{name:"actions",align:"left"},{name:"name",align:"left",label:this.$t("Name"),field:"name",sortable:!0},{name:"description",align:"left",label:this.$t("description"),field:"description"},{name:"color",align:"left",label:this.$t("color"),field:"color"}],pagination:{rowsPerPage:6,page:1}}}},watch:{tab(e){this.$router.push(`/account#${e}`)},$route(e){e.hash.length>1&&(this.tab=e.hash.replace("#",""))},"assetsTable.search":{handler(){const e={};this.assetsTable.search&&(e.search=this.assetsTable.search),this.getUserAssets()}}},computed:{accountNavigationItems(){return[{value:"user",label:this.$t("account_settings"),description:this.$t("account_settings_description"),icon:"person"},{value:"notifications",label:this.$t("notifications"),description:this.$t("account_notifications_description"),icon:"notifications"},{value:"theme",label:this.$t("look_and_feel"),description:this.$t("look_and_feel_description"),icon:"palette"},{value:"two_factor",label:this.$t("two_factor_auth_account"),description:this.$t("two_factor_description"),icon:"verified_user"},{value:"api_acls",label:this.$t("access_control_list"),description:this.$t("access_control_list_description"),icon:"lock"},{value:"assets",label:this.$t("assets"),description:this.$t("account_assets_description"),icon:"perm_media"},{value:"labels",label:this.$t("labels"),description:this.$t("account_labels_description"),icon:"local_offer"}]},activeAccountSection(){return this.accountNavigationItems.find(e=>e.value===this.tab)||this.accountNavigationItems[0]},isUserTouched(){return!_.isEqual(this.g.user,this.untouchedUser)},selectedApiToken(){return this.selectedApiAcl.token_id_list.find(e=>e.id===this.apiAcl.selectedTokenId)},expiryAt(){return this.selectedApiToken.expires_at?`${this.$t("expiry")}: ${LNbits.utils.formatTimestamp(this.selectedApiToken.expires_at)}`:""},tokenStatus(){if(this.selectedApiToken.expires_at){const e=new Date;let t="",s="positive";return new Date(1e3*this.selectedApiToken.expires_at)<e?(t=this.$t("acl_token_expired"),s="negative"):t=this.$t("acl_token_active"),{status:t,badgeColor:s}}return""}},methods:{changeLanguage(e){window.i18n.global.locale=e,this.$q.localStorage.set("lnbits.lang",e)},async updateAccount(){try{const{data:e}=await LNbits.api.request("PATCH","/api/v1/auth",null,{user_id:this.g.user.id,username:this.g.user.username,email:this.g.user.email,extra:this.g.user.extra});this.untouchedUser=JSON.parse(JSON.stringify(this.g.user)),this.hasUsername=!!e.username,Quasar.Notify.create({type:"positive",message:"Account updated."})}catch(e){LNbits.utils.notifyApiError(e)}},disableUpdatePassword(){return!this.credentialsData.newPassword||!this.credentialsData.newPasswordRepeat||this.credentialsData.newPassword!==this.credentialsData.newPasswordRepeat},async updatePassword(){if(this.credentialsData.username)try{const{data:e}=await LNbits.api.request("PUT","/api/v1/auth/password",null,{user_id:this.g.user.id,username:this.credentialsData.username,password_old:this.credentialsData.oldPassword,password:this.credentialsData.newPassword,password_repeat:this.credentialsData.newPasswordRepeat});this.untouchedUser=JSON.parse(JSON.stringify(e)),this.hasUsername=!!e.username,this.credentialsData.show=!1,Quasar.Notify.create({type:"positive",message:"Password updated."})}catch(e){LNbits.utils.notifyApiError(e)}else Quasar.Notify.create({type:"warning",message:"Please set a username."})},async updatePubkey(){try{const{data:e}=await LNbits.api.request("PUT","/api/v1/auth/pubkey",null,{user_id:this.g.user.id,pubkey:this.credentialsData.pubkey});this.untouchedUser=JSON.parse(JSON.stringify(e)),this.hasUsername=!!e.username,this.credentialsData.show=!1,this.$q.notify({type:"positive",message:"Public key updated."})}catch(e){LNbits.utils.notifyApiError(e)}},showUpdateCredentials(){this.credentialsData={show:!0,oldPassword:null,username:this.g.user.username,pubkey:this.g.user.pubkey,newPassword:null,newPasswordRepeat:null}},selectAccountSection(e){this.tab=e,"user"===e&&(this.credentialsData.show=!1)},newApiAclDialog(){this.apiAcl.newAclName=null,this.apiAcl.showNewAclDialog=!0},newTokenAclDialog(){this.apiAcl.newTokenName=null,this.apiAcl.newTokenExpiry=null,this.apiAcl.showNewTokenDialog=!0},handleApiACLSelected(e){this.selectedApiAcl={id:null,name:null,endpoints:[],token_id_list:[]},this.apiAcl.selectedTokenId=null,e&&setTimeout(()=>{const t=this.apiAcl.data.find(t=>t.id===e);this.selectedApiAcl&&(this.selectedApiAcl={...t},this.selectedApiAcl.allRead=this.selectedApiAcl.endpoints.every(e=>e.read),this.selectedApiAcl.allWrite=this.selectedApiAcl.endpoints.every(e=>e.write))})},handleAllEndpointsReadAccess(){this.selectedApiAcl.endpoints.forEach(e=>e.read=this.selectedApiAcl.allRead)},handleAllEndpointsWriteAccess(){this.selectedApiAcl.endpoints.forEach(e=>e.write=this.selectedApiAcl.allWrite)},async getApiACLs(){try{const{data:e}=await LNbits.api.request("GET","/api/v1/auth/acl",null);this.apiAcl.data=e.access_control_list}catch(e){LNbits.utils.notifyApiError(e)}},askPasswordAndRunFunction(e){this.apiAcl.passwordGuardedFunction=e,this.apiAcl.showPasswordDialog=!0},runPasswordGuardedFunction(){this.apiAcWhy this scored 39/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.