ekzyis d89a4a429a
Wallet v2 (#2169)
* Migrate vault entries to new schema (#2092)

* Migrate existing vault entries to new schema

* Read+write new vault schema

* Drop VaultEntry table

* Refactor vaultPrismaFragments

* Remove wrong comment

* Remove TODO

* Fix possible race condition on update of vault key

* Remove lib/object.js

* Wallet schema v2 (#2146)

* Add wallet-v2 TODOs

* Update checkWallet

* Wallet list

* Delete almost all wallet v1 code

and add some code for wallet protocol forms

* Define protocol display name in JSON

* Show form per protocol

* Increase max-height of image in form

* Add JSdoc for protocols, form validation

* Use wallet cards again

My wallet list was quite ugly and I couldn't look at it anymore.

* Refactor hooks in wallet provider

* Fix PasswordInput not used

* Read encrypted wallets

* Decrypt wallets

* useWalletQuery now returns decrypted wallets
* Refactor useIndexedDB because its only purpose will be to store the key, so no need for pagination code etc.
* There is still a bug: if the wallet is not decrypted on first render, the form will not see the decrypted value. See TODO.

* Rename protocolJson to protocol

it no longer uses a JSON file

* Fix form not updated with decrypted API key

* Fix wallet template forms

* Fix optional shown as hint

* Rename to mapUserWalletResolveTypes

* Save LNbits send and recv

TODO:

* implement resolvers for other protocols
* fix double update required for trigger?
* add missing validation on server
* add missing network tests
* don't import from wallets/client on server

* Move definitions to lib/wallets.json and lib/protocols

* Fix ProtocolWallet.updated_at not updated by trigger

* Move wallet fragments into wallets/client/fragments/

* move invoice fragments to fragments/invoice.js
* remove some unused fragments that I don't think I also will not use
* move fragments that will be generated in own file

* Move wallet resolvers into wallets/server/resolvers

* Fix missing authorization check on wallet update

* Run all shared code in generic wallet update function

* Fix 'encrypt' flag not set for blink send currency

* Add mutations for all protocols

* Fix macaroon validation

* Fix CLN socket value not set

* Add server-side schema validation

* Fix JSDoc typedef for protocols

* Don't put JSDoc into separate file

* Create test invoices on save

* Also move type resolvers into wallets/server/resolvers

* Fix unconfigured protocols of UserWallet not found

* Fix Blink API key in wallet seed

* Test send payment on save (except LNC)

This does not include LNC because LNC cannot be saved yet

* Check if window.webln is defined on save

* Create new wallets from templates

* Separate protocols in wallets/lib into individual files

* Use justify-content-start for protocol tabs

and larger margin at the top

* Add LNC to client protocols

* Only return wallets from useWallets

* Query decrypted wallets

* Payments with new wallets

* More wallet logos

* Fix TypeError in useIndexedDB

* Add protocol attach docs

* Fix undefined useWalletRecvPrompt import

* Remove outdated TODOs

* First successful zap to new wallets

* Fix walletLogger imports

* Fix sequences

* the sequences for InvoiceForward and DirectPayment were still starting at 1
* when using setval() with two arguments, nextval() will return the second argument+1 (see https://www.postgresql.org/docs/current/functions-sequence.html)

* Rename ProtocolWallet columns

* Remove more outdated TODOs

* Update wallet indicator

* Fix page reset on route change

* Refactor __typename checks into functions

* Refactor protocol selection into own hook

* Add button to detach protocol

* Refetch wallet on save and detach

* Refetch wallets on change

* Always show all templates

* Refactor WalletLink component

* Also put wallet into forms context

* Remove outdated TODOs

* Use useMemo in wallets hooks

* Passphrase modals

* prompt for password if decryption failed
* add button to reveal passphrase on wallet page

TODO:
* remove button if passphrase was revealed or imported
* encrypt wallets with new key on passphrase reveal

* Fix protocol missing as callback dependency

* Encrypt wallets with new key on passphrase export

* Update 'unlock wallets' text

* Rename wallet mutation hooks

* Remove 'removeWallet' mutation

Wallets are automatically deleted when all protocols are deleted

* Passphrase reset

* Use 110px as minimum width for bip39 words

longest bip39 words are 8 characters and they fit into 103px so I rounded up to 110px.

* Also disable passphrase export on save

* Wallet settings

* Fix wallet receive prompt

* Remove unused parameters from postgres function

* Rename UserWallet to Wallet, ProtocolWallet to WalletProtocol

* Use danger variant for button to show passphrase

* Fix inconsistent imports and exports

* Remove outdated TODOs

* wallet logs

* Remove outdated comment

* Make sure wallets are used in priority order

* Separate wallets from templates in reducer

* Fix missing useCallback dependencies

* Refactor with useWalletLogger hook

* Move enabled to WalletProtocol

* Add checkbox to enable/disable protocol

* Fix migration with prod db dump

* Parse Coinos relay URLs

* Skip network tests if only enabled changed

* Allow IndexedDB calls without session

* Add code to migrate old CryptoKey

* first try to use existing CryptoKey before generating a new one
* bump IDB version to delete old object stores and create new ones
* return IDB callbacks with useMemo
* don't delete old IDB right away, wait until next release

* Fix ghost import error

*Sometimes*, I get import errors because it tries to resolve @/wallets/server to wallets/server.js instead of wallets/server/index.js.

For the files in wallets/server, it kind of makes sense because it's a circular import.

But I don't know why the files in worker/ have this problem.

Interestingly, it only seems to happen with walletLogger imports, so I guess its related to its import chain.

Anyway, this commit should make sure this never happens again ...

* Skip wallets queries if not logged in

* Split CUSTOM wallet into NWC and LN_ADDR

* Migrate local wallets

* Link to /wallets/:id/receive if send not supported

* Hide separator if there are no configured wallets

* Save LNC

* Add one-liner to attach LNC

* Update wallet priorities via DnD

* Wallet logs are part of protocol resolvers

* Fix logging to deleted protocol

* Fix trying to fetch logs for template

* also change type to Int so GraphQL layer can catch trying to fetch string IDs as is the case for templates

* Fix embedded flag for wallets logs not set

* Remove TODO

* Decrease max-height for embedded wallet logs on big screens

* Fix missing refetch on wallet priority update

* Set priorities of all wallets in one tx

* Fix nested state update

* Add DragIcon

* DnD mobile support and refactor

* Add CancelButton to wallet settings

* Remount form if path changes

This fixes the following warning in the console:

"""
Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component.
"""

* Support string and object for wallet.image JSON

* Append domain to lightning address inputs

* Remove outdated TODOs

* Add template IDs to wallet JSON

* Fix missing callback dependency

* Implement lightning address save in receive prompt

* Update TODOs

* Fix missing check for enabled

* Pay QR codes with WebLN as anon

* Add logo for NWC

* Fix trying to save logs for template

* Add template logs

* Fix inconsistent margin

* Always throw on missing key

* Remove misleading comment

Wallets are returned even if decryption fails so we can show the unlock page if a wallet is stored as encrypted in the context.

Maybe I should rethink this.

* Check for existing wallets on local wallet migration

* Fix local wallet migration causing duplicates

* Fix protocol reattached on detach due to migration

* Fix form not centered

* Fix ZEUS lightning address domain

* Add placeholder, help, hints etc. to wallet form inputs

* Fix wallet badges not updated

* Remove unused declared variables

* Rename to ATTACH_PAGE

* Fix 500 error if no amount was given to LNURLp endpoint

* Tag log messages with wallet name

* Only skip network tests if we're disabling the wallet

* Rename var to networkTests

* Continue to store key hash in IndexedDB

* Rethink wallet state management

If decryption failed, the function to decrypt the wallets didn't throw but simply returned wallets that were still encrypted.

This was bad because it meant we could not rely on the wallets in the state being decrypted, even though this was the original idea behind the query hooks: hide the details of encryption and decryption inside them.

Because of this, we had to check if the wallets were still encrypted before we ran the wallet migration since we want to check if a protocol already exists.

This commit fixes this by making encryption and decryption always throw (and catching the errors), as well as returning a ready state from hooks. A hook might not be ready because it still needs to load something (in the case of the crypto hooks, it's loading the key from IndexedDB). Callers check that ready state before they call the function returned by the hook.

So now, the wallet migration hook can itself simply check if the hook to encrypt wallets is ready and if the wallets are no longer loading to let callers know if it itself is ready.

Since we also relied on wallets stored as encrypted in the context to show the unlock page, this was also changed by comparing the local and remote key hash.

* Add empty line

* Save new key hash during wallet reset

* Only receive protocol upserts require networkTests param

* Compare key hashes on server on each save

* Delete old code

* Fix card shows attach instead of configure

* Fix empty wallets created during migration

The old schema can contain '' instead of NULL in the columns of wallets for receiving.

* Update reset passphrase text

* Wrap passphrase reset in try/catch

* Fix migrate called multiple times

* Update key hash on migration if not set

* Fetch local wallets in migrate

* Fix missing await on setKey

* Let first device set key hash

* Fix indicator not shown if wallets locked

* Check if IndexedDB is available

* Fix inconsistent WebLN error message

* Disable WebLN if not available

* Remove outdated TODO

* Cursor-based pagination for wallet logs

* Fix log message x-overflow

* Add context to wallet logs

* Wrap errors are warnings in logs

* Rename wallet v2 migrations

* Update wallet status during logging

* Fix wallet logs loading state

The loading state would go from false -> true -> false because it's false when the lazy query wasn't called yet.

* Add wallet search

* Add Alby Go wallet

* Revert "Add Alby Go wallet"

This reverts commit 926c70638f1673756480c848237e52d5889dc037.

* Fix wallet logs sent by client don't update protocol status

* Fix mutation name

* put drag icon on opposite corner

* Add wallets/README.md

* Fix inconsistent case in wallets/README.md

* Fix autoprefixer warning about mixed support

This warning was in the app logs:

app     | Warning
app     |
app     | (31:3) autoprefixer: end value has mixed support, consider using flex-end instead
app     |
app     | Import trace for requested module:
app     | ./styles/wallet.module.css
app     | ./wallets/client/hooks/prompt.js
app     | ./wallets/client/hooks/index.js
app     | ./wallets/client/context/hooks.js
app     | ./wallets/client/context/provider.js
app     | ./wallets/client/context/index.js

* fix effect of wallet indicators on logo

* Fix deleting wallet template logs

* Use name as primary key of WalletTemplate

* Fix wallet_clear_vault trigger not mentioned in README

* Fix wallet receive prompt

Also remove no longer needed templateId from wallets.json and helper functions

* Use findUnique since name is now primary key

* Merge Alby wallets into one

* Remove unused name parameter from WalletsForm component

* Fix number check to decide if wallet or template

* Update wallet encryption on click, not as effect

* add cashu.me and lightning address logos

* add images

* Use recommended typeof to check if IDB available

* Also check if IDB available on delete

* Use constraint triggers

* Add indices on columns used for joins

* Fix inconsistent CLEAR OR REPLACE TRIGGER

* Attach wallet_check_support trigger to WalletProtocol table

* Update wallets/README.md

* Remove debugging code

* Refactor reducer: replace page with status

* Show 'wallets unavailable' if device does not support IndexedDB

* Remove duplicate ELSIF condition

* Fix hasSendWallet

The useSendWallets hook was not checking if the returned send wallets are enabled.

Since the components that used that hook only need to know if there is a send wallet, I replaced the useSendWallets hook with a useHasSendWallet hook.

* Add Cash App wallet

* fix changes loglevel enum

* Fix key init race condition in strict mode if no key exists yet

* Formatting

* Fix key init race condition via transactions in readwrite mode

* Replace Promise.withResolvers with regular promises

* replace generic spinner with our usual

---------

Co-authored-by: k00b <k00b@stacker.news>
2025-07-15 16:36:43 -05:00
2024-01-30 18:47:01 -06:00
2022-06-08 16:56:35 -05:00
2025-07-15 16:36:43 -05:00
2025-04-12 14:20:35 -05:00
2024-04-12 19:15:04 -05:00
2025-07-15 16:36:43 -05:00
2024-09-06 10:04:03 -05:00
2025-07-15 16:36:43 -05:00
2025-07-15 16:36:43 -05:00
2025-07-15 16:36:43 -05:00
2025-07-15 16:36:43 -05:00
2025-07-15 16:36:43 -05:00
2025-07-15 16:36:43 -05:00
2025-07-15 16:36:43 -05:00
2025-07-15 16:36:43 -05:00
2025-07-10 11:54:23 -05:00
2025-07-15 16:36:43 -05:00
2025-07-15 16:36:43 -05:00
2024-10-15 12:13:40 -05:00
2025-07-15 16:36:43 -05:00
2025-07-11 23:39:07 -05:00
2025-05-13 13:44:12 -05:00
2025-07-15 16:36:43 -05:00
2024-10-08 15:23:27 -05:00
2021-06-28 18:28:26 -05:00
2025-06-03 20:47:25 -05:00
2025-07-04 01:14:45 -05:00
2025-07-04 01:14:45 -05:00
2023-09-26 20:33:54 -05:00
2025-05-21 13:06:19 -05:00
2025-06-02 13:07:26 -05:00

Internet Communities with Bitcoin Economies

  • Stacker News is trying to fix online communities with economics
  • What You See is What We Ship (look ma, I invented an initialism)
  • 100% FOSS
  • We pay bitcoin for PRs, issues, documentation, code reviews and more
  • Next.js, postgres, graphql, and lnd

Getting started

Launch a fully featured SN development environment in a single command.

$ ./sndev start

Go to localhost:3000.


Installation

  • Clone the repo
    • ssh: git clone git@github.com:stackernews/stacker.news.git
    • https: git clone https://github.com/stackernews/stacker.news.git
  • Install docker
    • If you're running MacOS or Windows, I highly recommend using OrbStack instead of Docker Desktop
  • Please make sure that at least 10 GB of free space is available, otherwise you may encounter issues while setting up the development environment.

Usage

Start the development environment

$ ./sndev start

View all available commands

$ ./sndev help

                            888
                            888
                            888
      .d8888b  88888b.  .d88888  .d88b.  888  888
     88K      888 '88b d88' 888 d8P  Y8b 888  888
     'Y8888b. 888  888 888  888 88888888 Y88  88P
          X88 888  888 Y88b 888 Y8b.      Y8bd8P
      88888P' 888  888  'Y88888  'Y8888    Y88P

manages a docker based stacker news development environment

USAGE
  $ sndev [COMMAND]
  $ sndev help [COMMAND]

COMMANDS
  help                    show help

  env:
    start                 start env
    stop                  stop env
    restart               restart env
    status                status of env
    logs                  logs from env
    delete                delete env

  sn:
    login                 login as a nym
    set_balance           set the balance of a nym

  lightning:
    fund                   pay a bolt11 for funding
    withdraw               create a bolt11 for withdrawal

  db:
    psql                   open psql on db
    prisma                 run prisma commands

  domains:
    domains                custom domains dev management

  dev:
    pr                     fetch and checkout a pr
    lint                   run linters
    test                   run tests

  other:
    cli                    service cli passthrough
    open                   open service GUI in browser
    onion                  service onion address
    cert                   service tls cert
    compose                docker compose passthrough

Modifying services

Running specific services

By default all services will be run. If you want to exclude specific services from running, set COMPOSE_PROFILES in a .env.local file to one or more of minimal,images,search,payments,wallets,email,capture. To only run mininal necessary without things like payments in .env.local:

COMPOSE_PROFILES=minimal

To run with images and payments services:

COMPOSE_PROFILES=images,payments

Merging compose files

By default sndev start will merge docker-compose.yml with docker-compose.override.yml. Specify any overrides you want to merge with docker-compose.override.yml.

For example, if you want to replace the db seed with a custom seed file located in docker/db/another.sql, you'd create a docker-compose.override.yml file with the following:

services:
  db:
    volumes:
      - ./docker/db/another.sql:/docker-entrypoint-initdb.d/seed.sql

You can read more about docker compose override files.

To enable semantic search that uses text embeddings, run ./scripts/nlp-setup.

Before running ./scripts/nlp-setup, ensure the following are true:

  • search is enabled in COMPOSE_PROFILES:

    COMPOSE_PROFILES=...,search,...
    
  • The default opensearch index (default name=item) is created and done indexing. This should happen the first time you run ./sndev start, but it may take a few minutes for indexing to complete.

After nlp-setup is done, restart your containers to enable semantic search:

> ./sndev restart

Local DNS via dnsmasq

To enable dnsmasq:

  • domains should be enabled in COMPOSE_PROFILES:

    COMPOSE_PROFILES=...,domains,...
    

To add/remove DNS records you can now use ./sndev domains dns. More on this here.


Table of Contents


Contributing

We want your help.


We pay bitcoin for contributions

  • pull requests closing existing issues
  • code review
  • issue specification whether for bugs, features, or enhancements
  • discovery of security vulnerabilities
  • discovery of privacy vulnerabilities
  • improvements to development documentation
  • helpfulness

View a current list of granted awards


Just in case

This document in no way legally entitles you to payments for contributions, entitles you to being a contributor, or entitles you to the attention of other contributors. This document lays out the system we can use to determine contribution awards which we generally intend to abide by but importantly we reserve the right to refuse payments or contributions, modify rules and award amounts, make exceptions to rules or reward amounts, and withhold awards for any reason at anytime, even just for the heck of it, at our sole discretion. If you need more certainty than what I've just described, don't participate. We provide awards as an experiment to make FOSS less sucky.


Pull request awards

Rules

  1. PRs closing an issue will be awarded according to the difficulty tag on an issue, e.g. difficulty:easy pays 100k sats.
  2. Issues are occasionally marked with a priority tag which multiplies the award of a PR closing an issue, e.g. an issue marked with priority:high and difficulty:hard awards 2m sats.
  3. An award is reduced by 10% of the award amount for each substantial change requested to the PR on code review, e.g. if two changes are requested on a PR closing an issue tagged with difficulty:hard, 800k sats will be awarded.
    • Reductions are applied before priority multipliers, e.g. a PR closing a priority:high and difficulty:hard issue that's approved after two changes are requested awards 1.6m sats.
    • You are responsible for understanding the issue and requirements before requesting review on a PR.
    • There is no award reduction for asking specific questions on the issue itself or on the PR before requesting review
    • There is no award reduction for asking more general questions in a discussion
  4. A PR must be merged by an SN engineer before a PR receives an award

Due to Rule 3, make sure that you mark your PR as a draft when you create it and it's not ready for review yet.

Difficulty award amounts

tag description award
difficulty:good-first-issue at most a couple lines of code in a couple files and does not require much familiarity with the codebase 20k sats
difficulty:easy at most a couple lines of code in a couple files but does require familiarity with the code base 100k sats
difficulty:medium more code, more places and could require adding columns in the db and some modification chunky db queries 250k sats
difficulty:medium-hard even more code, even more places and requires either more sophisticated logic, more significant db modeling eg adding a table, and/or a deeper study of a something 500k sats
difficulty:hard either a bigger lift than the what's required of medium-hard or very tricky in a particular way that might not require a lot of code but does require a lot of context/troubleshooting/expertise 1m sats

Priority multipliers

tag multiplier
priority:low 0.5
priority:medium 1.5
priority:high 2
priority:urgent 3

Requesting modifications to reward amounts

We try to assign difficulty and priority tags to issues accurately, but we're not perfect. If you believe an issue is mis-tagged, you can request a change to the issue's tags.


Code review awards

Code reviewers will be awarded the amount their code review reduced from the PR author's reward, e.g. two substantial problems/areas of improvement identified in a PR closing a priority:high and difficulty:hard issue awards 400k sats.

Rules

  1. The problem or improvement must be acknowledged as such by SN engineers explicitly
  2. A PR must be merged by an SN engineer before a PR's code reviewers receive an award

Code review approvals are more than welcome, but we can't guarantee awards for them because the work performed to approve a PR is unverifiable.


Issue specification awards

Issue specifiers will be awarded up to 10% of a PR award for issues resulting in a PR being merged by an SN engineer that closes the issue. In addition to being subject to PR award amounts and reductions, specification amounts are awarded on the basis of how much additional help and specification is required by other contributors.

Rules

  1. The issue must directly result in PR being merged by an SN engineer that closes the issue
  2. Issue specification award amounts are based on the final PR award amounts
    • that is, they are subject to PR award code review reductions and priority multipliers
  3. Award amounts will be reduced on the basis of how much additional help and specification is required by other contributors
  4. Issue specifiers who can close their own issues with their own PRs are also eligible for this 10%
    • e.g an issue tagged as difficulty:hard that is both specified and closed by a PR from the same contributor without changes requested awards 1.1m sats

Relative awards

circumstances award
issue doesn't require further help and/or specification from other contributors 10%
issue requires little help and/or specification from other contributors 5%
issue requires more help and/or specification from other contributors than the issue specifier contributed 1%
issue is vague and/or incomplete and must mostly be entirely specified by someone else 0%

For example: a specified issue that's tagged as difficulty:hard, doesn't require additional specification and disambiguation by other contributors, and results in PR being merged without changes requested awards the issue specifier 100k sats.


Responsible disclosure of security or privacy vulnerability awards

Awards for responsible disclosures are assessed on the basis of:

  1. the potential loss resulting from an exploit of the vulnerability
  2. the trivialness of exploiting the vulnerability
  3. the disclosure's detail

Award amounts will be easiest to assess on a case by case basis. Upon confirmation of a vulnerability, we agree to award responsible disclosures at minimum 100k sats and as high as the total potential loss that would result from exploiting the vulnerability.

Rules

  1. Disclosure is responsible and does not increase the likelihood of an exploit.
  2. Disclosure includes steps to reproduce.
  3. Disclosure includes a realistic attack scenario with prerequisites for an attack and expected gains after the exploitation. Disclosures without such scenario, with unrealistic assumptions or without meaningful outcomes will not be eligible for awards.
  4. You must be the first person to responsibly disclose the issue to be eligible for awards.

Development documentation awards

For significant changes to documentation, create an issue before making said changes. In such cases we will award documentation improvements in accordance with issue specification and PR awards.

For changes on the order of something like a typo, we'll award a nominal amount at our discretion.


Helpfulness awards

Like issue specification awards, helping fellow contributors substantially in a well documented manner such that the helped fellow contributes a merged PR is eligible for a one-time relative reward.

circumstances award
substantial and singular source of help 10%
substantial but nonsingular source of help 1-5%
source of relatively trivial help 1%

Contribution extras

We want to make contributing to SN as rewarding as possible, so we offer a few extras to contributors.

Dev chat

We self-host a private chat server for contributors to SN. If you'd like to join, please respond in this discussion.

Triage permissions

We offer triage permissions to contributors after they've made a few contributions. I'll usually add them as I notice people contributing, but if I missed you and you'd like to be added, let me know!

Contributor badges on SN profiles

Contributors can get badges on their SN profiles by opening a pull request adding their SN nym to the contributors.txt file.

What else you got

In the future we plan to offer more, like gratis github copilot subscriptions, reverse tunnels, codespaces, and merch.

If you'd like to see something added, please make a suggestion.


Development Tips


Linting

We use JavaScript Standard Style to enforce code style and correctness. You should run sndev lint before submitting a PR.

If you're using VSCode, you can install the StandardJS VSCode Extension extension to get linting in your editor. We also recommend installing StandardJS code snippets and StandardJS react code snippets for code snippets.


Database migrations

We use prisma for our database migrations. To create a new migration, modify prisma/schema.prisma according to prisma schema reference and apply it with:

./sndev prisma migrate dev

If you want to create a migration without applying it, eg to create a trigger or modify the generated sql before applying, use the --create-only option:

./sndev prisma migrate dev --create-only

Generate the local copy of the prisma ORM client in node_modules after changes. This should only be needed to get Intellisense in your editor locally.

./sndev prisma generate


Connecting to the local database

You can connect to the local database via ./sndev psql. psql is an interactive terminal for working with PostgreSQL.


Running cli on local lightning nodes

You can run lncli on the local lnd nodes via ./sndev cli lnd and ./sndev cli sn_lnd. The node for your local SN instance is sn_lnd and the node serving as any external node, like a stacker's node or external wallet, is lnd.

You can run lightning-cli on the local cln node via ./sndev cli cln which serves as an external node or wallet.


Testing local auth

You can login to test features like posting, replying, tipping, etc with ./sndev login <nym> which will provide a link to login as an existing nym or a new account for a nonexistent nym. But, it you want to test auth specifically you'll need to configure them in your .env file.

Login with Email

MailHog

  • The app is already prepared to send emails through MailHog so no extra configuration is needed
  • Click "sign up" and enter any email address (remember, it's not going anywhere beyond your workstation)
  • Access MailHog's web UI on http://localhost:8025
  • Click the link (looks like this):
http://localhost:3000/api/auth/callback/email?email=satoshi%40gmail.com&token=110e30a954ce7ca643379d90eb511640733de405f34a31b38eeda8e254d48cd7

Sendgrid

  • Create a Sendgrid account (or other smtp service)
LOGIN_EMAIL_SERVER=smtp://apikey:<sendgrid_api_key>@smtp.sendgrid.net:587
LOGIN_EMAIL_FROM=<sendgrid_email_from>
  • Click "sign up" and enter your email address
  • Check your email
  • Click the link (looks like this):
http://localhost:3000/api/auth/callback/email?email=satoshi%40gmail.com&token=110e30a954ce7ca643379d90eb511640733de405f34a31b38eeda8e254d48cd7

Login with Github

  • Create a new OAuth app in your Github account
    • Set the callback URL to: http://localhost:3000/api/auth/callback/github
  • Update your .env file
GITHUB_ID=<Client ID>
GITHUB_SECRET=<Client secret>
  • Signup and login as above

Login with Lightning

  • Use ngrok to create a HTTPS tunnel to localhost:3000
  • Update LNAUTH_URL in .env with the URL provided by ngrok and add /api/lnauth to it

Enabling web push notifications

To enable Web Push locally, you will need to set the VAPID_* env vars. VAPID_MAILTO needs to be an email address using the mailto: scheme. For NEXT_PUBLIC_VAPID_PUBKEY and VAPID_PRIVKEY, you can run npx web-push generate-vapid-keys.


Custom domains

Add or remove DNS records in local

A worker dedicated to verifying custom domains, checks, among other things, if a domain has the correct DNS records and values. This would normally require a real domain and access to its DNS configuration. Therefore we use dnsmasq to have local DNS, make sure you have enabled it.

To add a DNS record the syntax is the following:

./sndev domains dns add|remove cname|txt <name/domain> <value>

For TXT records, you can also use "" quoted strings on value.

To list all DNS records present in the dnsmasq config: ./sndev domains dns list

Access a local custom domain added via dnsmasq

sndev will use the dnsmasq DNS server by default, but chances are that you might want to access the domain via your browser.

For every edit on dnsmasq, it will give you the option to either edit the /etc/hosts file or use the dnsmasq DNS server which can be reached on 127.0.0.1:5353. You can avoid getting asked to edit the /etc/hosts file by adding the --no-hosts parameter.

Internals


Stack

The site is written in javascript (not typescript 😱) using Next.js, a React framework. The backend API is provided via GraphQL. The database is PostgreSQL modeled with Prisma. The job queue is also maintained in PostgreSQL. We use lnd for our lightning node. A customized Bootstrap theme is used for styling.


Services

Currently, SN runs and maintains two significant services and one microservice:

  1. the nextjs web app, found in ./
  2. the worker service, found in ./worker, which runs periodic jobs and jobs sent to it by the web app
  3. a screenshot microservice, found in ./capture, which takes screenshots of SN for social previews

In addition, we run other critical services the above services interact with like lnd, postgres, opensearch, tor, and s3.


Wallet transaction safety

To ensure stackers balances are kept sane, some wallet updates are run in serializable transactions at the database level. Because early versions of prisma had relatively poor support for transactions most wallet touching code is written in plpgsql stored procedures and can be found in the prisma/migrations folder.

UPDATE: Most wallet updates are now run in read committed transactions. See api/paidAction/README.md for more information.


Need help?

Open a discussion or issue or email us or request joining the dev chat.


Responsible disclosure

If you found a vulnerability, we would greatly appreciate it if you contact us via security@stacker.news or open a security advisory. Our PGP key can be found here (FEE1 E768 E0B3 81F5).


License

MIT

Languages
JavaScript 74.2%
PLpgSQL 20.9%
Shell 1.9%
CSS 1.6%
SCSS 1%
Other 0.4%