store: rename badge service to store service (#7987)

Co-authored-by: sh-agents <350651734+sh-agents@users.noreply.github.com>
This commit is contained in:
shandsh-agents authored and GitHub committed 2026-11-03 13:24:17 +00:00
1 parent 6f8ebda2c5
commit 2c09d06793
191 files changed
+1341 -1309

No files matched your search

+2 -2
View File
@@ -15,7 +15,7 @@ on:
- "apps/simplex-chat/**"
- "apps/simplex-bot/**"
- "apps/simplex-bot-advanced/**"
- "apps/simplex-badge-service/**"
- "apps/simplex-store-service/**"
- "apps/simplex-broadcast-bot/**"
- "apps/simplex-directory-service/**"
- "apps/multiplatform/**"
@@ -35,7 +35,7 @@ on:
- "packages/simplex-chat-client/types/typescript/**"
- "packages/simplex-chat-python/**"
- "scripts/ci/package-tests.sh"
- "apps/simplex-badge-service/web/**"
- "apps/simplex-store-service/web/**"
- "scripts/ci/packages_release.py"
- "scripts/ci/test_packages_release.py"
types: [opened, synchronize, reopened, ready_for_review]
+2
View File
@@ -88,4 +88,6 @@ website/test/stubs-layout-cache/_includes/*.js
apps/android/app/release
apps/multiplatform/.kotlin/sessions
# anywhere in the tree: this file holds a real BTCPay api_key and webhook_secret
store_service.ini
# a local ini under its name before the store service rename holds the same secrets
badge_service.ini
@@ -2,8 +2,8 @@
module Main where
import BadgeService.Options (BadgeServiceOpts (..))
import BadgeService.Service
import StoreService.Options (StoreServiceOpts (..))
import StoreService.Service
import Control.Logger.Simple (LogConfig (..), LogLevel (..), setLogLevel, withGlobalLogging)
import GHC.IO.Encoding (setLocaleEncoding)
import Simplex.Chat.Terminal (terminalChatConfig)
@@ -17,7 +17,7 @@ main = do
mapM_ (`hSetEncoding` utf8) [stdout, stderr]
withGlobalLogging LogConfig {lc_file = Nothing, lc_stderr = True} $ do
setLogLevel LogWarn
opts@BadgeServiceOpts {runCLI} <- welcomeGetOpts
opts@StoreServiceOpts {runCLI} <- welcomeGetOpts
if runCLI
then badgeServiceCLI opts
else newServiceState >>= badgeService opts terminalChatConfig
then storeServiceCLI opts
else newServiceState >>= storeService opts terminalChatConfig
@@ -1,8 +1,8 @@
# SimpleX badge service
# SimpleX store service
`simplex-badge-service` runs the whole supporter-badge service as one process, two
`simplex-store-service` runs the whole store service as one process, two
lanes: a SimpleX chat bot that answers service RPC over a double-ratchet contact
address, and — only when `--service-config` names a `badge_service.ini` — the badge-codes
address, and — only when `--service-config` names a `store_service.ini` — the badge-codes
web checkout (BTCPay and Stripe payment, code issuance, the poller). **Without
`--service-config` the web listener does not start at all**; the process still runs the
chat side and nothing else.
@@ -11,7 +11,7 @@ The wire protocol for the RPC side is
[`docs/protocol/badges-rpc.md`](../../docs/protocol/badges-rpc.md). The web checkout is
specified in
[`plans/badges-codes/2026-08-27-badge-codes.md`](../../plans/badges-codes/2026-08-27-badge-codes.md),
whose §9 is the `badge_service.ini` reference, with the implementation plan in
whose §9 is the `store_service.ini` reference, with the implementation plan in
[`plans/badges-codes/2026-08-31-service-btcpay.md`](../../plans/badges-codes/2026-08-31-service-btcpay.md).
Earlier plans (`2026-07-30-supporter-badges-v3-ux.md`, `2026-07-31-badges-core-implementation.md`,
`2026-08-04-badges-mvp-scope.md`) predate the web checkout and describe the RPC-only
@@ -37,13 +37,13 @@ purchase that already exists.
Build prerequisites and the general contribution flow are in [`docs/CONTRIBUTING.md`](../../docs/CONTRIBUTING.md).
```
cabal build exe:simplex-badge-service
cabal build exe:simplex-store-service
```
## Run
```
simplex-badge-service --help
simplex-store-service --help
```
- default (no `--run-cli`): background service mode, no interactive terminal.
@@ -62,7 +62,7 @@ The service checks the secret against the configured public key at that index an
if they disagree: credentials signed with the wrong key cannot be verified by any client, and the
codes redeemed against them would be spent for nothing.
The key can come from `badge_service.ini` instead:
The key can come from `store_service.ini` instead:
```ini
[issuer]
@@ -77,12 +77,12 @@ index it signs with at startup.
The command line wins over the file when both `--issuer-key-idx` and `--issuer-secret` are given.
Note that a secret passed as a flag is visible to every user on the machine through `ps`, where one
in the ini is only as readable as the file: `badge_service.ini` is gitignored and already holds the
in the ini is only as readable as the file: `store_service.ini` is gitignored and already holds the
provider API keys and webhook secrets.
Other options:
- `--service-config INI_FILE`: path to `badge_service.ini`. Omit it to run the chat/RPC side
- `--service-config INI_FILE`: path to `store_service.ini`. Omit it to run the chat/RPC side
only; the process never starts a web listener without it, and never starts one under
`--run-cli`, which parses and validates the whole file (`[listener] static_dir` included) but
uses only its `[issuer]`, `[apple]`, `[google]` and `[dev]` sections. An issuer key is
@@ -90,28 +90,28 @@ Other options:
- `--service-name NAME`: the bot's display name, without `*`s or spaces (default `SimpleX Badges`).
- `--client-service`: use the client service certificate.
- also accepts the standard SimpleX Chat core options — database path, SMP/XFTP servers,
`--socks-proxy`, `--log-level`/`-l`, and the rest — run `simplex-badge-service --help`
`--socks-proxy`, `--log-level`/`-l`, and the rest — run `simplex-store-service --help`
for the complete list.
### Running the web checkout
`badge_service.ini` holds the listener bind address and `static_dir`, an optional
`store_service.ini` holds the listener bind address and `static_dir`, an optional
`[btcpay]` section (omitting it disables Bitcoin and Monero), an optional `[stripe]`
section (omitting it disables card payments), an optional `[group]` section (omitting it
turns off the group's commands, though a group created earlier still has its code messages updated)
and the poll cadence.
`badge_service.ini.example` is the committed template; `badge_service.ini` itself is
`store_service.ini.example` is the committed template; `store_service.ini` itself is
gitignored, since a real one holds API keys and webhook secrets.
The full walkthrough is in
[`web/README.md`](web/README.md#running-the-real-service-against-this-build). Short version:
```
cd apps/simplex-badge-service/web && npm install && npm run build && cd ../../..
cp apps/simplex-badge-service/badge_service.ini.example apps/simplex-badge-service/badge_service.ini
cabal run simplex-badge-service -- \
cd apps/simplex-store-service/web && npm install && npm run build && cd ../../..
cp apps/simplex-store-service/store_service.ini.example apps/simplex-store-service/store_service.ini
cabal run simplex-store-service -- \
--issuer-key-idx IDX --issuer-secret SECRET \
--service-config apps/simplex-badge-service/badge_service.ini
--service-config apps/simplex-store-service/store_service.ini
```
`IDX` and `SECRET` must be one of the issuer keys clients already ship, not a fresh
@@ -221,14 +221,14 @@ account key, or either section beside
```ini
[apple]
bundle_id = chat.simplex.app
root_certificates = /etc/simplex-badge-service/AppleRootCA-G3.cer
root_certificates = /etc/simplex-store-service/AppleRootCA-G3.cer
api_key_id = 2X9R4HXF34
api_issuer_id = 57246542-96fe-1a63-e053-0824d011072a
api_private_key_file = /etc/simplex-badge-service/AuthKey_2X9R4HXF34.p8
api_private_key_file = /etc/simplex-store-service/AuthKey_2X9R4HXF34.p8
[google]
package_name = chat.simplex.app
service_account_file = /etc/simplex-badge-service/play-service-account.json
service_account_file = /etc/simplex-store-service/play-service-account.json
```
- `[apple]` verifies the signed transaction offline, against the roots `root_certificates` lists,
@@ -407,6 +407,36 @@ credits this way. Nothing tells a production `[google]` from a test one, so neve
beside the production Play app's `[google]`, or every licence tester the Play Console lists gets a
badge without paying.
## Deployment
### Upgrading from the badge service
The rename to StoreService changed what the operator runs:
| Before | After |
|---|---|
| `scripts/badge-service/` | `scripts/store-service/` |
| compose service `badge-service`, image `simplex-badge-service` | compose service `store-service`, image `simplex-store-service` |
| `badge_service.ini` | `store_service.ini` |
| the folder `config`, mounted read-only at `/etc/simplex-badge-service` (before it, `badge_service.ini` alone, mounted at `/etc/simplex-badge-service/badge_service.ini`) | the folder `config`, mounted read-only at `/etc/simplex-store-service` |
| `[apple] root_certificates` and `[google] service_account_file` under `/etc/simplex-badge-service/` | the same files under `/etc/simplex-store-service/` |
| the binary `simplex-badge-service` | `simplex-store-service` |
Move `scripts/badge-service/config/` to `scripts/store-service/config/` (a deployment from before
the config folder creates it and moves `badge_service.ini` into it), rename `badge_service.ini` in it
to `store_service.ini`, and change its paths as the table says, the
`/etc/simplex-badge-service/` files under `[apple]` and `[google]` among them. Point Caddy's badges root at
`scripts/store-service/web`, which the service fills at boot. Then start the new service with
```
docker compose up -d --build --remove-orphans
```
from `scripts/store-service/`. Without `--remove-orphans` the old `badge-service` container keeps
running beside the new one, on the same port and database. The database `badge_service`,
`BADGE_DB_CONN`, the `sx_badge_service_` tables and the chat database prefix
`simplex_badge_service` are unchanged.
## Issuing codes
Operators issue codes two ways: from the service's own command line in `--run-cli` mode, and from the
@@ -448,7 +478,7 @@ why issuing codes lives in the service rather than in core.
### From the group
With `[group]` in `badge_service.ini`, the service manages one group and serves three commands in
With `[group]` in `store_service.ini`, the service manages one group and serves three commands in
it: `/issue <type> [months <M>] [uses <N>]` and `/bulk <type> [months <M>] count <B>` for moderators
and above, `/revoke <code>` for admins and owners. `months` is 1 to 255, `uses` 1 to 1000 and
`count` 1 to 100; a value outside these gets the usage reply. A member's role is checked as the
@@ -3,7 +3,7 @@
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
module BadgeService.Catalog
module StoreService.Catalog
( OfferInvalid (..),
CatalogRefusal (..),
offerTotal,
@@ -22,7 +22,7 @@ import Data.Text (Text)
import Data.Time.Clock (UTCTime)
import Data.Word (Word32, Word64, Word8)
import Simplex.Chat.Badges (BadgeType (..))
import Simplex.Chat.Badges.Service (BadgeOffer (..), BadgePrice (..))
import Simplex.Chat.StoreService (BadgeOffer (..), BadgePrice (..))
import Simplex.Chat.Badges.Types (BadgeItemStatus (..), BadgeOfferId (..), BadgePriceId (..), OfferDiscount (..))
import Simplex.Chat.PaymentService.Types (CurrencyAmount (..), PaymentProvider (..))
@@ -1,7 +1,7 @@
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
module BadgeService.Codes
module StoreService.Codes
( issueOneCode,
issueFailedText,
revokeBadgeCode,
@@ -9,8 +9,8 @@ module BadgeService.Codes
)
where
import BadgeService.Store (RevokeResult, insertBadgeCode, revokeCode)
import BadgeService.Store.Invoices (truncateToSecond)
import StoreService.Store (RevokeResult, insertBadgeCode, revokeCode)
import StoreService.Store.Invoices (truncateToSecond)
import Data.Int (Int64)
import Data.Text (Text)
import Data.Time.Clock (getCurrentTime)
@@ -3,7 +3,7 @@
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module BadgeService.Config
module StoreService.Config
( ListenerConfig (..),
BTCPayConfig (..),
StripeConfig (..),
@@ -24,7 +24,7 @@ module BadgeService.Config
where
import qualified Control.Exception as E
import BadgeService.Log (logWarn)
import StoreService.Log (logWarn)
import Control.Monad (mfilter, unless, when)
import Data.Attoparsec.Text (Parser, endOfInput, isEndOfLine, parseOnly, satisfy, skipMany, skipSpace, skipWhile)
import qualified Data.ByteString.Char8 as B
@@ -5,7 +5,7 @@
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-ambiguous-fields #-}
module BadgeService.Group
module StoreService.Group
( ensureManagedGroup,
runGroupLane,
inertGroupConfig,
@@ -24,12 +24,12 @@ module BadgeService.Group
)
where
import BadgeService.Codes (issueFailedText, issueOneCode, revokeBadgeCode, singleUse)
import BadgeService.Config (GroupConfig (..))
import BadgeService.Group.Command (CmdAction (..), GroupCmd (..), groupCmdAction, groupCommands)
import BadgeService.Log (logError, logInfo, logWarn)
import BadgeService.Store (CodeTracker (..), ManagedGroup (..), RevokeResult (..), clearCodeGroupItems, getCodeTracker, getEditableTrackers, getManagedGroup, insertManagedGroup, markOwnerBootstrapped, setCodeGroupItem)
import BadgeService.Store.Invoices (truncateToSecond)
import StoreService.Codes (issueFailedText, issueOneCode, revokeBadgeCode, singleUse)
import StoreService.Config (GroupConfig (..))
import StoreService.Group.Command (CmdAction (..), GroupCmd (..), groupCmdAction, groupCommands)
import StoreService.Log (logError, logInfo, logWarn)
import StoreService.Store (CodeTracker (..), ManagedGroup (..), RevokeResult (..), clearCodeGroupItems, getCodeTracker, getEditableTrackers, getManagedGroup, insertManagedGroup, markOwnerBootstrapped, setCodeGroupItem)
import StoreService.Store.Invoices (truncateToSecond)
import Control.Concurrent.STM (TQueue, atomically, flushTQueue, readTQueue, readTVarIO, writeTQueue)
import Control.Monad (forM_, forever, mfilter, replicateM, unless, void)
import Control.Monad.Except (runExceptT)
@@ -2,7 +2,7 @@
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
module BadgeService.Group.Command
module StoreService.Group.Command
( GroupCmd (..),
CmdAction (..),
groupCmdAction,
@@ -1,7 +1,7 @@
{-# LANGUAGE OverloadedStrings #-}
-- | The SMP agent logs unconditionally at info on the global logger, so the service keeps its own info lines on this separate channel when that logger is raised to Warn.
module BadgeService.Log
module StoreService.Log
( logInfo,
logWarn,
logError,
@@ -2,7 +2,7 @@
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module BadgeService.Names.Chain
module StoreService.Names.Chain
( ChainClient (..),
ChainError (..),
TxHash (..),
@@ -11,7 +11,7 @@ module BadgeService.Names.Chain
)
where
import BadgeService.Names.Registration (RegisterIntent, commitCalldata, registerWithCreditCalldata)
import StoreService.Names.Registration (RegisterIntent, commitCalldata, registerWithCreditCalldata)
import Control.Concurrent.STM (TVar)
import Control.Exception (try)
import Control.Monad.Except (ExceptT, liftEither, runExceptT, throwError)
@@ -2,7 +2,7 @@
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
module BadgeService.Names.Registration
module StoreService.Names.Registration
( Registration (..),
RegisterIntent (..),
sponsorDomain,
@@ -3,15 +3,15 @@
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
module BadgeService.Options
( BadgeServiceOpts (..),
getBadgeServiceOpts,
badgeServiceOpts,
module StoreService.Options
( StoreServiceOpts (..),
getStoreServiceOpts,
storeServiceOpts,
mkChatOpts,
)
where
import BadgeService.Config (BadgeIssuerKey (..))
import StoreService.Config (BadgeIssuerKey (..))
import qualified Data.ByteString.Char8 as B
import qualified Data.Text as T
import Options.Applicative
@@ -19,7 +19,7 @@ import Simplex.Chat.Controller (updateStr, versionNumber, versionString)
import Simplex.Chat.Options (ChatCmdLog (..), ChatOpts (..), CoreChatOpts, CreateBotOpts (..), coreChatOptsP)
import Simplex.Messaging.Encoding.String (strDecode)
data BadgeServiceOpts = BadgeServiceOpts
data StoreServiceOpts = StoreServiceOpts
{ coreOptions :: CoreChatOpts,
serviceName :: T.Text,
clientService :: Bool,
@@ -30,14 +30,14 @@ data BadgeServiceOpts = BadgeServiceOpts
testing :: Bool
}
badgeServiceOpts :: FilePath -> FilePath -> Parser BadgeServiceOpts
badgeServiceOpts appDir defaultDbName = do
storeServiceOpts :: FilePath -> FilePath -> Parser StoreServiceOpts
storeServiceOpts appDir defaultDbName = do
coreOptions <- coreChatOptsP appDir defaultDbName
serviceName <-
strOption
( long "service-name"
<> metavar "SERVICE_NAME"
<> help "The display name of the badge service bot, without *'s and spaces (SimpleX Badges)"
<> help "The display name of the store service bot, without *'s and spaces (SimpleX Badges)"
<> value "SimpleX Badges"
)
clientService <-
@@ -53,14 +53,14 @@ badgeServiceOpts appDir defaultDbName = do
runCLI <-
switch
( long "run-cli"
<> help "Run badge service as CLI"
<> help "Run store service as CLI"
)
serviceConfigFile <-
optional
( strOption
( long "service-config"
<> metavar "INI_FILE"
<> help "Path to badge_service.ini: parsed in full in every mode, but --run-cli starts no web listener"
<> help "Path to store_service.ini: parsed in full in every mode, but --run-cli starts no web listener"
)
)
issuerKeyIdx <-
@@ -80,7 +80,7 @@ badgeServiceOpts appDir defaultDbName = do
<> help "Issuer secret from `simplex-chat badge keygen` (base64url)"
)
pure
BadgeServiceOpts
StoreServiceOpts
{ coreOptions,
serviceName = T.pack serviceName,
clientService,
@@ -94,19 +94,19 @@ badgeServiceOpts appDir defaultDbName = do
testing = False
}
getBadgeServiceOpts :: FilePath -> FilePath -> IO BadgeServiceOpts
getBadgeServiceOpts appDir defaultDbName =
getStoreServiceOpts :: FilePath -> FilePath -> IO StoreServiceOpts
getStoreServiceOpts appDir defaultDbName =
execParser $
info
(helper <*> versionOption <*> badgeServiceOpts appDir defaultDbName)
(header versionStr <> fullDesc <> progDesc "Start SimpleX Badge Service with DB_FILE options")
(helper <*> versionOption <*> storeServiceOpts appDir defaultDbName)
(header versionStr <> fullDesc <> progDesc "Start SimpleX Store Service with DB_FILE options")
where
versionStr = versionString versionNumber
versionOption = infoOption versionAndUpdate (long "version" <> short 'v' <> help "Show version")
versionAndUpdate = versionStr <> "\n" <> updateStr
mkChatOpts :: BadgeServiceOpts -> ChatOpts
mkChatOpts BadgeServiceOpts {coreOptions, serviceName, clientService} =
mkChatOpts :: StoreServiceOpts -> ChatOpts
mkChatOpts StoreServiceOpts {coreOptions, serviceName, clientService} =
ChatOpts
{ coreOptions,
chatCmd = "",
@@ -2,11 +2,11 @@
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
module BadgeService.Orders (settleOrder, decide, codeLifetime) where
module StoreService.Orders (settleOrder, decide, codeLifetime) where
import BadgeService.Providers (Funded (..), PaymentSignal (..), Received (..))
import BadgeService.Store.Invoices (InvoicePayment (..), InvoiceRow (..), markCodePaid, paymentStatusText, settlementCodeHash, settlementInvoice, truncateToSecond, updateInvoiceStatus, upsertPayment)
import BadgeService.Waiters (Waiters, publish, publishPayment)
import StoreService.Providers (Funded (..), PaymentSignal (..), Received (..))
import StoreService.Store.Invoices (InvoicePayment (..), InvoiceRow (..), markCodePaid, paymentStatusText, settlementCodeHash, settlementInvoice, truncateToSecond, updateInvoiceStatus, upsertPayment)
import StoreService.Waiters (Waiters, publish, publishPayment)
import Control.Concurrent.STM (atomically)
import Control.Monad (when)
import Data.ByteString (ByteString)
@@ -4,7 +4,7 @@
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module BadgeService.Poller
module StoreService.Poller
( PollerEnv (..),
ReadHints,
newReadHints,
@@ -27,14 +27,14 @@ module BadgeService.Poller
)
where
import BadgeService.Config (PollConfig (..))
import BadgeService.Orders (decide, settleOrder)
import BadgeService.Providers (ListPass (..), PaymentSignal (..), Provider (..), ProviderError (..), Received (..), expiresItself, settleWindow)
import BadgeService.Store.Invoices (InvoiceRow (..), OverdueInvoice (..), expireOverdue, getInvoiceByProviderRef, overdueInvoices, unpaidRefs)
import BadgeService.Waiters (Waiters, publish, waitingCount, waitingCountSTM)
import StoreService.Config (PollConfig (..))
import StoreService.Orders (decide, settleOrder)
import StoreService.Providers (ListPass (..), PaymentSignal (..), Provider (..), ProviderError (..), Received (..), expiresItself, settleWindow)
import StoreService.Store.Invoices (InvoiceRow (..), OverdueInvoice (..), expireOverdue, getInvoiceByProviderRef, overdueInvoices, unpaidRefs)
import StoreService.Waiters (Waiters, publish, waitingCount, waitingCountSTM)
import Control.Concurrent.STM
import Control.Exception (SomeAsyncException, SomeException, fromException, throwIO, try)
import BadgeService.Log (logError, logInfo, logWarn)
import StoreService.Log (logError, logInfo, logWarn)
import Control.Monad (filterM, forever, unless, void, when)
import Data.List (find, partition, sortOn)
import Data.Map.Strict (Map)
@@ -1,7 +1,7 @@
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
module BadgeService.Providers
module StoreService.Providers
( ProviderError (..),
WebhookError (..),
Received (..),
@@ -3,7 +3,7 @@
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module BadgeService.Providers.BTCPay
module StoreService.Providers.BTCPay
( btcpayProvider,
btcMethodId,
xmrMethodId,
@@ -16,8 +16,8 @@ module BadgeService.Providers.BTCPay
)
where
import BadgeService.Config (BTCPayConfig (..), speedPolicyName)
import BadgeService.Providers
import StoreService.Config (BTCPayConfig (..), speedPolicyName)
import StoreService.Providers
( ListPass (..),
OrderDraft (..),
PaymentSignal (..),
@@ -30,7 +30,7 @@ import BadgeService.Providers
WebhookError (..),
)
import Control.Exception (try)
import BadgeService.Log (logError, logInfo, logWarn)
import StoreService.Log (logError, logInfo, logWarn)
import Control.Monad (unless)
import Crypto.Hash (Digest, SHA256)
import Crypto.MAC.HMAC (HMAC, hmac, hmacGetDigest)
@@ -3,15 +3,15 @@
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module BadgeService.Providers.Stripe
module StoreService.Providers.Stripe
( stripeProvider,
signalOf,
IntentRead (..),
)
where
import BadgeService.Config (StripeConfig (..))
import BadgeService.Providers
import StoreService.Config (StripeConfig (..))
import StoreService.Providers
( ListPass (..),
OrderDraft (..),
PaymentSignal (..),
@@ -4,15 +4,15 @@
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
module BadgeService.Service
module StoreService.Service
( ServiceState (..),
newServiceState,
configureStoreVerifier,
welcomeGetOpts,
checkIssuerKey,
badgeService,
badgeServiceCLI,
badgeServiceResponse,
storeService,
storeServiceCLI,
storeServiceResponse,
RequestLane (..),
requestLane,
PurchaseChecks (..),
@@ -35,25 +35,25 @@ module BadgeService.Service
)
where
import BadgeService.Catalog (StoreProduct (..), defaultCatalog, storeProduct)
import BadgeService.Codes (issueFailedText, issueOneCode, singleUse)
import BadgeService.Config (AppleStoreConfig (..), BadgeIssuerKey (..), PlayStoreConfig (..), ServiceConfig (..), readServiceConfig)
import BadgeService.Group (GroupEvent, ensureManagedGroup, groupEvent, hasTracker, refreshTracker, revokeWithTracker, runGroupLane)
import BadgeService.Group.Command (badgeTypeP, codeP, maxMonths, textTokenP)
import BadgeService.Log (logError, logInfo, logWarn)
import BadgeService.Options
import BadgeService.Poller (newPollerEnv, newReadHints, runPoller)
import BadgeService.Providers.BTCPay (btcpayProvider)
import BadgeService.Providers.Stripe (stripeProvider)
import BadgeService.Store
import BadgeService.Store.Invoices (seedCatalog, truncateToSecond)
import BadgeService.Store.Migrate (runBadgeServiceMigrations)
import BadgeService.StoreReceipts
import BadgeService.StoreReceipts.Apple (appleSubscriptionChecker, readAppleRoot, verifyAppleTransaction)
import BadgeService.StoreReceipts.Google (PlayVerifier (..), playStoreVerifier)
import BadgeService.StoreReceipts.Mock (newMockStoreVerifier)
import BadgeService.Waiters (Waiters, newWaiters)
import BadgeService.Web.Server (Bucket, exportWebapp, newWebEnv, runWebListener, takeFrom)
import StoreService.Catalog (StoreProduct (..), defaultCatalog, storeProduct)
import StoreService.Codes (issueFailedText, issueOneCode, singleUse)
import StoreService.Config (AppleStoreConfig (..), BadgeIssuerKey (..), PlayStoreConfig (..), ServiceConfig (..), readServiceConfig)
import StoreService.Group (GroupEvent, ensureManagedGroup, groupEvent, hasTracker, refreshTracker, revokeWithTracker, runGroupLane)
import StoreService.Group.Command (badgeTypeP, codeP, maxMonths, textTokenP)
import StoreService.Log (logError, logInfo, logWarn)
import StoreService.Options
import StoreService.Poller (newPollerEnv, newReadHints, runPoller)
import StoreService.Providers.BTCPay (btcpayProvider)
import StoreService.Providers.Stripe (stripeProvider)
import StoreService.Store
import StoreService.Store.Invoices (seedCatalog, truncateToSecond)
import StoreService.Store.Migrate (runStoreServiceMigrations)
import StoreService.StoreReceipts
import StoreService.StoreReceipts.Apple (appleSubscriptionChecker, readAppleRoot, verifyAppleTransaction)
import StoreService.StoreReceipts.Google (PlayVerifier (..), playStoreVerifier)
import StoreService.StoreReceipts.Mock (newMockStoreVerifier)
import StoreService.Waiters (Waiters, newWaiters)
import StoreService.Web.Server (Bucket, exportWebapp, newWebEnv, runWebListener, takeFrom)
import Control.Applicative (optional)
import Control.Concurrent.STM
import Control.Monad
@@ -73,7 +73,7 @@ import Data.Word (Word32)
import Simplex.Chat.Badges
import Simplex.Chat.Badges.Code
import Simplex.Chat.Badges.Ledger
import Simplex.Chat.Badges.Service
import Simplex.Chat.StoreService
import Simplex.Chat.Badges.StorePlan (storePlan)
import Simplex.Chat.Badges.Types (BadgeCodePaymentStatus (..))
import Simplex.Chat.Bot (initializeBotAddress')
@@ -103,7 +103,7 @@ data ServiceState = ServiceState
storeVerifier :: StoreVerifier
}
-- | With no store verifier, which badge_service.ini configures, every store receipt not already credited
-- | With no store verifier, which store_service.ini configures, every store receipt not already credited
-- is answered provider_not_configured.
newServiceState :: IO ServiceState
newServiceState = do
@@ -112,22 +112,22 @@ newServiceState = do
groupEventQ <- newTQueueIO
pure ServiceState {serviceCC, serviceRequestQ, groupEventQ, storeVerifier = noStoreVerifier}
welcomeGetOpts :: IO BadgeServiceOpts
welcomeGetOpts :: IO StoreServiceOpts
welcomeGetOpts = do
appDir <- getAppUserDataDirectory "simplex"
opts@BadgeServiceOpts {coreOptions, testing, serviceName} <- getBadgeServiceOpts appDir "simplex_badge_service"
opts@StoreServiceOpts {coreOptions, testing, serviceName} <- getStoreServiceOpts appDir "simplex_badge_service"
unless testing $ do
putStrLn $ "SimpleX Badge Service v" ++ versionNumber
putStrLn $ "SimpleX Store Service v" ++ versionNumber
printDbOpts coreOptions
putStrLn $ "Service name: " ++ T.unpack serviceName
pure opts
checkIssuerKey :: BadgeServiceOpts -> Maybe ServiceConfig -> ChatConfig -> IO (Either String BadgeIssuerKey)
checkIssuerKey BadgeServiceOpts {issuerKey} serviceCfg cfg = case issuerKey of
checkIssuerKey :: StoreServiceOpts -> Maybe ServiceConfig -> ChatConfig -> IO (Either String BadgeIssuerKey)
checkIssuerKey StoreServiceOpts {issuerKey} serviceCfg cfg = case issuerKey of
Left e -> pure (Left e)
Right (Just k) -> checkOne cfg k
Right Nothing -> case serviceCfg >>= issuer of
Nothing -> pure $ Left "an issuer key is required - pass --issuer-key-idx and --issuer-secret, or add an [issuer] section to badge_service.ini (see `simplex-chat badge keygen`)"
Nothing -> pure $ Left "an issuer key is required - pass --issuer-key-idx and --issuer-secret, or add an [issuer] section to store_service.ini (see `simplex-chat badge keygen`)"
Just k -> checkOne cfg k
checkOne :: ChatConfig -> BadgeIssuerKey -> IO (Either String BadgeIssuerKey)
@@ -139,7 +139,7 @@ checkOne ChatConfig {badgePublicKeys} k@BadgeIssuerKey {keyIdx, secretKey} =
Just _ -> Left $ "issuer secret does not match the configured key at index " <> show keyIdx <> ", its public key is " <> T.unpack (safeDecodeUtf8 $ strEncode pk)
Nothing -> Left $ "no configured badge key at index " <> show keyIdx <> ", clients could not verify what this service signs"
requireIssuerKey :: BadgeServiceOpts -> Maybe ServiceConfig -> ChatConfig -> IO BadgeIssuerKey
requireIssuerKey :: StoreServiceOpts -> Maybe ServiceConfig -> ChatConfig -> IO BadgeIssuerKey
requireIssuerKey opts serviceCfg cfg =
checkIssuerKey opts serviceCfg cfg >>= either (\e -> putStrLn ("Error: " <> e) >> exitFailure) (\k@BadgeIssuerKey {keyIdx} -> logInfo ("signing badges with issuer key " <> tshow keyIdx) $> k)
@@ -191,8 +191,8 @@ configureStoreVerifier serviceCfg env@ServiceState {serviceCC, storeVerifier = v
orExit = (>>= either (\e -> putStrLn ("Error: " <> e) >> exitFailure) pure)
notConfigured = pure $ Left SRNotConfigured
badgeService :: BadgeServiceOpts -> ChatConfig -> ServiceState -> IO ()
badgeService opts@BadgeServiceOpts {serviceConfigFile} cfg env = do
storeService :: StoreServiceOpts -> ChatConfig -> ServiceState -> IO ()
storeService opts@StoreServiceOpts {serviceConfigFile} cfg env = do
serviceCfg <- traverse readConfigOrExit serviceConfigFile
key <- requireIssuerKey opts serviceCfg cfg
waiters <- newWaiters
@@ -243,8 +243,8 @@ seedServiceCatalog st = do
"badge catalog: " <> tshow (length prices) <> " prices and " <> tshow (length offers) <> " offers compiled in, "
<> tshow seededPrices <> " prices and " <> tshow seededOffers <> " offers inserted"
badgeServiceCLI :: BadgeServiceOpts -> IO ()
badgeServiceCLI opts@BadgeServiceOpts {serviceConfigFile} = do
storeServiceCLI :: StoreServiceOpts -> IO ()
storeServiceCLI opts@StoreServiceOpts {serviceConfigFile} = do
serviceCfg <- traverse readConfigOrExit serviceConfigFile
key <- requireIssuerKey opts serviceCfg terminalChatConfig
env <- newServiceState >>= configureStoreVerifier serviceCfg
@@ -343,13 +343,13 @@ data RequestLane = MainLane | PurchaseLane | RenewalLane
-- purchase's row lock before re-reading the tip, so the lanes may run concurrently at any --pool-size.
requestLane :: StoreChecks -> ChatController -> Maybe C.PublicKeyEd25519 -> J.Object -> IO RequestLane
requestLane checks cc sigKey reqData = case J.fromJSON (J.Object reqData) of
J.Success BadgeServiceRequest {request = BSCPurchaseBadge {payment = SPGoogle {}, upgrade = Nothing}} -> pure PurchaseLane
J.Success BadgeServiceRequest {request = BSCPurchaseBadge {payment = SPApple {jws}, upgrade = Nothing}}
J.Success StoreServiceRequest {request = STCPurchaseBadge {payment = SPGoogle {}, upgrade = Nothing}} -> pure PurchaseLane
J.Success StoreServiceRequest {request = STCPurchaseBadge {payment = SPApple {jws}, upgrade = Nothing}}
| maybe False autoRenewable (appleTransactionFacts jws) -> pure PurchaseLane
J.Success BadgeServiceRequest {request = BSCTransferBadge {payment = SPApple {jws}}}
J.Success StoreServiceRequest {request = STCTransferBadge {payment = SPApple {jws}}}
| maybe False autoRenewable (appleTransactionFacts jws) -> pure PurchaseLane
J.Success BadgeServiceRequest {request = BSCTransferBadge {payment = SPGoogle {}}} -> pure PurchaseLane
J.Success BadgeServiceRequest {purchaseKey = Just k, request = BSCIssueBadge {}}
J.Success StoreServiceRequest {request = STCTransferBadge {payment = SPGoogle {}}} -> pure PurchaseLane
J.Success StoreServiceRequest {purchaseKey = Just k, request = STCIssueBadge {}}
| sigKey == Just k -> do
now <- badgeNow cc
withDB' "requestLane" cc (\db -> getIssuePurchase db k) <&> \case
@@ -359,7 +359,7 @@ requestLane checks cc sigKey reqData = case J.fromJSON (J.Object reqData) of
Right _ -> MainLane
-- a read that failed may hide a due check, and the main lane is what must not wait on a store
Left _ -> RenewalLane
J.Success BadgeServiceRequest {purchaseKey = Just k, request = BSCUpgradeBadgeSubscription {}}
J.Success StoreServiceRequest {purchaseKey = Just k, request = STCUpgradeBadgeSubscription {}}
| sigKey == Just k -> do
now <- badgeNow cc
withDB' "requestLane" cc (\db -> getIssuePurchase db k) <&> \case
@@ -376,14 +376,14 @@ routeLookahead = 60
-- | Cancellation is rethrown, since that is how the race stops this thread. The
-- exception itself is not logged: it can quote the request, which carries codes and store receipts.
survive :: T.Text -> IO () -> IO ()
survive what action = action `catchOwn'` \_ -> logError $ "badge service: " <> what <> " failed; the next one will be handled"
survive what action = action `catchOwn'` \_ -> logError $ "store service: " <> what <> " failed; the next one will be handled"
badgePreStartHook :: BadgeServiceOpts -> ChatController -> IO ()
badgePreStartHook :: StoreServiceOpts -> ChatController -> IO ()
badgePreStartHook opts ChatController {config, chatStore} =
runBadgeServiceMigrations opts config chatStore
runStoreServiceMigrations opts config chatStore
badgePostStartHook :: BadgeServiceOpts -> ServiceState -> ChatController -> IO ()
badgePostStartHook BadgeServiceOpts {noAddress, testing} env cc = do
badgePostStartHook :: StoreServiceOpts -> ServiceState -> ChatController -> IO ()
badgePostStartHook StoreServiceOpts {noAddress, testing} env cc = do
-- Core starts this False and gates service request delivery on it, so the hook must set it.
atomically $ writeTVar (processServiceRequests cc) True
readTVarIO (currentUser cc) >>= \case
@@ -396,70 +396,70 @@ badgePostStartHook BadgeServiceOpts {noAddress, testing} env cc = do
handleServiceRequest :: BadgeIssuerKey -> StoreVerifier -> PurchaseChecks -> ChatController -> Maybe (TQueue GroupEvent) -> User -> AgentInvId -> Maybe C.PublicKeyEd25519 -> J.Object -> IO ()
handleServiceRequest key verifier checks cc trackerQ_ User {userId} reqId sigKey reqData = do
let reqIdT = safeDecodeUtf8 (strEncode reqId)
logInfo $ "badge service request " <> reqIdT
logInfo $ "store service request " <> reqIdT
resp <-
badgeServiceResponse key verifier checks cc trackerQ_ sigKey reqData `catchOwn'` \_ ->
logError ("badge service request " <> reqIdT <> " failed") $> errorResponse BSEInternal
storeServiceResponse key verifier checks cc trackerQ_ sigKey reqData `catchOwn'` \_ ->
logError ("store service request " <> reqIdT <> " failed") $> errorResponse STEInternal
logInfo $ "badge answer: " <> responseName resp
sendChatCmd cc (APISendServiceResponse userId reqId (responseObject resp)) >>= \case
Right _ -> pure ()
Left e -> logError $ "badge service response failed for " <> reqIdT <> ": " <> tshow e
Left e -> logError $ "store service response failed for " <> reqIdT <> ": " <> tshow e
responseObject :: BadgeServiceResponse -> J.Object
responseObject :: StoreServiceResponse -> J.Object
responseObject r = case J.toJSON r of
J.Object o -> o
_ -> KM.fromList [("type", J.String "error"), ("code", J.toJSON BSEInternal)]
_ -> KM.fromList [("type", J.String "error"), ("code", J.toJSON STEInternal)]
errorResponse :: BadgeServiceErrorCode -> BadgeServiceResponse
errorResponse code = BSPError {code, message = Nothing, retryAfter = badgeErrorRetryAfter code}
errorResponse :: StoreServiceErrorCode -> StoreServiceResponse
errorResponse code = STPError {code, message = Nothing, retryAfter = badgeErrorRetryAfter code}
badgeErrorRetryAfter :: BadgeServiceErrorCode -> Maybe Word32
badgeErrorRetryAfter :: StoreServiceErrorCode -> Maybe Word32
badgeErrorRetryAfter = \case
BSEPaymentPending -> Just 300
BSEProviderUnavailable -> Just 300
BSERateLimited -> Just 60
STEPaymentPending -> Just 300
STEProviderUnavailable -> Just 300
STERateLimited -> Just 60
_ -> Nothing
-- | The agent verified the signature, so sigKey is a key the sender holds; a differing purchaseKey would let a client claim a purchase it cannot sign for.
badgeServiceResponse :: BadgeIssuerKey -> StoreVerifier -> PurchaseChecks -> ChatController -> Maybe (TQueue GroupEvent) -> Maybe C.PublicKeyEd25519 -> J.Object -> IO BadgeServiceResponse
badgeServiceResponse key verifier checks cc trackerQ_ sigKey reqData = case J.fromJSON (J.Object reqData) of
J.Error _ -> pure $ errorResponse BSEBadRequest
J.Success BadgeServiceRequest {version, purchaseKey, request}
| not (version `isCompatible` supportedBadgeServiceVRange) -> pure $ errorResponse BSEUnsupportedVersion
| purchaseKey /= sigKey -> pure $ errorResponse BSEBadRequest
storeServiceResponse :: BadgeIssuerKey -> StoreVerifier -> PurchaseChecks -> ChatController -> Maybe (TQueue GroupEvent) -> Maybe C.PublicKeyEd25519 -> J.Object -> IO StoreServiceResponse
storeServiceResponse key verifier checks cc trackerQ_ sigKey reqData = case J.fromJSON (J.Object reqData) of
J.Error _ -> pure $ errorResponse STEBadRequest
J.Success StoreServiceRequest {version, purchaseKey, request}
| not (version `isCompatible` supportedStoreServiceVRange) -> pure $ errorResponse STEUnsupportedVersion
| purchaseKey /= sigKey -> pure $ errorResponse STEBadRequest
| otherwise -> logInfo ("badge request: " <> commandName request) >> case request of
BSCRedeemBadgeCode {masterKey, code} -> case purchaseKey of
STCRedeemBadgeCode {masterKey, code} -> case purchaseKey of
Just k -> redeemCode key cc trackerQ_ k masterKey code
Nothing -> pure $ errorResponse BSEBadRequest
BSCPurchaseBadge {masterKey, payment, upgrade}
Nothing -> pure $ errorResponse STEBadRequest
STCPurchaseBadge {masterKey, payment, upgrade}
| Just receipt_ <- toStoreReceipt verifier payment -> case (purchaseKey, upgrade) of
(Just k, Nothing) -> either storeRefusalResponse (purchaseWithReceipt key cc verifier checks RUPurchase k masterKey) receipt_
-- store upgrades are not built, and ignoring one would credit its months at the discounted price
(Just _, Just _) -> pure $ errorResponse BSEBadRequest
(Nothing, _) -> pure $ errorResponse BSEBadRequest
BSCIssueBadge {balance} -> case purchaseKey of
(Just _, Just _) -> pure $ errorResponse STEBadRequest
(Nothing, _) -> pure $ errorResponse STEBadRequest
STCIssueBadge {balance} -> case purchaseKey of
Just k -> issueBadgeCmd key cc verifier k Nothing balance
Nothing -> pure $ errorResponse BSEBadRequest
Nothing -> pure $ errorResponse STEBadRequest
-- only an App Store subscription changes tier on the same transaction; Play gives a change a new token
BSCUpgradeBadgeSubscription {payment = payment@SPApple {}, balance}
STCUpgradeBadgeSubscription {payment = payment@SPApple {}, balance}
| Just k <- purchaseKey,
Just receipt_ <- toStoreReceipt verifier payment ->
either storeRefusalResponse (upgradeSubscriptionCmd key cc verifier k balance) receipt_
BSCUpgradeBadgeSubscription {} -> pure $ errorResponse BSEBadRequest
BSCTransferBadge {masterKey, payment}
STCUpgradeBadgeSubscription {} -> pure $ errorResponse STEBadRequest
STCTransferBadge {masterKey, payment}
| Just k <- purchaseKey,
Just receipt_ <- toStoreReceipt verifier payment ->
either storeRefusalResponse (purchaseWithReceipt key cc verifier checks (RUTransfer $ presentedTransaction payment) k masterKey) receipt_
BSCTransferBadge {} -> pure $ errorResponse BSEBadRequest
STCTransferBadge {} -> pure $ errorResponse STEBadRequest
-- Every command but redeemBadgeCode and purchaseBadge from a store needs a key the service already knows; those two create the purchase, so their key is unknown on a first purchase.
_ -> case purchaseKey of
Nothing -> pure $ errorResponse BSEUnsupportedVersion
Nothing -> pure $ errorResponse STEUnsupportedVersion
Just k ->
withDB' "purchaseKeyExists" cc (`purchaseKeyExists` k) >>= \case
Right True -> pure $ errorResponse BSEUnsupportedVersion
Right False -> pure $ errorResponse BSEUnknownPurchaseKey
Left _ -> pure $ errorResponse BSEInternal
Right True -> pure $ errorResponse STEUnsupportedVersion
Right False -> pure $ errorResponse STEUnknownPurchaseKey
Left _ -> pure $ errorResponse STEInternal
badgeNow :: ChatController -> IO UTCTime
badgeNow ChatController {config = ChatConfig {badgeCurrentTime}} = badgeCurrentTime
@@ -476,18 +476,18 @@ credentialForEntry BadgeIssuerKey {keyIdx, secretKey} masterKey e@StatementEntry
issuanceAfter :: StatementEntry -> (StatementEntry, BadgeCredential) -> (StatementEntry, StatementEntry, BadgeCredential)
issuanceAfter previous (issued, credential) = (previous, issued, credential)
credentialResponse :: Maybe BadgeCredential -> Maybe T.Text -> Maybe SubscriptionState -> [StatementEntry] -> BadgeServiceResponse
credentialResponse :: Maybe BadgeCredential -> Maybe T.Text -> Maybe SubscriptionState -> [StatementEntry] -> StoreServiceResponse
credentialResponse credential previousEntryId subscription entries =
BSPBadgeCredential {credential, receipt = Nothing, statement = BadgeStatement {entries, previousEntryId}, subscription}
STPBadgeCredential {credential, receipt = Nothing, statement = BadgeStatement {entries, previousEntryId}, subscription}
-- | Nothing is written until the credential is signed, so a signing failure leaves the code unspent.
redeemCode :: BadgeIssuerKey -> ChatController -> Maybe (TQueue GroupEvent) -> C.PublicKeyEd25519 -> BadgeMasterKey -> T.Text -> IO BadgeServiceResponse
redeemCode :: BadgeIssuerKey -> ChatController -> Maybe (TQueue GroupEvent) -> C.PublicKeyEd25519 -> BadgeMasterKey -> T.Text -> IO StoreServiceResponse
redeemCode key cc trackerQ_ purchaseKey masterKey codeText = case parseBadgeCode codeText of
Nothing -> pure $ errorResponse BSECodeInvalid
Nothing -> pure $ errorResponse STECodeInvalid
Just code -> do
now <- badgeNow cc
withDB "getBadgeCode" cc (readCode now code) >>= \case
Left _ -> pure $ errorResponse BSEInternal
Left _ -> pure $ errorResponse STEInternal
Right (Left resp) -> pure resp
Right (Right IssuedCode {badgeCodeId, badgeType, months, redeemLimit}) ->
signFirstMonth key cc masterKey badgeType months SCCode now >>= \case
@@ -499,32 +499,32 @@ redeemCode key cc trackerQ_ purchaseKey masterKey codeText = case parseBadgeCode
Nothing ->
readCode now code db >>= \case
Left resp -> pure (resp, False)
Right _ -> logError "badge service: redeeming a code failed, but the code has uses left and is not revoked" $> (errorResponse BSEInternal, False)
Right _ -> logError "store service: redeeming a code failed, but the code has uses left and is not revoked" $> (errorResponse STEInternal, False)
Just purchaseId -> liftIO $ (,True) <$> firstMonthResponse db purchaseId Nothing Nothing firstMonth
let (resp, claimed) = fromRight (errorResponse BSEInternal, False) r
let (resp, claimed) = fromRight (errorResponse STEInternal, False) r
when (claimed && hasTracker redeemLimit) $ refreshTracker cc trackerQ_ badgeCodeId code
pure resp
where
readCode now code db = liftIO $
getBadgeCode db (badgeCodeHash code) >>= \case
Nothing -> pure $ Left $ errorResponse BSECodeInvalid
Nothing -> pure $ Left $ errorResponse STECodeInvalid
Just c@IssuedCode {badgeCodeId, revokedAt, paymentStatus, expiresAt, redeemLimit, redeemCount} ->
getCodePurchaseForKey db badgeCodeId purchaseKey >>= \case
-- A key that already redeemed gets its credential back without a use, even if the code has since
-- expired or been revoked: a client whose reply was lost retries, and would otherwise lose the badge.
KeyRedeemed KeyPurchase {badgePurchaseId, credential} ->
maybe (Left $ errorResponse BSEInternal) (Left . credentialResponse (Just credential) Nothing Nothing)
maybe (Left $ errorResponse STEInternal) (Left . credentialResponse (Just credential) Nothing Nothing)
<$> getLedgerEntries db badgePurchaseId 0
-- code_used would make the client drop its keys, so the holder could never get the badge back.
KeyRedeemedUnreadable ->
logError "badge service: a redeemed code's credential is missing or unreadable" $> Left (errorResponse BSEInternal)
logError "store service: a redeemed code's credential is missing or unreadable" $> Left (errorResponse STEInternal)
KeyUnredeemed
-- Revoked is checked first, so it answers as if the code never existed.
| Just _ <- revokedAt -> pure $ Left $ errorResponse BSECodeInvalid
| Just _ <- revokedAt -> pure $ Left $ errorResponse STECodeInvalid
-- Redeeming an unpaid code would issue a free badge, so unpaid is refused.
| CPSUnpaid <- paymentStatus -> pure $ Left $ errorResponse BSEPaymentPending
| redeemCount >= redeemLimit -> pure $ Left $ errorResponse BSECodeUsed
| maybe False (now >=) expiresAt -> pure $ Left $ errorResponse BSECodeExpired
| CPSUnpaid <- paymentStatus -> pure $ Left $ errorResponse STEPaymentPending
| redeemCount >= redeemLimit -> pure $ Left $ errorResponse STECodeUsed
| maybe False (now >=) expiresAt -> pure $ Left $ errorResponse STECodeExpired
| otherwise -> pure $ Right c
-- | What a store receipt is presented for. A transfer carries the Apple transaction the device presented,
@@ -538,15 +538,15 @@ presentedTransaction = \case
-- | Every refusal is answered before anything is written, so it leaves the receipt unclaimed; and
-- nothing is written until the credential is signed.
purchaseWithReceipt :: BadgeIssuerKey -> ChatController -> StoreVerifier -> PurchaseChecks -> ReceiptUse -> C.PublicKeyEd25519 -> BadgeMasterKey -> StoreReceipt -> IO BadgeServiceResponse
purchaseWithReceipt :: BadgeIssuerKey -> ChatController -> StoreVerifier -> PurchaseChecks -> ReceiptUse -> C.PublicKeyEd25519 -> BadgeMasterKey -> StoreReceipt -> IO StoreServiceResponse
purchaseWithReceipt key cc verifier checks use purchaseKey masterKey StoreReceipt {txRef = StoreTransactionRef {provider, transactionRef = providerRef}, receiptProductId, subscriptionRef, verifyReceipt, acknowledgeReceipt, acknowledgeSubscription} =
withDB' "getStorePayment" cc (\db -> (,) <$> getStorePaymentCredit db provider providerRef <*> keyHoldsPurchase db) >>= \case
Left _ -> pure $ errorResponse BSEInternal
Left _ -> pure $ errorResponse STEInternal
Right (credit, keyHeld)
-- only the key it credited can ask, and it is told only what it was given, so the store is not asked
| creditedBy credit -> answerCredit credit
-- a payment moves only to a key with no purchase, so one transferOut alone names the purchase holding it
| keyHeld -> pure $ errorResponse BSEBadRequest
| keyHeld -> pure $ errorResponse STEBadRequest
-- a Play subscription is verified by asking about the subscription itself
| Just StoreSubscription <- storeProduct provider =<< receiptProductId -> purchaseSubscription receiptProductId credit
| otherwise ->
@@ -577,10 +577,10 @@ purchaseWithReceipt key cc verifier checks use purchaseKey masterKey StoreReceip
answerCredit credit =
withDB' "answerStoreCredit" cc (\db -> creditedResponse db purchaseKey credit) <&> \case
Right (Left resp) -> resp
_ -> errorResponse BSEInternal
_ -> errorResponse STEInternal
-- the product is read only for a receipt not yet credited, so retiring it leaves its replays answered
newPurchase tx@VerifiedStoreTransaction {productId, paid, testPurchase} = case storeProduct provider productId of
Nothing -> pure $ errorResponse BSEProductUnavailable
Nothing -> pure $ errorResponse STEProductUnavailable
-- an Apple subscription, whose JWS was verified offline
Just StoreSubscription -> purchaseSubscription (Just productId) Uncredited
Just StoreOneTime {badgeType, months} -> do
@@ -597,10 +597,10 @@ purchaseWithReceipt key cc verifier checks use purchaseKey masterKey StoreReceip
purchaseSubscription product_ credit = do
now <- badgeNow cc
atomically (subscriptionAsk now) >>= \case
ClaimHeld remaining -> pure BSPError {code = BSEPaymentPending, message = Nothing, retryAfter = Just (ceiling remaining)}
ClaimHeld remaining -> pure STPError {code = STEPaymentPending, message = Nothing, retryAfter = Just (ceiling remaining)}
NoPlayRead wait -> do
logWarn "Play subscription read refused: the purchase path's reads for this minute are used"
pure BSPError {code = BSERateLimited, message = Nothing, retryAfter = Just (ceiling wait)}
pure STPError {code = STERateLimited, message = Nothing, retryAfter = Just (ceiling wait)}
AskStore ->
checkStoreSubscription verifier subscriptionRef product_ >>= \case
-- no store was asked, so the claim is not held off
@@ -645,23 +645,23 @@ purchaseWithReceipt key cc verifier checks use purchaseKey masterKey StoreReceip
-- an older transaction stops moving the subscription once the store charges again, so a leaked receipt lapses
| SubscriptionApple _ <- subscriptionRef,
presented /= ((\StoreCharge {chargeRef} -> chargeRef) <$> latestCharge) =
pure $ errorResponse BSEPaymentPending
pure $ errorResponse STEPaymentPending
| otherwise = do
now <- badgeNow cc
withDB' "getMovedPayment" cc (\db -> getPurchaseSubscription db fromPurchaseId >>= mapM (movedPayment db)) >>= \case
Right (Just (paymentId, movedFromExpiry_, Just fromTip))
-- A store receipt proves control of the store account but is no one-time secret, so this is the only bound on moves:
-- waiting out the credential of the key the payment last moved from keeps each paid month with at most two keys.
| maybe False (now <) movedFromExpiry_ -> pure $ errorResponse BSETransferLimited
| maybe False (now <) movedFromExpiry_ -> pure $ errorResponse STETransferLimited
| otherwise -> case grantableCharge provider now checked >>= fundsMonthNow purchaseKey now Nothing of
Left notGranted -> firstChargeNotGranted provider notGranted
Right grant -> movePayment now paymentId fromTip grant
_ -> pure $ errorResponse BSEInternal
_ -> pure $ errorResponse STEInternal
where
movedPayment db PurchaseSubscription {paymentId} = (paymentId,,) <$> getMovedFromExpiry db paymentId <*> getLedgerTip db fromPurchaseId
movePayment now paymentId fromTip (charge@StoreCharge {chargeRef, periodStart}, (badgeType, months)) =
withDB' "getSubscriptionCharge" cc (\db -> getSubscriptionCharge db paymentId chargeRef) >>= \case
Left _ -> pure $ errorResponse BSEInternal
Left _ -> pure $ errorResponse STEInternal
Right recorded -> do
chargeId <- maybe (randomId cc) (pure . fst) recorded
entryIds <- (,,,) <$> randomId cc <*> randomId cc <*> randomId cc <*> randomId cc
@@ -681,8 +681,8 @@ purchaseWithReceipt key cc verifier checks use purchaseKey masterKey StoreReceip
Just <$> firstMonthResponse db purchaseId Nothing (Just subscriptionState) firstMonth
case r of
Right (Just resp) -> logInfo "store subscription moved to another key" $> resp
Right Nothing -> logError "badge service: a subscription moved, or its ledger changed, while its transfer was signed" $> errorResponse BSEInternal
Left _ -> pure $ errorResponse BSEInternal
Right Nothing -> logError "store service: a subscription moved, or its ledger changed, while its transfer was signed" $> errorResponse STEInternal
Left _ -> pure $ errorResponse STEInternal
providerToken = case subscriptionRef of
SubscriptionGoogle token -> Just token
SubscriptionApple _ -> Nothing
@@ -698,9 +698,9 @@ purchaseWithReceipt key cc verifier checks use purchaseKey masterKey StoreReceip
Nothing ->
liftIO (getStorePaymentCredit db provider providerRef >>= creditedResponse db purchaseKey) >>= \case
Left resp -> pure resp
Right () -> logError "badge service: a store payment exists but funds no purchase" $> errorResponse BSEInternal
Right () -> logError "store service: a store payment exists but funds no purchase" $> errorResponse STEInternal
Just purchaseId -> liftIO $ writeCredit db purchaseId paymentId
pure $ fromRight (errorResponse BSEInternal) r
pure $ fromRight (errorResponse STEInternal) r
-- | Why a store charge grants nothing.
data NotGranted
@@ -749,38 +749,38 @@ coverageEnded db paymentId SubscriptionCheck {subscriptionState, latestCharge}
| otherwise = pure False
-- | No payment row exists yet to stamp, so a first purchase's checks are bounded by the purchase checks.
firstChargeNotGranted :: PaymentProvider -> NotGranted -> IO BadgeServiceResponse
firstChargeNotGranted :: PaymentProvider -> NotGranted -> IO StoreServiceResponse
firstChargeNotGranted provider = \case
NGMalformedPeriod -> storeRefusalResponse $ SRVerifierFailed "a charge whose period does not end after its start"
-- Play issues a new token when an ended subscription is bought again, so this one can never be credited
NGEnded | PPGoogle <- provider -> storeRefusalResponse $ SRInvalid "the subscription ended"
NGNotStarted -> storeRefusalResponse SRPending
-- a later charge, or an Apple resubscription under the same original id, may yet be credited from this receipt
reason -> logInfo ("store subscription not credited yet: " <> tshow reason) $> BSPError {code = BSEPaymentPending, message = Nothing, retryAfter = Just 86400}
reason -> logInfo ("store subscription not credited yet: " <> tshow reason) $> STPError {code = STEPaymentPending, message = Nothing, retryAfter = Just 86400}
-- | What each request was answered, to pair with its command in a log. No payload: a credential,
-- an invoice and a statement are the client's, and an error's message can quote what it refused.
responseName :: BadgeServiceResponse -> T.Text
responseName :: StoreServiceResponse -> T.Text
responseName = \case
BSPBadgeCatalog {} -> "catalog"
BSPBadgeInvoice {} -> "invoice"
BSPBadgeCredential {credential = Just _, subscription} ->
STPBadgeCatalog {} -> "catalog"
STPBadgeInvoice {} -> "invoice"
STPBadgeCredential {credential = Just _, subscription} ->
"badge issued" <> maybe "" (\s -> ", subscription " <> tshow s) subscription
BSPBadgeCredential {credential = Nothing} -> "no month to issue"
BSPError {code} -> "error " <> tshow code
STPBadgeCredential {credential = Nothing} -> "no month to issue"
STPError {code} -> "error " <> tshow code
-- | The command each request ran, so a log can be followed without the request ids. No payload:
-- a payment holds a store receipt, and an upgrade a receipt code.
commandName :: BadgeServiceCommand -> T.Text
commandName :: StoreServiceCommand -> T.Text
commandName = \case
BSCGetBadgeCatalog -> "getBadgeCatalog"
BSCGetBadgeInvoice {} -> "getBadgeInvoice"
BSCRedeemBadgeCode {} -> "redeemBadgeCode"
BSCPurchaseBadge {payment} -> "purchaseBadge " <> paymentName payment
BSCUpgradeBadgeSubscription {payment} -> "upgradeBadgeSubscription " <> paymentName payment
BSCTransferBadge {payment} -> "transferBadge " <> paymentName payment
BSCIssueBadge {} -> "issueBadge"
BSCPauseBadge -> "pauseBadge"
STCGetBadgeCatalog -> "getBadgeCatalog"
STCGetBadgeInvoice {} -> "getBadgeInvoice"
STCRedeemBadgeCode {} -> "redeemBadgeCode"
STCPurchaseBadge {payment} -> "purchaseBadge " <> paymentName payment
STCUpgradeBadgeSubscription {payment} -> "upgradeBadgeSubscription " <> paymentName payment
STCTransferBadge {payment} -> "transferBadge " <> paymentName payment
STCIssueBadge {} -> "issueBadge"
STCPauseBadge -> "pauseBadge"
where
paymentName = \case
SPApple {} -> "(App Store)"
@@ -790,28 +790,28 @@ commandName = \case
-- | A forged receipt and a refunded one are both receipt_invalid, so the client learns nothing a
-- forger could iterate on. A test purchase is named, since the device that made it already knows.
storeRefusalResponse :: StoreRefusal -> IO BadgeServiceResponse
storeRefusalResponse :: StoreRefusal -> IO StoreServiceResponse
storeRefusalResponse = \case
-- warn, not info: every one of these ends a purchase for good, and one of them (a store that no longer
-- knows a subscription it once sold) can do that to a purchase the user really paid for
SRInvalid reason -> logWarn ("store receipt refused for good: " <> reason) $> errorResponse BSEReceiptInvalid
SRTestPurchase -> logInfo "store receipt refused: test purchase" $> errorResponse BSETestPurchase
SRPending -> pure $ errorResponse BSEPaymentPending
SRUnreachable reason -> logWarn ("store unreachable: " <> reason) $> errorResponse BSEProviderUnavailable
SRVerifierFailed reason -> logError ("store receipt not verified: " <> reason) $> errorResponse BSEInternal
SRNotConfigured -> logWarn "store receipt refused: no verifier for this store is configured" $> errorResponse BSEProviderNotConfigured
SRInvalid reason -> logWarn ("store receipt refused for good: " <> reason) $> errorResponse STEReceiptInvalid
SRTestPurchase -> logInfo "store receipt refused: test purchase" $> errorResponse STETestPurchase
SRPending -> pure $ errorResponse STEPaymentPending
SRUnreachable reason -> logWarn ("store unreachable: " <> reason) $> errorResponse STEProviderUnavailable
SRVerifierFailed reason -> logError ("store receipt not verified: " <> reason) $> errorResponse STEInternal
SRNotConfigured -> logWarn "store receipt refused: no verifier for this store is configured" $> errorResponse STEProviderNotConfigured
creditedResponse :: DB.Connection -> C.PublicKeyEd25519 -> FundingCredit -> IO (Either BadgeServiceResponse ())
creditedResponse :: DB.Connection -> C.PublicKeyEd25519 -> FundingCredit -> IO (Either StoreServiceResponse ())
creditedResponse db purchaseKey = \case
Uncredited -> pure $ Right ()
CreditedUnreadable -> pure $ Left $ errorResponse BSEInternal
CreditedUnreadable -> pure $ Left $ errorResponse STEInternal
Credited CreditedPurchase {purchaseKey = k, badgePurchaseId, credential, subscription}
| k /= purchaseKey -> pure $ Left $ errorResponse BSEReceiptUsed
| k /= purchaseKey -> pure $ Left $ errorResponse STEReceiptUsed
| otherwise ->
maybe (Left $ errorResponse BSEInternal) (Left . credentialResponse (Just credential) Nothing subscription)
maybe (Left $ errorResponse STEInternal) (Left . credentialResponse (Just credential) Nothing subscription)
<$> getLedgerEntries db badgePurchaseId 0
signFirstMonth :: BadgeIssuerKey -> ChatController -> BadgeMasterKey -> BadgeType -> Int -> StatementCreditType -> UTCTime -> IO (Either BadgeServiceResponse ([StatementEntry], (StatementEntry, StatementEntry, BadgeCredential)))
signFirstMonth :: BadgeIssuerKey -> ChatController -> BadgeMasterKey -> BadgeType -> Int -> StatementCreditType -> UTCTime -> IO (Either StoreServiceResponse ([StatementEntry], (StatementEntry, StatementEntry, BadgeCredential)))
signFirstMonth key cc masterKey badgeType months credit now = do
grantUuid <- randomId cc
-- TODO [badges] a top-up grants onto an existing ledger, and must lapse before it or the
@@ -820,22 +820,22 @@ signFirstMonth key cc masterKey badgeType months credit now = do
signMonthAfter key cc masterKey now seed [grantEntry now grantUuid badgeType months credit seed]
-- | The rows that fund a month, after the entry they follow, with that month issued at now and signed.
signMonthAfter :: BadgeIssuerKey -> ChatController -> BadgeMasterKey -> UTCTime -> StatementEntry -> [StatementEntry] -> IO (Either BadgeServiceResponse ([StatementEntry], (StatementEntry, StatementEntry, BadgeCredential)))
signMonthAfter :: BadgeIssuerKey -> ChatController -> BadgeMasterKey -> UTCTime -> StatementEntry -> [StatementEntry] -> IO (Either StoreServiceResponse ([StatementEntry], (StatementEntry, StatementEntry, BadgeCredential)))
signMonthAfter key cc masterKey now previous rows = do
issueUuid <- randomId cc
let funded = last (previous : rows)
case issueEntry now issueUuid funded of
Nothing -> logError "badge service: the rows written fund no month to issue" $> Left (errorResponse BSEInternal)
Nothing -> logError "store service: the rows written fund no month to issue" $> Left (errorResponse STEInternal)
Just issued ->
credentialForEntry key masterKey issued >>= \case
Left e -> logError ("badge service signing failed: " <> T.pack e) $> Left (errorResponse BSEInternal)
Left e -> logError ("store service signing failed: " <> T.pack e) $> Left (errorResponse STEInternal)
Right signed -> pure $ Right (rows, issuanceAfter funded signed)
firstMonthResponse :: DB.Connection -> Int64 -> Maybe T.Text -> Maybe SubscriptionState -> ([StatementEntry], (StatementEntry, StatementEntry, BadgeCredential)) -> IO BadgeServiceResponse
firstMonthResponse :: DB.Connection -> Int64 -> Maybe T.Text -> Maybe SubscriptionState -> ([StatementEntry], (StatementEntry, StatementEntry, BadgeCredential)) -> IO StoreServiceResponse
firstMonthResponse db purchaseId creditPaymentId_ subscription (rows, issuance@(_, _, credential)) = do
appendLedgerPlan db purchaseId creditPaymentId_ rows $ Just issuance
entries_ <- getLedgerEntries db purchaseId 0
pure $ maybe (errorResponse BSEInternal) (credentialResponse (Just credential) Nothing subscription) entries_
pure $ maybe (errorResponse STEInternal) (credentialResponse (Just credential) Nothing subscription) entries_
-- | The subscription a device's transaction names, its product and that product's tier: what an upgrade waits for, never what it grants.
data SubscriptionUpgrade = SubscriptionUpgrade
@@ -845,31 +845,31 @@ data SubscriptionUpgrade = SubscriptionUpgrade
}
-- | Refused before the store is asked: a transaction that does not verify, or that is of no subscription product.
upgradeSubscriptionCmd :: BadgeIssuerKey -> ChatController -> StoreVerifier -> C.PublicKeyEd25519 -> BadgeBalance -> StoreReceipt -> IO BadgeServiceResponse
upgradeSubscriptionCmd :: BadgeIssuerKey -> ChatController -> StoreVerifier -> C.PublicKeyEd25519 -> BadgeBalance -> StoreReceipt -> IO StoreServiceResponse
upgradeSubscriptionCmd key cc verifier purchaseKey balance StoreReceipt {txRef = StoreTransactionRef {provider, transactionRef = claimedRef}, verifyReceipt} =
verifyReceipt >>= \case
Left refusal -> storeRefusalResponse refusal
Right VerifiedStoreTransaction {transactionRef}
| transactionRef /= claimedRef -> storeRefusalResponse $ SRVerifierFailed "verified a transaction other than the one claimed"
Right VerifiedStoreTransaction {productId} -> case storePlan provider productId of
Nothing -> pure $ errorResponse BSEBadRequest
Nothing -> pure $ errorResponse STEBadRequest
Just (tier, _) -> issueBadgeCmd key cc verifier purchaseKey (Just SubscriptionUpgrade {upgradeRef = claimedRef, upgradeProductId = productId, upgradeTier = tier}) balance
-- | The purchase is reached through the verified signer key and no other way.
issueBadgeCmd :: BadgeIssuerKey -> ChatController -> StoreVerifier -> C.PublicKeyEd25519 -> Maybe SubscriptionUpgrade -> BadgeBalance -> IO BadgeServiceResponse
issueBadgeCmd :: BadgeIssuerKey -> ChatController -> StoreVerifier -> C.PublicKeyEd25519 -> Maybe SubscriptionUpgrade -> BadgeBalance -> IO StoreServiceResponse
issueBadgeCmd key cc verifier purchaseKey upgrade_ BadgeBalance {lastEntry} = do
now <- badgeNow cc
purchase_ <- withDB' "getBadgePurchase" cc (\db -> getIssuePurchase db purchaseKey)
case purchase_ of
Left _ -> pure $ errorResponse BSEInternal
Right Nothing -> pure $ errorResponse BSEUnknownPurchaseKey
Left _ -> pure $ errorResponse STEInternal
Right Nothing -> pure $ errorResponse STEUnknownPurchaseKey
Right (Just (purchase, Just tip, Just subscription))
| Just upgrade <- upgrade_ -> upgradeSubscription upgrade purchase tip subscription now
-- once a subscription's paid coverage has ended, only a new store charge funds another month
| paidThrough tip <= now -> renewSubscription Nothing purchase tip subscription now
| ChecksAtEveryRequest <- storeChecks verifier -> checkStoreDuringCoverage purchase tip subscription now
| balanceStartTs tip <= now -> checkStoreBeforeMonth purchase tip subscription now
Right (Just _) | isJust upgrade_ -> pure $ errorResponse BSEBadRequest
Right (Just _) | isJust upgrade_ -> pure $ errorResponse STEBadRequest
Right (Just (ServicePurchase {badgePurchaseId}, Just StatementEntry {entryType = SEDebit SDTransferOut {}}, Nothing)) ->
answered "answerMovedOut" $ \db -> withoutCredential <$> issueResponse db badgePurchaseId now (Just SSEnded)
Right (Just (purchase, tip, subscription_)) -> issueDue purchase tip ((\PurchaseSubscription {storedState} -> storedState) <$> subscription_) now
@@ -883,7 +883,7 @@ issueBadgeCmd key cc verifier purchaseKey upgrade_ BadgeBalance {lastEntry} = do
Nothing -> writeIssued badgePurchaseId tip (maybeToList lapsed) now Nothing state_
Just e ->
credentialForEntry key masterKey e >>= \case
Left err -> logError ("badge service signing failed: " <> T.pack err) $> errorResponse BSEInternal
Left err -> logError ("store service signing failed: " <> T.pack err) $> errorResponse STEInternal
Right signed ->
writeIssued badgePurchaseId tip (maybeToList lapsed) now (Just $ issuanceAfter current signed) state_
-- Write only if the tip has not moved, since another request may have advanced it.
@@ -892,13 +892,13 @@ issueBadgeCmd key cc verifier purchaseKey upgrade_ BadgeBalance {lastEntry} = do
tip' <- lockedLedgerTip db purchaseId t
when (fmap entryId tip' == fmap entryId tip) $ appendLedgerPlan db purchaseId Nothing rows issuance_
issueResponse db purchaseId t state_
pure $ fromRight (errorResponse BSEInternal) r
pure $ fromRight (errorResponse STEInternal) r
-- Answered pending until the tier the device saw is granted, so the old tier's credential is never taken for the new one.
upgradeSubscription upgrade@SubscriptionUpgrade {upgradeRef, upgradeTier} purchase@ServicePurchase {badgePurchaseId} tip@StatementEntry {balanceBadgeType} subscription@PurchaseSubscription {subscriptionRef, storedState} now
| not ownSubscription = pure $ errorResponse BSEBadRequest
| not ownSubscription = pure $ errorResponse STEBadRequest
| balanceBadgeType == upgradeTier = answered "answerUpgraded" $ \db -> issueResponse db badgePurchaseId now (Just storedState)
| Just wait <- checkWait now subscription =
pure BSPError {code = BSEPaymentPending, message = Nothing, retryAfter = Just $ ceiling wait}
pure STPError {code = STEPaymentPending, message = Nothing, retryAfter = Just $ ceiling wait}
| otherwise = renewSubscription (Just upgrade) purchase tip subscription now
where
ownSubscription = case subscriptionRef of
@@ -910,7 +910,7 @@ issueBadgeCmd key cc verifier purchaseKey upgrade_ BadgeBalance {lastEntry} = do
| isNothing upgrading_ && not (subscriptionCheckDue (storeChecks verifier) now tip subscription) = answered "answerStoredSubscription" $ \db -> issueResponse db badgePurchaseId now (Just storedState)
| otherwise =
withDB' "stampSubscriptionCheck" cc (\db -> stampSubscriptionCheck db paymentId now) >>= \case
Left _ -> pure $ errorResponse BSEInternal
Left _ -> pure $ errorResponse STEInternal
Right () ->
-- the stores ignore the raise's product; the development mock charges its plan from now on
checkStoreSubscription verifier subscriptionRef (upgradeProductId <$> upgrading_) >>= \case
@@ -922,7 +922,7 @@ issueBadgeCmd key cc verifier purchaseKey upgrade_ BadgeBalance {lastEntry} = do
recordCheck latestCharge subscriptionState
Right (charge@StoreCharge {chargeRef, periodStart}, (badgeType, months)) ->
withDB' "getSubscriptionCharge" cc (\db -> getSubscriptionCharge db paymentId chargeRef) >>= \case
Left _ -> pure $ errorResponse BSEInternal
Left _ -> pure $ errorResponse STEInternal
-- the store still reports the charge the ledger last granted
Right (Just (_, True)) -> recordCheck (Just charge) subscriptionState
Right recorded -> do
@@ -943,8 +943,8 @@ issueBadgeCmd key cc verifier purchaseKey upgrade_ BadgeBalance {lastEntry} = do
Just <$> checkedResponse db badgeType subscriptionState
case r of
Right (Just resp) -> logBanked months $> resp
Right Nothing -> logError "badge service: a subscription's ledger moved while its renewal was signed" $> errorResponse BSEInternal
Left _ -> pure $ errorResponse BSEInternal
Right Nothing -> logError "store service: a subscription's ledger moved while its renewal was signed" $> errorResponse STEInternal
Left _ -> pure $ errorResponse STEInternal
where
-- the store's answer is kept, and a charge it reports is recorded once, granted or not
recordCheck charge_ state = do
@@ -954,12 +954,12 @@ issueBadgeCmd key cc verifier purchaseKey upgrade_ BadgeBalance {lastEntry} = do
setSubscriptionState db paymentId state now
checkedResponse db balanceBadgeType state
checkedResponse db ledgerTier state = case upgradeTier <$> upgrading_ of
Just tier | tier /= ledgerTier -> pure $ atLeastCheckInterval $ errorResponse BSEPaymentPending
Just tier | tier /= ledgerTier -> pure $ atLeastCheckInterval $ errorResponse STEPaymentPending
_ -> issueResponse db badgePurchaseId now (Just state)
-- A charge a dev deployment's store reports while coverage runs is banked with no issuance, and its month issued once coverage reaches it.
checkStoreDuringCoverage purchase@ServicePurchase {badgePurchaseId} tip PurchaseSubscription {paymentId, provider, subscriptionRef} now =
withDB' "stampSubscriptionCheck" cc (\db -> stampSubscriptionCheck db paymentId now) >>= \case
Left _ -> pure $ errorResponse BSEInternal
Left _ -> pure $ errorResponse STEInternal
Right () ->
checkStoreSubscription verifier subscriptionRef Nothing >>= \case
Left refusal -> atLeastCheckInterval <$> storeRefusalResponse refusal
@@ -988,7 +988,7 @@ issueBadgeCmd key cc verifier purchaseKey upgrade_ BadgeBalance {lastEntry} = do
else pure Nothing
(ended, banked,) <$> getLedgerTip db badgePurchaseId
case r of
Left _ -> pure $ errorResponse BSEInternal
Left _ -> pure $ errorResponse STEInternal
Right (True, _, _) -> refundRemaining purchase tip paymentId now
Right (False, banked, tip_) -> do
forM_ banked logBanked
@@ -1000,7 +1000,7 @@ issueBadgeCmd key cc verifier purchaseKey upgrade_ BadgeBalance {lastEntry} = do
| held = issueDue purchase (Just tip) (Just storedState) now
| otherwise =
withDB' "stampSubscriptionCheck" cc (\db -> stampSubscriptionCheck db paymentId now) >>= \case
Left _ -> pure $ errorResponse BSEInternal
Left _ -> pure $ errorResponse STEInternal
Right () ->
checkStoreSubscription verifier subscriptionRef Nothing >>= \case
Left refusal -> storeRefusalResponse refusal >> issueDue purchase (Just tip) (Just storedState) now
@@ -1013,7 +1013,7 @@ issueBadgeCmd key cc verifier purchaseKey upgrade_ BadgeBalance {lastEntry} = do
setSubscriptionState db paymentId (if ended then SSEnded else subscriptionState) now
pure ended
case r of
Left _ -> pure $ errorResponse BSEInternal
Left _ -> pure $ errorResponse STEInternal
Right True -> refundRemaining purchase tip paymentId now
Right False -> issueDue purchase (Just tip) (Just subscriptionState) now
where
@@ -1033,11 +1033,11 @@ issueBadgeCmd key cc verifier purchaseKey upgrade_ BadgeBalance {lastEntry} = do
Just . withoutCredential <$> issueResponse db badgePurchaseId now (Just SSEnded)
case r of
Right (Just resp) -> resp <$ unless (refunded == 0) (logInfo $ "store subscription ended during coverage: " <> tshow (negate refunded) <> " months refunded")
Right Nothing -> logError "badge service: a subscription's ledger moved while its refund was written" $> errorResponse BSEInternal
Left _ -> pure $ errorResponse BSEInternal
answered what action = fromRight (errorResponse BSEInternal) <$> withDB' what cc action
Right Nothing -> logError "store service: a subscription's ledger moved while its refund was written" $> errorResponse STEInternal
Left _ -> pure $ errorResponse STEInternal
answered what action = fromRight (errorResponse STEInternal) <$> withDB' what cc action
withoutCredential = \case
BSPBadgeCredential {receipt, statement, subscription} -> BSPBadgeCredential {credential = Nothing, receipt, statement, subscription}
STPBadgeCredential {receipt, statement, subscription} -> STPBadgeCredential {credential = Nothing, receipt, statement, subscription}
resp -> resp
logBanked months = logInfo $ "store subscription charge banked: " <> tshow months <> " months"
-- Only the asserted entry's identity is read, never the months it claims.
@@ -1048,7 +1048,7 @@ issueBadgeCmd key cc verifier purchaseKey upgrade_ BadgeBalance {lastEntry} = do
-- single opening credit, rather than resending the whole history
entries_ <- getLedgerEntries db purchaseId (fromMaybe 0 assertedId)
credential_ <- getCurrentIssuance db purchaseId t
pure $ maybe (errorResponse BSEInternal) (credentialResponse credential_ (assertedUuid <$ assertedId) subscription) entries_
pure $ maybe (errorResponse STEInternal) (credentialResponse credential_ (assertedUuid <$ assertedId) subscription) entries_
getIssuePurchase :: DB.Connection -> C.PublicKeyEd25519 -> IO (Maybe (ServicePurchase, Maybe StatementEntry, Maybe PurchaseSubscription))
getIssuePurchase db purchaseKey = do
@@ -1072,9 +1072,9 @@ subscriptionCheckInterval :: NominalDiffTime
subscriptionCheckInterval = 3600
-- | The next check waits out the interval whatever the client is told, so its retry waits as long.
atLeastCheckInterval :: BadgeServiceResponse -> BadgeServiceResponse
atLeastCheckInterval :: StoreServiceResponse -> StoreServiceResponse
atLeastCheckInterval = \case
BSPError {code, message, retryAfter = Just t} -> BSPError {code, message, retryAfter = Just $ max t $ round subscriptionCheckInterval}
STPError {code, message, retryAfter = Just t} -> STPError {code, message, retryAfter = Just $ max t $ round subscriptionCheckInterval}
resp -> resp
-- | The subscription claims the purchase path asked a store about, one map per store: the App Store's by original
@@ -6,7 +6,7 @@
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators #-}
module BadgeService.Store
module StoreService.Store
( IssuedCode (..),
KeyRedemption (..),
KeyPurchase (..),
@@ -53,8 +53,8 @@ module BadgeService.Store
)
where
import BadgeService.Store.Invoices (executeChanging, paymentStatusText)
import BadgeService.StoreReceipts (StoreCharge (..), SubscriptionRef (..))
import StoreService.Store.Invoices (executeChanging, paymentStatusText)
import StoreService.StoreReceipts (StoreCharge (..), SubscriptionRef (..))
import qualified Data.Aeson as J
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Lazy.Char8 as LB
@@ -64,7 +64,7 @@ import Data.Text (Text)
import Data.Time.Clock (UTCTime)
import Simplex.Chat.Badges (BadgeCredential, BadgeMasterKey (..), BadgeType)
import Simplex.Chat.Badges.Ledger
import Simplex.Chat.Badges.Service (StatementCreditType (..), StatementDebitType (..), StatementEntry (..), StatementEntryType (..), SubscriptionState)
import Simplex.Chat.StoreService (StatementCreditType (..), StatementDebitType (..), StatementEntry (..), StatementEntryType (..), SubscriptionState)
import Simplex.Chat.Badges.Types (BadgeCodePaymentStatus, BadgePurchaseStatus (..))
import Simplex.Chat.PaymentService.Types (CurrencyAmount (..), InvoiceId (..), PaymentProvider (..), PaymentStatus (..))
import Simplex.Chat.Store.Shared (insertedRowId)
@@ -5,7 +5,7 @@
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeOperators #-}
module BadgeService.Store.Invoices
module StoreService.Store.Invoices
( InvoiceRow (..),
InvoicePayment (..),
paymentHolds,
@@ -52,7 +52,7 @@ import Data.Time.Clock (UTCTime)
import Data.Time.Clock.POSIX (posixSecondsToUTCTime, utcTimeToPOSIXSeconds)
import Data.Word (Word8, Word32)
import Simplex.Chat.Badges (BadgeType (..))
import Simplex.Chat.Badges.Service (BadgePrice (..), BadgeOffer (..))
import Simplex.Chat.StoreService (BadgePrice (..), BadgeOffer (..))
import Simplex.Chat.Badges.Types (BadgeCodePaymentStatus (..), BadgeItemStatus (..), BadgeOfferId (..), BadgePriceId (..), OfferDiscount (..))
import Simplex.Chat.Store.Shared (insertedRowId)
import Simplex.Chat.PaymentService.Types (CardProvider (..), CryptoCurrency (..), CurrencyAmount (..), InvoiceId (..), InvoiceStatus (..), PaymentProvider (..), PaymentStatus (..), ServicePaymentDestination (..))
@@ -62,12 +62,12 @@ import Simplex.Messaging.Encoding.String (textDecode, textEncode)
import Simplex.Messaging.Util (safeDecodeUtf8, tshow)
#if defined(dbPostgres)
import BadgeService.Store.Postgres.Migrations (servicePrefix, withPrefix)
import StoreService.Store.Postgres.Migrations (servicePrefix, withPrefix)
import Database.PostgreSQL.Simple (Only (..), Query, ToRow, (:.) (..))
import qualified Database.PostgreSQL.Simple as PSQL
import Database.PostgreSQL.Simple.Errors (ConstraintViolation (..), constraintViolation)
#else
import BadgeService.Store.SQLite.Migrations (servicePrefix, withPrefix)
import StoreService.Store.SQLite.Migrations (servicePrefix, withPrefix)
import Database.SQLite.Simple (Only (..), Query, ToRow, (:.) (..))
import qualified Database.SQLite.Simple as SQL
#endif
@@ -3,12 +3,12 @@
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
module BadgeService.Store.Migrate
( runBadgeServiceMigrations,
module StoreService.Store.Migrate
( runStoreServiceMigrations,
)
where
import BadgeService.Options
import StoreService.Options
import Simplex.Chat.Controller (ChatConfig (..))
import Simplex.Chat.Options (CoreChatOpts (..))
import Simplex.Chat.Options.DB
@@ -18,22 +18,22 @@ import Simplex.Messaging.Agent.Store.Shared (MigrationConfig (..), MigrationConf
import System.Exit (exitFailure)
#if defined(dbPostgres)
import BadgeService.Store.Postgres.Migrations
import StoreService.Store.Postgres.Migrations
#else
import BadgeService.Store.SQLite.Migrations
import StoreService.Store.SQLite.Migrations
#endif
runBadgeServiceMigrations :: BadgeServiceOpts -> ChatConfig -> DBStore -> IO ()
runBadgeServiceMigrations opts ChatConfig {confirmMigrations} chatStore =
runStoreServiceMigrations :: StoreServiceOpts -> ChatConfig -> DBStore -> IO ()
runStoreServiceMigrations opts ChatConfig {confirmMigrations} chatStore =
migrateDBSchema
chatStore
(toDBOpts dbOptions chatSuffix False [])
(Just "sx_badge_service_migrations")
badgeServiceSchemaMigrations
storeServiceSchemaMigrations
MigrationConfig {confirm, backupPath = Nothing}
>>= either (exit . ("badge service migrations " <>) . show) pure
>>= either (exit . ("store service migrations " <>) . show) pure
where
BadgeServiceOpts {coreOptions = CoreChatOpts {dbOptions, yesToUpMigrations}} = opts
StoreServiceOpts {coreOptions = CoreChatOpts {dbOptions, yesToUpMigrations}} = opts
confirm = if confirmMigrations == MCConsole && yesToUpMigrations then MCYesUp else confirmMigrations
exit :: String -> IO a
@@ -2,7 +2,7 @@
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module BadgeService.Store.Postgres.Migrations (badgeServiceSchemaMigrations, servicePrefix, withPrefix) where
module StoreService.Store.Postgres.Migrations (storeServiceSchemaMigrations, servicePrefix, withPrefix) where
import Data.List (sortOn)
import Data.Text (Text)
@@ -10,8 +10,8 @@ import Simplex.Chat.Store.Postgres.Migrations.M20260915_user_badges (badgeSchema
import Simplex.Messaging.Agent.Store.Shared (Migration (..))
import Text.RawString.QQ (r)
badgeServiceSchemaMigrations :: [Migration]
badgeServiceSchemaMigrations = sortOn name $ map migration schemaMigrations
storeServiceSchemaMigrations :: [Migration]
storeServiceSchemaMigrations = sortOn name $ map migration schemaMigrations
where
migration (name, up, down) = Migration {name, up, down}
@@ -2,7 +2,7 @@
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module BadgeService.Store.SQLite.Migrations (badgeServiceSchemaMigrations, servicePrefix, withPrefix) where
module StoreService.Store.SQLite.Migrations (storeServiceSchemaMigrations, servicePrefix, withPrefix) where
import Data.List (sortOn)
import Data.Text (Text)
@@ -11,8 +11,8 @@ import Database.SQLite.Simple.QQ (sql)
import Simplex.Chat.Store.SQLite.Migrations.M20260915_user_badges (badgeSchema, badgeSchemaDown, withPrefix)
import Simplex.Messaging.Agent.Store.Shared (Migration (..))
badgeServiceSchemaMigrations :: [Migration]
badgeServiceSchemaMigrations = sortOn name $ map migration schemaMigrations
storeServiceSchemaMigrations :: [Migration]
storeServiceSchemaMigrations = sortOn name $ map migration schemaMigrations
where
migration (name, up, down) = Migration {name, up = fromQuery up, down = fromQuery <$> down}
@@ -5,7 +5,7 @@
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
module BadgeService.StoreReceipts
module StoreService.StoreReceipts
( VerifiedStoreTransaction (..),
StoreRefusal (..),
StoreVerifier (..),
@@ -22,7 +22,7 @@ module BadgeService.StoreReceipts
)
where
import BadgeService.Log (logInfo, logWarn)
import StoreService.Log (logInfo, logWarn)
import Control.Exception (Exception, catch, evaluate, try)
import qualified Data.ByteString.Lazy as LB
import Data.Char (isAlphaNum, isAscii, isAsciiLower, isAsciiUpper, isControl, isDigit, isPrint, isSpace)
@@ -34,7 +34,7 @@ import qualified Data.Text as T
import Data.Time.Clock (UTCTime)
import Network.HTTP.Client (HttpException (..), Manager, Request, Response (..), brReadSome, parseRequest, withResponse)
import Network.HTTP.Types (Status (..))
import Simplex.Chat.Badges.Service (SubscriptionState)
import Simplex.Chat.StoreService (SubscriptionState)
import Simplex.Chat.PaymentService (ServicePayment (..), appleTransactionRef, googlePurchaseRef)
import Simplex.Chat.PaymentService.Types (CurrencyAmount, PaymentProvider (..), StoreTransactionRef (..))
import Simplex.Messaging.Util (catchOwn', tshow)
@@ -4,15 +4,15 @@
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module BadgeService.StoreReceipts.Apple
module StoreService.StoreReceipts.Apple
( verifyAppleTransaction,
appleSubscriptionChecker,
readAppleRoot,
)
where
import BadgeService.Config (AppleServerApi (..))
import BadgeService.StoreReceipts (StoreCharge (..), StoreRefusal (..), StoreVerifierFailure (..), SubscriptionCheck (..), VerifiedStoreTransaction (..), storeRequest)
import StoreService.Config (AppleServerApi (..))
import StoreService.StoreReceipts (StoreCharge (..), StoreRefusal (..), StoreVerifierFailure (..), SubscriptionCheck (..), VerifiedStoreTransaction (..), storeRequest)
import Control.Concurrent.STM (TVar, atomically, newTVarIO, readTVarIO, writeTVar)
import Control.Exception (IOException, evaluate, throwIO, try)
import Control.Monad (guard, unless, when)
@@ -48,7 +48,7 @@ import Data.X509.Validation (SignatureFailure (..), SignatureVerification (..),
import Network.HTTP.Client (Manager, Request (..))
import Network.HTTP.Client.TLS (newTlsManager)
import Network.HTTP.Types (hAuthorization)
import Simplex.Chat.Badges.Service (SubscriptionState (..))
import Simplex.Chat.StoreService (SubscriptionState (..))
import Simplex.Chat.PaymentService (applePayloadRef)
import Simplex.Chat.PaymentService.Types (CurrencyAmount (..))
import Simplex.Messaging.Util (catchOwn', eitherToMaybe, tshow)
@@ -5,10 +5,10 @@
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
module BadgeService.StoreReceipts.Google (PlayVerifier (..), playStoreVerifier) where
module StoreService.StoreReceipts.Google (PlayVerifier (..), playStoreVerifier) where
import BadgeService.Config (PlayStoreConfig (..))
import BadgeService.StoreReceipts (StoreCharge (..), StoreRefusal (..), SubscriptionCheck (..), VerifiedStoreTransaction (..), storeRequest)
import StoreService.Config (PlayStoreConfig (..))
import StoreService.StoreReceipts (StoreCharge (..), StoreRefusal (..), SubscriptionCheck (..), VerifiedStoreTransaction (..), storeRequest)
import Control.Concurrent.STM
import Control.Exception (IOException, try)
import Control.Monad (forM)
@@ -36,7 +36,7 @@ import Network.HTTP.Client (Manager, Request (..), RequestBody (..))
import Network.HTTP.Client.TLS (newTlsManager)
import Network.HTTP.Types (hAuthorization, hContentType, methodPost, renderSimpleQuery)
import Simplex.Chat.Badges.Ledger (addMonths)
import Simplex.Chat.Badges.Service (SubscriptionState (..))
import Simplex.Chat.StoreService (SubscriptionState (..))
import Simplex.Chat.Badges.StorePlan (playBasePlan)
import Simplex.Chat.PaymentService (googlePurchaseRef)
import Simplex.Messaging.Util (tshow)
@@ -2,10 +2,10 @@
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
module BadgeService.StoreReceipts.Mock (newMockStoreVerifier) where
module StoreService.StoreReceipts.Mock (newMockStoreVerifier) where
import BadgeService.Catalog (playMonthlyPlan)
import BadgeService.StoreReceipts
import StoreService.Catalog (playMonthlyPlan)
import StoreService.StoreReceipts
import Control.Applicative ((<|>))
import Control.Concurrent.STM (TVar, atomically, modifyTVar', newTVarIO, readTVarIO)
import Control.Monad (guard)
@@ -18,7 +18,7 @@ import qualified Data.Text as T
import Data.Text.Encoding (encodeUtf8)
import Data.Time.Clock (UTCTime, addUTCTime)
import Simplex.Chat.Badges.Ledger (addMonths)
import Simplex.Chat.Badges.Service (SubscriptionState (..))
import Simplex.Chat.StoreService (SubscriptionState (..))
import Simplex.Chat.Badges.StorePlan (playBasePlan, storePlan)
import Simplex.Chat.PaymentService (appleTransactionRef, googlePurchaseRef)
import Simplex.Chat.PaymentService.Types (PaymentProvider (..))
@@ -1,6 +1,6 @@
{-# LANGUAGE NamedFieldPuns #-}
module BadgeService.Waiters (Waiters, Seen, newWaiters, publish, publishPayment, awaitStatus, waitingCount, waitingCountSTM) where
module StoreService.Waiters (Waiters, Seen, newWaiters, publish, publishPayment, awaitStatus, waitingCount, waitingCountSTM) where
import Control.Concurrent.STM
import Control.Exception (bracket)
@@ -3,7 +3,7 @@
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module BadgeService.Web.Server
module StoreService.Web.Server
( WebEnv (..),
Limit (..),
Bucket (..),
@@ -21,15 +21,15 @@ module BadgeService.Web.Server
)
where
import BadgeService.Catalog (PricedOffer (..), priceOffer)
import BadgeService.Config (BTCPayConfig (..), ListenerConfig (..), ServiceConfig (..), SpeedPolicy (..), StripeConfig (..), defaultExpiryMinutes, defaultSessionMinutes)
import BadgeService.Poller (ReadHints, queueReadHint)
import BadgeService.Providers (OrderDraft (..), Provider (..), ProviderError (..), ProviderInvoice (..), WebhookError (..))
import BadgeService.Store.Invoices (CreateError (..), InvoicePayment (..), InvoiceRow (..), NewInvoice (..), cancelOpenInvoice, codeHashExists, createInvoiceRows, cryptoCurrencyText, getInvoice, getInvoiceByProviderRef, invoiceStatusText, newInvoiceId, paymentHolds, readCatalogRows, textToInvoiceStatus, truncateToSecond)
import BadgeService.Waiters (Seen, Waiters, awaitStatus, publish)
import StoreService.Catalog (PricedOffer (..), priceOffer)
import StoreService.Config (BTCPayConfig (..), ListenerConfig (..), ServiceConfig (..), SpeedPolicy (..), StripeConfig (..), defaultExpiryMinutes, defaultSessionMinutes)
import StoreService.Poller (ReadHints, queueReadHint)
import StoreService.Providers (OrderDraft (..), Provider (..), ProviderError (..), ProviderInvoice (..), WebhookError (..))
import StoreService.Store.Invoices (CreateError (..), InvoicePayment (..), InvoiceRow (..), NewInvoice (..), cancelOpenInvoice, codeHashExists, createInvoiceRows, cryptoCurrencyText, getInvoice, getInvoiceByProviderRef, invoiceStatusText, newInvoiceId, paymentHolds, readCatalogRows, textToInvoiceStatus, truncateToSecond)
import StoreService.Waiters (Seen, Waiters, awaitStatus, publish)
import Control.Concurrent.STM
import qualified Control.Exception as E
import BadgeService.Log (logError, logInfo, logWarn)
import StoreService.Log (logError, logInfo, logWarn)
import Control.Monad (forM_, when)
import Data.Aeson ((.=))
import qualified Data.Aeson as J
@@ -336,7 +336,7 @@ exportWebapp lc@ListenerConfig {lStaticDir, lWebappExportDir} stripeCfg =
emptyDir out
copyTree lStaticDir out
prepareShell lc stripeCfg >>= mapM_ (LB.writeFile (out </> "index.html"))
logInfo ("badge service: exported the webapp to " <> T.pack out)
logInfo ("store service: exported the webapp to " <> T.pack out)
-- | Contents only: the directory itself may be a bind or volume mount point that cannot be removed.
emptyDir :: FilePath -> IO ()
@@ -735,7 +735,7 @@ runWebListener env = do
warnIfHeaderTrustIsExposed :: ListenerConfig -> IO ()
warnIfHeaderTrustIsExposed ListenerConfig {lHost, lTrustForwardedFor} =
when (lTrustForwardedFor && not (isLoopbackHost lHost)) $
logWarn ("badge service: trust_forwarded_for is on and the listener binds " <> lHost <> "; every caller can then choose its own rate limit bucket unless a proxy sets the header")
logWarn ("store service: trust_forwarded_for is on and the listener binds " <> lHost <> "; every caller can then choose its own rate limit bucket unless a proxy sets the header")
isLoopbackHost :: Text -> Bool
isLoopbackHost h = h `elem` ["127.0.0.1", "::1", "localhost"]
@@ -3,8 +3,8 @@
; the long poll's `wait`, `seenPaid` and `seenFull` all travel in it
host = 127.0.0.1
port = 8080
; required: the directory `npm run build` writes in apps/simplex-badge-service/web
static_dir = ./apps/simplex-badge-service/web/dist
; required: the directory `npm run build` writes in apps/simplex-store-service/web
static_dir = ./apps/simplex-store-service/web/dist
; serve the webapp over HTTP. On (default) is the all-in-one deployment. Off is a split deployment
; where a reverse proxy serves the exported folder and this service is only the API and webhooks.
serve_webapp = on
@@ -53,10 +53,10 @@ idle_seconds = 60
; Keep the key file readable by this service alone.
;[apple]
;bundle_id = chat.simplex.app
;root_certificates = /etc/simplex-badge-service/AppleRootCA-G3.cer
;root_certificates = /etc/simplex-store-service/AppleRootCA-G3.cer
;api_key_id = 2X9R4HXF34
;api_issuer_id = 57246542-96fe-1a63-e053-0824d011072a
;api_private_key_file = /etc/simplex-badge-service/AuthKey_2X9R4HXF34.p8
;api_private_key_file = /etc/simplex-store-service/AuthKey_2X9R4HXF34.p8
;api_host = https://api.storekit.itunes.apple.com
; verifies Play purchases with the Google Play Developer API. Omit the whole section and the service answers
@@ -67,7 +67,7 @@ idle_seconds = 60
; already acknowledged itself is answered internal until the permission is granted. Keep the file readable by this service alone.
;[google]
;package_name = chat.simplex.app
;service_account_file = /etc/simplex-badge-service/play-service-account.json
;service_account_file = /etc/simplex-store-service/play-service-account.json
; the key this service signs credentials with. index is the index clients verify against, so
; private_key has to be one whose public half already ships in the apps at that index: a fresh
@@ -68,23 +68,23 @@ is plain TypeScript, tested directly in Node.
## Running the real service against this build
**`mock/server.py` is not the service.** The service is the Haskell
executable `simplex-badge-service`, in `apps/simplex-badge-service/`, and
executable `simplex-store-service`, in `apps/simplex-store-service/`, and
`dist/` is the directory its listener serves. Nothing about the page changes
between the two — the service matches this build, never the reverse.
```
# 1. build the page. dist/ is the deploy tree: index.html, sw.js, assets/<hash>/
cd apps/simplex-badge-service/web
cd apps/simplex-store-service/web
npm install && npm run build
cd ../../..
# 2. configuration, from the committed example. Copy it IN
# PLACE, beside the example: that path is the one .gitignore covers, and this
# file is about to hold a real api_key and webhook_secret.
cd apps/simplex-badge-service
cp badge_service.ini.example badge_service.ini
cd apps/simplex-store-service
cp store_service.ini.example store_service.ini
cd ../..
# static_dir = ./apps/simplex-badge-service/web/dist <- the build above
# static_dir = ./apps/simplex-store-service/web/dist <- the build above
# [btcpay] = a real store's host, api_key, store_id and webhook_secret,
# or delete the whole section to disable BTC and XMR (the provider-unavailable screen)
# [issuer] = uncomment the section and put a real issuer secret in private_key,
@@ -98,28 +98,28 @@ cd ../..
# without a key it could sign a credential with. Put it in the ini's [issuer]
# section, or pass --issuer-key-idx and --issuer-secret, which override it.
# `simplex-chat badge keygen` prints a pair.
cabal run simplex-badge-service -- \
--service-config apps/simplex-badge-service/badge_service.ini
cabal run simplex-store-service -- \
--service-config apps/simplex-store-service/store_service.ini
```
Then open the `[listener]` host and port — `http://127.0.0.1:8080/` as the
example ships. `static_dir` is relative to the working directory, so run from
the repository root or make it absolute.
**The executable is the whole badge service, not just this listener.**
`badgeService` starts `simplexChatCore` unconditionally and the web listener
**The executable is the whole store service, not just this listener.**
`storeService` starts `simplexChatCore` unconditionally and the web listener
is one lane beside the chat one, so a local run opens or creates a chat
database (`printDbOpts` names the path at startup) and does agent network
work. `--no-address` skips creating the service's contact address on first
start, which a run of the web listener alone does not need.
*These three steps are read out of `Options.hs`, `Service.hs`, `Config.hs` and
`badge_service.ini.example` rather than from a run — driving them end to end
`store_service.ini.example` rather than from a run — driving them end to end
needs a chat database and a real BTCPay store.*
What the mock cannot stand in for:
| | `mock/server.py` | `simplex-badge-service` |
| | `mock/server.py` | `simplex-store-service` |
|---|---|---|
| Invoices | invented in memory | created at BTCPay over Greenfield |
| Payment detected by | `POST /control/settle/:id`, an endpoint that exists nowhere else | a poller reading the provider, which is the only thing that carries authority |
@@ -129,10 +129,10 @@ What the mock cannot stand in for:
The Haskell side's own end-to-end coverage of that lane — checkout, payment,
polling, partial payment, expiry, late settlement and replay, all against a
fake Greenfield — is `tests/Bots/BadgeService/WebTests.hs`:
fake Greenfield — is `tests/Bots/StoreService/WebTests.hs`:
```
cabal test --test-options='-m "/SimpleX badge service/"'
cabal test --test-options='-m "/SimpleX store service/"'
```
## Running the mock
@@ -311,7 +311,7 @@ def main():
# so only a publishable key (pk_) is allowed.
sys.exit("mock: STRIPE_PUBLISHABLE_KEY must be a publishable key (pk_...)")
server = Server(("127.0.0.1", port), Handler)
print(f"mock badge service on http://localhost:{port}", flush=True)
print(f"mock store service on http://localhost:{port}", flush=True)
print("stripe: " + (f"publishable key {STRIPE_PUBLISHABLE_KEY[:11]}… — the real card form"
if STRIPE_PUBLISHABLE_KEY
else "no STRIPE_PUBLISHABLE_KEY — no card form; pay with btc or xmr"),
File renamed without changes.

Before

Width:  |  Height:  |  Size: 317 KiB

After

Width:  |  Height:  |  Size: 317 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 294 KiB

After

Width:  |  Height:  |  Size: 294 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 4.3 KiB

After

Width:  |  Height:  |  Size: 4.3 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 4.3 KiB

After

Width:  |  Height:  |  Size: 4.3 KiB

Loaded 100 of 191 files, more files were not shown because too many files have changed in this diff. Show more