* Basic CSP with unsafe-inline, unsafe-eval
* Allow 'self' for img-src and connect-src
Apparently, there is a bug for Chrome on iOS if connect-src does not allow 'self'.
See known issues at https://caniuse.com/contentsecuritypolicy
* Use nonces for strict CSP
* More CSP comments
* Add frame-ancestors directive
* Add more useful headers
* Add HSTS header
* Allow youtube and twitter embeds
For some reason, www.youtube.com is enough. It also works for youtube.com and youtube-nocookie.com.
For twitter embeds from twitter.com or x.com, platform.twitter.com is enough.
* Allow CDN and media domain in CSP
* Only allow unsafe-eval in dev build
* Ignore _next/webpack-hmr in middleware
* add nsfw column to sub
* add nsfw boolean to territorySchema
* save nsfw value in upsertSub mutation
* return nsfw value from Sub query for correct value in edit territory form
* add nsfw checkbox to territory form
* add nsfw badge to territory header
* add nsfwMode to user
* show nsfw badge next to item territory
* exclude nsfw sub from items query
* show nsfw mode checkbox on settings page
* fix nsfw badge formatting
* separate user from current, signed in user
* update relationClause to join with sub table
* refactor to simplify hide nsfw sql
* filter nsfw items when viewing user items
* hide nsfw posts for logged out users
* filter nsfw subs based on user preference
* show nsfw sub name if logged out user is viewing the page
* show current sub at the top of the list instead of bottom
* always join item with sub to check nsfw
* check for sub presence before showing nsfw badge on item
* skip manually adding sub to select if sub is null
* fix relationClause to join with root item
* move moderation and nsfw into accordion
---------
Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
* Refactor setting of default providers
* fixed warning about component update while rendering another component
* individual providers no longer need to know if they are the default or not
* default setting is now handled by WebLNContext -- the same context that returns the provider. this makes a lot more sense and is a lot easier to read
* default payment checkbox is now also disabled if there is only one enabled provider or if it is the default provider
* Fix order lost on page reload
On page reload, the providers were synced in the order they were loaded.
This means that the default payment provider setting was lost.
Fixed this by syncing order to local storage and on page reload, only syncing providers when they were initialized (else the order would have been lost again).
* Add LNbits card
* Save LNbits Provider in WebLN context
* Check LNbits connection on save
* refactor: put LNbitsProvider into own file
* Pay invoices using WebLN provider from context
* Remove deprecated FIXME
* Try WebLN provider first
* Fix unhandled promise rejection
* Fix this in sendPayment
* Be optimistic regarding WebLN zaps
This wraps the WebLN payment promise with Apollo cache updates.
We will be optimistics and assume that the payment will succeed and update the cache accordingly.
When we notice that the payment failed, we undo this update.
* Bold strike on WebLN zap
If lightning strike animation is disabled, toaster will be used.
* Rename undo variable to amount
* Fix zap undo
* Add NWC card
* Attempt to check NWC connection using info event
* Fix NaN on zap
Third argument of update is reserved for context
* Fix TypeError in catch of QR code
* Add basic NWC payments
* Wrap LNbits getInfo with try/catch
* EOSE is enough to check NWC connection
* refactor: Wrap WebLN providers into own context
I should have done this earlier
* Show red indicator on error
* Fix useEffect return value
* Fix wrong usage of pubkey
The event pubkey is derived from the secret. Doesn't make sense to manually set it. It's also the wrong pubkey: we're not the wallet service.
* Use p tag in NWC request
* Add comment about required filter field
* Aesthetic changes to NWC sendPayment
* Add TODO about receipt verification
* Fix WebLN attempted again after error
* Fix undefined name
* Add code to mock NWC relay
* Revert "Bold strike on WebLN zap"
This reverts commit a9eb27daec0cd2ef30b56294b05e0056fb5b4184.
* Fix update undo
* Fix lightning strike before payment
* WIP: Wrap WebLN payments with toasts
* add toasts for pending, error, success
* while pending, invoice can be canceled
* there are still some race conditions between payiny the invoice / error on payment and invoice cancellation
* Fix invoice poll using stale value from cache
* Remove unnecessary if
* Make sure that pay_invoice is declared as supported
* Check if WebLN provider is enabled before calling sendPayment
* Fix bad retry
If WebLN payments failed due to insufficient balances, the promise resolved and thus the action was retried but failed immediately since the invoice (still) wasn't paid.
* Fix cache undo update
* Fix no cache update after QR payment
* refactor: Use fragments to undo cache updates
* Remove console.log
* Small changes to NWC relay mocking
* Return SendPaymentResponse
See https://www.webln.guide/building-lightning-apps/webln-reference/webln.sendpayment
* Also undo cache update on retry failure
* Disable NWC mocking
* Fix initialValue not set
But following warning is now shown in console:
"""
Warning: A component is changing a controlled input to be uncontrolled.
This is likely caused by the value changing from a defined to undefined, which should not happen.
Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components
"""
* Remove comment since only relevant for blastr (mutiny relay)
* Remove TODO
* Fix duplicate cache update
* Fix QR modal not closed after payment
* Ignore lnbits variable unused
* Use single relay connection for all NWC events
* Fix missing timer and subscription cleanup
* Remove TODO
Confirmed that nostr-tools verifies events and filters for us.
See https://github.com/nbd-wtf/nostr-tools/blob/master/abstract-relay.ts#L161
* Fix switch from controlled to uncontrolled input
* Show 'configure' on error
* Use budgetable instead of async
* Remove EOSE listener
Only nostr.mutinywallet.com didn't respond with info events due to implementation-specific reasons. This is no longer the case.
* Use invoice expiry for NWC timeout
I don't think there was a specific reason why I used 60 seconds initially.
* Validate LNbits config on save
* Validate NWC config on save
* Also show unattach if configuration is invalid
If unattach is only shown if configuration is valid, resetting the configuration is not possible while it's invalid. So we're stuck with a red wallet indicator.
* Fix detection of WebLN payment
It depended on a Apollo cache update function being available. But that is not the case for every WebLN payment.
* Fix formik bag lost
* Use payment instead of zap in toast
* autoscale capture svc by response time
* docs and changes for testing lnbits locally
* Rename configJSON to config
Naming of config object was inconsistent with saveConfig function which was annoying.
Also fixed other inconsistencies between LNbits and NWC provider.
* Allow setting of default payment provider
* Update TODO comment about provider priority
The list 'paymentMethods' is not used yet but is already implemented for future iterations.
* Add wallet security disclaimer
* Update labels
---------
Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
Co-authored-by: keyan <keyan.kousha+huumn@gmail.com>
* Show territory details in post form
* Style territory details in post form
* Keep details closed by default
* Use SUB_FULL
* Undo unused changes to specify accordian default
---------
Co-authored-by: ekzyis <ek@stacker.news>
* Use parallel invoice subscriptions
* Fix missing idempotency
* Log error
* Use cursor for invoice subscription
* Subscribe to outgoing payments for withdrawals
* Add TODO comments regarding migration to LND subscriptions
* Also use isPoll variable in checkInvoice
* Queue status check of pending withdrawals
* Use for loop to check pending withdrawals
* Reconnect to LND gRPC API on error
* Fix hash modified of applied migrations
* Separate wallet code from worker index
* refactor subscription code some more
* remove unnecessary subWrapper abstraction
* move all wallet related code into worker/wallet.js such that only a single import is needed in worker/index.js
* Migrate from polling to LND subscriptions
* Remove unnecessary reconnect code
* Add FIXME
* Add listener for HODL invoice updates
* Remove obsolete comment
* Update README
* Add job to cancel hodl invoice if expired
* Fix missing else
* small bug fixes and readability enhancements
* refine and add periodic redundant deposit/withdrawal checks
---------
Co-authored-by: ekzyis <ek@stacker.news>
Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
Co-authored-by: keyan <keyan.kousha+huumn@gmail.com>
Code works but it prints a warning in the console:
> Warning: Invalid DOM property `autocomplete`. Did you mean `autoComplete`?
Co-authored-by: ekzyis <ek@stacker.news>
* Christmas zaps
* Also add 50px margin on left side
* Remove wrong comment
* Use grey snow in light mode
---------
Co-authored-by: ekzyis <ek@stacker.news>
* * add error boundary immediately above page component
* send error logs to server via LoggerContext
* display error stack and component stack in copyable text area
* wrap every context provider in an error boundary
* memoize context values to fix error boundary propagation issue
* Wrap page component in an error boundary so we can use our context utilities
for a better experience, like toast and logger
Still have a top-level error boundary that catches things from the context providers,
just in case.
Don't display the whole error stack, just because it's ugly, but make it copyable
* First pass of implementing Badging API for notifications
* Only show app badge when driven from push notifications
* Display number of unread push notifications instead of just an empty badge
Clear badge via postMessage when notifications page is loaded
* de-dupe some code, update badge counter on each notification click
* remove ids, track open note count instead
* restore optional chaining
* ensure note count doesn't go below 0, and fix event.waitUntil error when clearing badge
* incorporate PR feedback
* add custom range option to top items page
* add custom range option to profile page
* add date filter option to chart pages
* cleanup
* fix x-axis date labels
* date picker improvements
* enhancements to custom date selection
* remove unneeded condition
---------
Co-authored-by: rleed <rleed1@pm.me>
Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
* Show when wallet history facts occurred
make use of the `timeSince` function that we use in item components
to show a relative time that a wallet history event occurred.
you an also hover over the relative time to see the ISO timestamp.
* Add `suppressHydrationWarning` to avoid hydration issues in dev mode
* Display date/time instead of relative time since
* display bolt11 info and preimage for invoices
* Remove preimage attempt for wdrwl, since it doesn't make sense
Other various code cleanup
* Only include preimage for confirmed paid and settled invoices
adds auto-complete support for other stacker.news users when withdrawing
to a lightning address
implemented via adding an optional `transformUser` prop to the `UserSuggest` and `InputUserSuggest`
components, which allows you to transform fetched user results before displaying in the suggestion
dropdown
this is used to transform a user nym to nym@stacker.news, the corresponding
lightning address
by default, `transformUser` is an identity fn aka no transformation
this change also clears suggestions when the surrounding input field is blurred, which
is a better UX IMO
* Debounce the `onAddrChange` event handler when sending to a LN Address,
so we more accurately display the input form for LUD-12 and LUD-18 options
* Remove explicit URI encoding of Payer Data when sending to a LN Addr, since we're getting encoding for free via URLSearchParams
* Append `@stacker.news` to identifier values sent in payer data
* Don't do extra decoding when receiving LUD-18 data
* Crossposting discussion function, crossposting setting migration
* Passing in id, adding relays to test
* Adding checkbox setting for crossposting enabled
* Adding paramaterized event fields to crosspostDiscussion, successfully crossposting discussions
* Cleaning up for rebase
* Removing nostrRelays
* Retry crosspost toast
* Adding nostrCrossposting to settings, fixing migration
* Full flow is working with error surfacing, retries, and skips for a retry
* Updates to error handling/retries for crossposting, fixing settings for crossposting
* Allowing recursive retries for crossposting to specific relays
* Fixing / syncing crossposting settings, cleaning up and seperating out nostr functions
* Cleaning up
* Running linter
* make nostr crossposter a hook
---------
Co-authored-by: Austin <austin@pop-os.localdomain>
Co-authored-by: plebdev <plebdev@plebdevs-MacBook-Pro.local>
Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
Co-authored-by: keyan <keyan.kousha+huumn@gmail.com>
* LUD-18 Wallet implementation
Query the lightning address provider client-side to learn of capabilities
Conditionally render LUD-12 and LUD-18 fields based on what the remote
server says is supported
Allow identifier, name, and email to be sent from the SN side during the withdrawal flow. Auth seems too complicated for our use case, and idk about pubkey?
* Clear inputs if the new ln addr provier doesn't support those fields
* various ux improvements
* dynamic client-side validation for required payer data
* don't re-init form state on error
* correct min and max amount values
* only send applicable data to graphql api based on payerdata schema
* input type for numeric values (amount, max fee)
* update step for amount and max fee
* Fix identifier optional and field blur
* reuse more code
---------
Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
Co-authored-by: keyan <keyan.kousha+huumn@gmail.com>
* first pass of LUD-18 support
* Various LUD-18 updates
* don't cache the well-known response, since it includes randomly generated single use values
* validate k1 from well-known response to pay URL
* only keep k1's for 10 minutes if they go unused
* fix validation logic to make auth object optional
* Various LUD18 updates
* move k1 cache to database
* store payer data in invoice db table
* show payer data in invoices on satistics page
* show comments and payer data on invoice page
* Show lud18 data in invoice notification
* PayerData component for easier display of info in invoice, notification, wallet history
* `payerData` -> `invoicePayerData` in fact schema
* Merge prisma migrations
* lint fixes
* worker job to clear out unused lnurlp requests after 30 minutes
* More linting
* Move migration to older
* WIP review
* enhance lud-18
* refine notification ui
---------
Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
Co-authored-by: keyan <keyan.kousha+huumn@gmail.com>
* Remove outdated comments about srcSet value
We no longer distinguish between `undefined` and `null` for `srcSet`.
* Fix misleading URL shown
* Update/fix comments in <ImageOriginal>
* Simplify condition when to show image
I think this is not required since `showImage` will always stay false if tab !== 'preview' or me?.clickToLoadImg are true.
* Rename to imgproxyOnly
* Add info to imgproxyOnly setting
* Fix text of markdown links not used on imgproxy errors
* Fix rendering markdown links with text as images
---------
Co-authored-by: ekzyis <ek@stacker.news>
* Support JIT invoicing on donations to rewards pool
Now you can just-in-time fund your account to donate to SN's reward pool.
You can also donate without an account via the @anon account, also using
JIT invoices.
* Ensure donate amount is numeric
* Explicit error checking for hash being required for invoice validation
* let donation exceptions bubble for jit funding
---------
Co-authored-by: keyan <keyan.kousha+huumn@gmail.com>
Danger case was already handled by the common `Form` component,
but success wasn't happening. I like having feedback on actions like this one.
Now, the danger toast is also specific to the donate action, and not just the underlying
JS error that occurred (which is logged, instead).
* Convert worker to ESM
To use ESM for the worker, I created a package.json file in worker/ with `{ type: "module" }` as its sole content.
I then rewrote every import to use ESM syntax.
I also tried to set `{ type: "module" }` in the root package.json file to also use ESM in next.config.js.
However, this resulted in a weird problem: default imports were now getting imported as objects in this shape: `{ default: <defaultImport> }`.
Afaik, this should only be the case if you use "import * as foo from 'bar'" syntax: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#default_import
This is fixed by not using `{ type: "module" }` for some reason. However, then, next.config.js also doesn't support ESM import syntax anymore.
The documentation says that if you want to use ESM, you can use next.config.mjs: https://nextjs.org/docs/pages/api-reference/next-config-js
But I didn't want to use MJS extension since I don't have any experience with it. For example, not sure if it's good style to mix JS with MJS etc. So I kept the CJS import syntax there.
* Ignore worker/ during linting
I wasn't able to fix the following errors:
/home/runner/work/stacker.news/stacker.news/worker/auction.js:0:0: Parsing error: No Babel config file detected for /home/runner/work/stacker.news/stacker.news/worker/auction.js. Either disable config file checking with requireConfigFile: false, or configure Babel so that it can find the config files. (null)
/home/runner/work/stacker.news/stacker.news/worker/earn.js:0:0: Parsing error: No Babel config file detected for /home/runner/work/stacker.news/stacker.news/worker/earn.js. Either disable config file checking with requireConfigFile: false, or configure Babel so that it can find the config files. (null)
/home/runner/work/stacker.news/stacker.news/worker/index.js:0:0: Parsing error: No Babel config file detected for /home/runner/work/stacker.news/stacker.news/worker/index.js. Either disable config file checking with requireConfigFile: false, or configure Babel so that it can find the config files. (null)
/home/runner/work/stacker.news/stacker.news/worker/nostr.js:0:0: Parsing error: No Babel config file detected for /home/runner/work/stacker.news/stacker.news/worker/nostr.js. Either disable config file checking with requireConfigFile: false, or configure Babel so that it can find the config files. (null)
/home/runner/work/stacker.news/stacker.news/worker/ots.js:0:0: Parsing error: No Babel config file detected for /home/runner/work/stacker.news/stacker.news/worker/ots.js. Either disable config file checking with requireConfigFile: false, or configure Babel so that it can find the config files. (null)
/home/runner/work/stacker.news/stacker.news/worker/repin.js:0:0: Parsing error: No Babel config file detected for /home/runner/work/stacker.news/stacker.news/worker/repin.js. Either disable config file checking with requireConfigFile: false, or configure Babel so that it can find the config files. (null)
/home/runner/work/stacker.news/stacker.news/worker/search.js:0:0: Parsing error: No Babel config file detected for /home/runner/work/stacker.news/stacker.news/worker/search.js. Either disable config file checking with requireConfigFile: false, or configure Babel so that it can find the config files. (null)
/home/runner/work/stacker.news/stacker.news/worker/streak.js:0:0: Parsing error: No Babel config file detected for /home/runner/work/stacker.news/stacker.news/worker/streak.js. Either disable config file checking with requireConfigFile: false, or configure Babel so that it can find the config files. (null)
/home/runner/work/stacker.news/stacker.news/worker/trust.js:0:0: Parsing error: No Babel config file detected for /home/runner/work/stacker.news/stacker.news/worker/trust.js. Either disable config file checking with requireConfigFile: false, or configure Babel so that it can find the config files. (null)
/home/runner/work/stacker.news/stacker.news/worker/views.js:0:0: Parsing error: No Babel config file detected for /home/runner/work/stacker.news/stacker.news/worker/views.js. Either disable config file checking with requireConfigFile: false, or configure Babel so that it can find the config files. (null)
/home/runner/work/stacker.news/stacker.news/worker/wallet.js:0:0: Parsing error: No Babel config file detected for /home/runner/work/stacker.news/stacker.news/worker/wallet.js. Either disable config file checking with requireConfigFile: false, or configure Babel so that it can find the config files. (null)
I tried to tell babel where to find the babel config file (.babelrc), specifying the babel config in worker/package.json under "babel", using babel.config.json etc. to no avail.
However, afaict, we don't need babel for the worker since it won't run in a browser. Babel is only used to transpile code to target browsers.
But it still would be nice to lint the worker code with standard.
But we can figure this out later.
* Fix worker imports from lib/ and api/
This fixes the issue that we can't use `{ "type": "module" }` in the root package.json since it breaks the app with this error:
app | TypeError: next_auth_providers_credentials__WEBPACK_IMPORTED_MODULE_2__ is not a function
app | at eval (webpack-internal:///./pages/api/auth/[...nextauth].js:218:20)
app | at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
app | LND GRPC connection successful
app | - error pages/api/auth/[...nextauth].js (139:2) @ CredentialsProvider
app | - error Error [TypeError]: next_auth_providers_credentials__WEBPACK_IMPORTED_MODULE_2__ is not a function
app | at eval (webpack-internal:///./pages/api/auth/[...nextauth].js:218:20) {
app | digest: undefined
app | }
app | 137 |
app | 138 | const providers = [
app | > 139 | CredentialsProvider({
app | | ^
app | 140 | id: 'lightning',
app | 141 | name: 'Lightning',
app | 142 | credentials: {
app | TypeError: next_auth_providers_credentials__WEBPACK_IMPORTED_MODULE_2__ is not a function
app | at eval (webpack-internal:///./pages/api/auth/[...nextauth].js:218:20)
app | at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
build but we need to tell the worker that the files are MJS, else we get this error:
worker | file:///app/worker/wallet.js:3
worker | import { datePivot } from '../lib/time.js'
worker | ^^^^^^^^^
worker | SyntaxError: Named export 'datePivot' not found. The requested module '../lib/time.js' is a CommonJS module, which may not support all module.exports as named exports.
worker | CommonJS modules can always be imported via the default export, for example using:
worker |
worker | import pkg from '../lib/time.js';
worker | const { datePivot } = pkg;
worker |
worker | at ModuleJob._instantiate (node:internal/modules/esm/module_job:124:21)
worker | at async ModuleJob.run (node:internal/modules/esm/module_job:190:5)
worker |
worker | Node.js v18.17.0
worker |
worker exited with code 1
* Fix global not defined in browser context
* Also ignore api/ and lib/ during linting
I did not want to do this but I was not able to fix this error in any other way I tried:
/home/ekzyis/programming/stacker.news/api/lnd/index.js:0:0: Parsing error: No Babel config file detected for /home/ekzyis/programming/stacker.news/api/lnd/index.js. Either disable config file checking with requ
ireConfigFile: false, or configure Babel so that it can find the config files. (null)
Did not want to look deeper into all this standard, eslint, babel configuration stuff ...
---------
Co-authored-by: ekzyis <ek@stacker.news>
Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
* Prototype implementing LUD-12 comments on payRequest in LNURLP Lightning Address flow
* Support sending comment when withdrawing to ln addr (LUD-12)
* Prevent `initialError` from being toasted informs multiple times
* delete the old create_invoice function
* improve lightning addr withdrawal styling
* allow lnaddr comment to show up in notifications
* enhance satistics
---------
Co-authored-by: keyan <keyan.kousha+huumn@gmail.com>
* Add diagnostics settings & endpoint
Stackers can now help us to identify and fix bugs by enabling diagnostics.
This will send anonymized data to us.
For now, this is only used to send events around push notifications.
* Send diagnostics to slack
* Detect OS
* Diagnostics data is only pseudonymous, not anonymous
It's only pseudonymous since with additional knowledge (which stacker uses which fancy name), we could trace the events back to individual stackers.
Data is only anonymous if this is not possible - it must be irreversible.
* Check if window.navigator is defined
* Use Slack SDK
* Catch errors of slack requests
---------
Co-authored-by: ekzyis <ek@stacker.news>
Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
* Hide wallet balance on long press
* Use setting to hide wallet balance
* Fix layout shift on hover
* Fix SSR warning about useLayoutEffect
See https://reactjs.org/link/uselayouteffect-ssr
* Also hide balance in wallet
---------
Co-authored-by: ekzyis <ek@stacker.news>
* Add block height to price carousel
source block height from mempool.space API
https://mempool.space/docs/api/rest#get-block-tip-height
* Add block height to SSR, clean up fragment query
* Cache block height for 1 minute, not 30 seconds
use `numWithUnits` for block height label
* Replace mempool.space API with LND API call
---------
Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
* Notifications for when you are forwarded sats from a post
Support notifications when a post for which you are forwarded gets zapped
This is controlled by a new boolean flag in user settings
* Send push notifications to forwarded users when they get forwarded sats
* Add `Promise.allSettled` per PR feedback
* Remove `FEE` act type when building forwarded zaps notifications
Don't include `FEE` actions, only `TIP` actions to avoid "0 sats forwarded" notifications
---------
Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
This overrides OS auto-rotate settings on Android. This means that the PWA does auto-rotate even if the OS setting to auto-rotate is not enabled.
This property is experimental and only supported by Chromium-based browsers anyway.
Also, you can still manually rotate if you want.
Co-authored-by: ekzyis <ek@stacker.news>
* Use HODL invoices
* Fix expiry check comparing string with Date
* Fix unconfirmed user balance for HODL invoices
This is done by syncing the data from LND to the Invoice table.
If the columns is_held and msatsReceived are set, the frontend is told that we're ready to execute the action.
We then update the user balance in the same tx as the action.
We need to still keep checking the invoice for expiration though.
* Fix worker acting upon deleted invoices
* Prevent usage of invoice after expiration
* Use onComplete from <Countdown> to show expired status
* Remove unused lnd argument
* Fix item destructuring from query
* Fix balance added to every stacker
* Fix hmac required
* Fix invoices not used when logged in
* refactor: move invoiceable code into form
* renamed invoiceHash, invoiceHmac to hash, hmac since it's less verbose all over the place
* form now supports `invoiceable` in its props
* form then wraps `onSubmit` with `useInvoiceable` and passes optional invoice options
* Show expired if expired and canceled
* Also use useCallback for zapping
* Always expire modal invoices after 3m
* little styling thing
---------
Co-authored-by: ekzyis <ek@stacker.news>
Co-authored-by: keyan <keyan.kousha+huumn@gmail.com>
Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
* Prototype of toast system
* More toast adoption
* share
* flag
* bookmark
* subscribe
* delete
* More toast usage:
* forms
* settings save
* Log error during flag failure
* Incorporate PR feedback:
1. return `toaster` from `useToast` hook, with simplified `success` and `danger` methods
2. remove toast header, move close button to body
3. change how toast ids are generated to use a global incrementing int
4. update toast messages
* PR feedback:
* reduce width of toast on narrow screens
* dynamic delete success toast message based on deleted type
* add toasts to auth methods deletion operations
* Dismiss all toasts upon page navigation
* refine style and use delay prop
* more styling
---------
Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
Co-authored-by: keyan <keyan.kousha+huumn@gmail.com>
* Add new setting to hide bookmarks from other users (and anon)
* Optional chaining in case user doesnt exist, and avoid duplicate sql query in some cases
Remove the static manifest file and serve it via an API route instead.
Change the background color of the PWA depending on the client hint provided data
* Configure imgproxy timeouts
* Use click to load on imgproxy errors
* Add setting for click to load
---------
Co-authored-by: ekzyis <ek@stacker.news>
Add images for each supported iOS device for a dark-theme splash screen
Conditionally use light vs dark images based on the `(prefers-color-scheme: dark)`
media query
Note: Once the PWA is installed, it appears that iOS caches the splash screen image for an
unknown period of time, so if you change your device's preferred theme after installation,
the splash screen doesn't update to reflect it. The PWA must be re-installed for
this change to take effect.
* Add anon zaps
* Add anon comments and posts (link, discussion, poll)
* Use payment hash instead of invoice id as proof of payment
Our invoice IDs can be enumerated.
So there is a - even though very rare - chance that an attacker could find a paid invoice which is not used yet and use it for himself.
Random payment hashes prevent this.
Also, since we delete invoices after use, using database IDs as proof of payments are not suitable.
If a user tells us an invoice ID after we deleted it, we can no longer tell if the invoice was paid or not since the LN node only knows about payment hashes but nothing about the database IDs.
* Allow pay per invoice for stackers
The modal which pops up if the stacker does not have enough sats now has two options: "fund wallet" and "pay invoice"
* Fix onSuccess called twice
For some reason, when calling `showModal`, `useMemo` in modal.js and the code for the modal component (here: <Invoice>) is called twice.
This leads to the `onSuccess` callback being called twice and one failing since the first one deletes the invoice.
* Keep invoice modal open if focus is lost
* Skip anon user during trust calculation
* Add error handling
* Skip 'invoice not found' errors
* Remove duplicate insufficient funds handling
* Fix insufficient funds error detection
* Fix invoice amount for comments
* Allow pay per invoice for bounty and job posts
* Also strike on payment after short press
* Fix unexpected token 'export'
* Fix eslint
* Remove unused id param
* Fix comment copy-paste error
* Rename to useInvoiceable
* Fix unexpected token 'export'
* Fix onConfirmation called at every render
* Add invoice HMAC
This prevents entities which know the invoice hash (like all LN nodes on the payment path) from using the invoice hash on SN.
Only the user which created the invoice knows the HMAC and thus can use the invoice hash.
* make anon posting less hidden, add anon info button explainer
* Fix anon users can't zap other anon users
* Always show repeat and contacts on action error
* Keep track of modal stack
* give anon an icon
* add generic date pivot helper
* make anon user's invoices expire in 5 minutes
* fix forgotten find and replace
* use datePivot more places
* add sat amounts to invoices
* reduce anon invoice expiration to 3 minutes
* don't abbreviate
* Fix [object Object] as error message
Any errors thrown here are already objects of shape { message: string }
* Fix empty invoice creation attempts
I stumbled across this while checking if anons can edit their items.
I monkey patched the code to make it possible (so they can see the 'edit' button) and tried to edit an item but I got this error:
Variable "$amount" of required type "Int!" was not provided.
I fixed this even though this function should never be called without an amount anyway. It will return a sane error in that case now.
* anon func mods, e.g. inv limits
* anon tips should be denormalized
* remove redundant meTotalSats
* correct overlay zap text for anon
* exclude anon from trust graph before algo runs
* remove balance limit on anon
* give anon a bio and remove cowboy hat/top stackers;
* make anon hat appear on profile
* concat hash and hmac and call it a token
* Fix localStorage cleared because error were swallowed
* fix qr layout shift
* restyle fund error modal
* Catch invoice errors in fund error modal
* invoice check backoff
* anon info typo
* make invoice expiration times have saner defaults
* add comma to anon info
* use builtin copy input label
---------
Co-authored-by: ekzyis <ek@stacker.news>
Co-authored-by: keyan <keyan.kousha+huumn@gmail.com>
* npm uninstall next-pwa
next-pwa was last updated in August 2022.
There is also an issue which mentions that next-pwa is abandoned (?): https://github.com/shadowwalker/next-pwa/issues/482
But the main reason for me uninstalling it is that it adds a lot of preconfigured stuff which is not necessary for us.
It even lead to a bug since pages were cached without our knowledge.
So I will go with a different PWA approach. This different approach should do the following:
- make it more transparent what the service worker is doing
- gives us more control to configure the service worker and thus making it easier
* Use workbox-webpack-plugin
Every other plugin (`next-offline`, `next-workbox-webpack-plugin`, `next-with-workbox`, ...) added unnecessary configuration which felt contrary to how PWAs should be built.
(PWAs should progressivly enhance the website in small steps, see https://web.dev/learn/pwa/getting-started/#focus-on-a-feature)
These default configurations even lead to worse UX since they made invalid assumptions about stacker.news:
We _do not_ want to cache our start url and we _do not_ want to cache anything unless explicitly told to.
Almost every page on SN should be fresh for the best UX.
To achieve this, by default, the service worker falls back to the network (as if the service worker wasn't there).
Therefore, this should be the simplest configuration with a valid precache and cache busting support.
In the future, we can try to use prefetching to improve performance of navigation requests.
* Add support for Web Share Target API
See https://developer.chrome.com/articles/web-share-target/
* Use Web Push API for push notifications
I followed this (very good!) guide: https://web.dev/notifications/
* Refactor code related to Web Push
* Send push notification to users on events
* Merge notifications
* Send notification to author of every parent recursively
* Remove unused userId param in savePushSubscription
As it should be, the user id is retrieved from the authenticated user in the backend.
* Resubscribe user if push subscription changed
* Update old subscription if oldEndpoint was given
* Allow users to unsubscribe
* Use LTREE operator instead of recursive query
* Always show checkbox for push notifications
* Justify checkbox to end
* Update title of first push notification
* Fix warning from uncontrolled to controlled
* Add comment about Notification.requestPermission
* Fix timestamp
* Catch error on push subscription toggle
* Wrap function bodies in try/catch
* Use Promise.allSettled
* Filter subscriptions by user notification settings
* Fix user notification filter
* Use skipWaiting
---------
Co-authored-by: ekzyis <ek@stacker.news>
* Enable push notifications in settings
* Fix checkbox still checked after user denied permission
The error was related to me thinking that the value prop does anything. It didn't.
The value of the checkbox is handled by formik.
So the solution was to hook into formik and use the handler which actually changes the value.
* Add double opt-in to /notifications
* Better styling of alert in /notifications
---------
Co-authored-by: ekzyis <ek@stacker.news>