stacker.news/api/resolvers/index.js

60 lines
1.9 KiB
JavaScript
Raw Normal View History

2021-03-25 19:29:24 +00:00
import user from './user'
import message from './message'
2021-04-12 18:05:09 +00:00
import item from './item'
2021-04-30 21:42:51 +00:00
import wallet from './wallet'
2021-06-27 03:09:39 +00:00
import lnurl from './lnurl'
2021-08-17 18:15:24 +00:00
import notifications from './notifications'
2021-10-12 23:49:04 +00:00
import invite from './invite'
2022-02-17 17:23:43 +00:00
import sub from './sub'
2022-05-12 18:44:21 +00:00
import upload from './upload'
2023-05-18 23:41:56 +00:00
import growth from './growth'
2022-10-20 22:44:44 +00:00
import search from './search'
2022-12-08 00:04:02 +00:00
import rewards from './rewards'
2022-12-19 22:27:52 +00:00
import referrals from './referrals'
import price from './price'
2023-07-27 00:18:42 +00:00
import { GraphQLJSONObject as JSONObject } from 'graphql-type-json'
2023-06-20 01:26:34 +00:00
import admin from './admin'
import blockHeight from './blockHeight'
import chainFee from './chainFee'
2023-07-27 00:18:42 +00:00
import { GraphQLScalarType, Kind } from 'graphql'
2023-11-22 16:30:43 +00:00
import { createIntScalar } from 'graphql-scalar'
backend payment optimism (#1195) * wip backend optimism * another inch * make action state transitions only happen once * another inch * almost ready for testing * use interactive txs * another inch * ready for basic testing * lint fix * inches * wip item update * get item update to work * donate and downzap * inchy inch * fix territory paid actions * wip usePaidMutation * usePaidMutation error handling * PENDING_HELD and HELD transitions, gql paidAction return types * mostly working pessimism * make sure invoice field is present in optimisticResponse * inches * show optimistic values to current me * first pass at notifications and payment status reporting * fix migration to have withdrawal hash * reverse optimism on payment failure * Revert "Optimistic updates via pending sats in item context (#1229)" This reverts commit 93713b33df9bc3701dc5a692b86a04ff64e8cfb1. * add onCompleted to usePaidMutation * onPaid and onPayError for new comments * use 'IS DISTINCT FROM' for NULL invoiceActionState columns * make usePaidMutation easier to read * enhance invoice qr * prevent actions on unpaid items * allow navigation to action's invoice * retry create item * start edit window after item is paid for * fix ux of retries from notifications * refine retries * fix optimistic downzaps * remember item updates can't be retried * store reference to action item in invoice * remove invoice modal layout shift * fix destructuring * fix zap undos * make sure ItemAct is paid in aggregate queries * dont toast on long press zap undo * fix delete and remindme bots * optimistic poll votes with retries * fix retry notifications and invoice item context * fix pessimisitic typo * item mentions and mention notifications * dont show payment retry on item popover * make bios work * refactor paidAction transitions * remove stray console.log * restore docker compose nwc settings * add new todos * persist qr modal on post submission + unify item form submission * fix post edit threshold * make bounty payments work * make job posting work * remove more store procedure usage ... document serialization concerns * dont use dynamic imports for paid action modules * inline comment denormalization * create item starts with median votes * fix potential of serialization anomalies in zaps * dont trigger notification indicator on successful paid action invoices * ignore invoiceId on territory actions and add optimistic concurrency control * begin docs for paid actions * better error toasts and fix apollo cache warnings * small documentation enhancements * improve paid action docs * optimistic concurrency control for territory updates * use satsToMsats and msatsToSats helpers * explictly type raw query template parameters * improve consistency of nested relation names * complete paid action docs * useEffect for canEdit on payment * make sure invoiceId is provided when required * don't return null when expecting array * remove buy credits * move verifyPayment to paidAction * fix comments invoicePaidAt time zone * close nwc connections once * grouped logs for paid actions * stop invoiceWaitUntilPaid if not attempting to pay * allow actionState to transition directly from HELD to PAID * make paid mutation wait until pessimistic are fully paid * change button text when form submits/pays * pulsing form submit button * ignore me in notification indicator for territory subscription * filter unpaid items from more queries * fix donation stike timing * fix pending poll vote * fix recent item notifcation padding * no default form submitting button text * don't show paying on submit button on free edits * fix territory autorenew with fee credits * reorg readme * allow jobs to be editted forever * fix image uploads * more filter fixes for aggregate views * finalize paid action invoice expirations * remove unnecessary async * keep clientside cache normal/consistent * add more detail to paid action doc * improve paid action table * remove actionType guard * fix top territories * typo api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * typo components/use-paid-mutation.js Co-authored-by: ekzyis <ek@stacker.news> * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> * encorporate ek feeback * more ek suggestions * fix 'cost to post' hover on items * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> --------- Co-authored-by: ekzyis <ek@stacker.news>
2024-07-01 17:02:29 +00:00
import paidAction from './paidAction'
Encrypted device sync (#1373) * user vault * code cleanup and fixes * improve ui * prevent name collisions between users on the same device * some improvements * implement storage migration * comments and cleanup * make connect button primary instead of warning * move show passphrase in new line (improvement for small screen devices) * make show passphrase field readOnly * fixes * fix vault key unsync * implicit migration * move device sync under general tab * fix locally disabled wallets and default wallet selection * improve text * remove useless SSR check * add auth checks * Rename variables * Fix missing await * Refactor local<>vault storage interface I've changed quite some things here. Attempt of a summary: * storageKey is now only controlled by useVaultStorageState I've noticed that dealing with how storage keys are generated (to apply user scope) was handled in two places: the existing wallet code and in the new vault code. This was confusing and error-prone. I've fixed that by completely relying on the new vault code to generate correct storage keys. * refactored migration Migration now simply encrypts any existing local wallets and sends them to the server. On success, the local unencrypted version is deleted. The previous code seemed to unnecessarily generate new local entries prefixed by 'vault:'. However, since we either use unencrypted local state OR use the encrypted vault on the server for the data, I didn't see any need for these. Migration seems to work just as well as before. * removed unnecessary state In the <DeviceSync> component, enabled & connected were using a unnecessary combo of useState+useEffect. They were only using variables that are always available during render so simple assignments were enough. * other minor changes include: * early returns * remove unnecessary SSR checks in useEffect or useCallback * formatting, comments * remove unnecessary me? to expose possible bugs * Fix missing dependency for useZap This didn't cause any bugs because useWallet returns everything we need on first render. This caused a bug with E2EE device sync branch though since there the wallet is loaded async. This meant that during payment, the wallet config was undefined. * Assume JSON during encryption and decryption * Fix stale value from cache served on next fetches * Add wallet.perDevice field This adds 'perDevice' as a new wallet field to force local storage. For example, WebLN should not be synced across devices. * Remove debug buttons * Rename userVault -> vault * Update console.log's * revert some of the migration and key handling changes. restore debug buttons for testing * Fix existing wallets not loaded * Pass in localOnly and generate localStorageKey once * Small refactor of migration * Fix wallet drag and drop * Add passphrase copy button * Fix priorityOnly -> skipTests * Disable autocompletion for reset confirmation prompt * Show wrong passphrase as input error * Move code into components/device-sync.js * Import/export passphrase via QR code * Fix modal back button invisible in light mode * Fix modal closed even on connect error * Use me-2 for cancel/close button * Some rephrasing * Fix wallet detach * Remove debug buttons * Fix QR code scan in dark mode * Don't allow custom passphrases * More rephrasing * Only use schema if not enabled * Fix typo in comment * Replace 'generate passphrase' button with reload icon * Add comment about IV reuse in GCM * Use 600k iterations as recommended by OWASP * Set extractable to false where not needed * use-vault fallbacks to local storage only for anonymous users * fix localStorage reset on logout * add copy button * move reset out of modals * hide server side errors * hardened passphrase storage * do not show passphrase even if hardened storage is disabled (ie. indexeddb not supported) * show qr code button on passphrase creation * use toast for serverside error * Move key (de)serialization burden to get/setLocalKey functions * password textarea and remove qr * don't print plaintext vault values into console --------- Co-authored-by: ekzyis <ek@stacker.news> Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com> Co-authored-by: k00b <k00b@stacker.news>
2024-10-01 19:55:01 +00:00
import vault from './vault'
2023-07-27 00:18:42 +00:00
const date = new GraphQLScalarType({
name: 'Date',
description: 'Date custom scalar type',
serialize (value) {
if (value instanceof Date) {
return value.toISOString() // Convert outgoing Date to string for JSON
} else if (typeof value === 'string') {
return value
}
throw Error('GraphQL Date Scalar serializer expected a `Date` object got `' + typeof value + '` ' + value)
},
parseValue (value) {
if (typeof value === 'string') {
return new Date(value) // Convert incoming string to Date
}
throw new Error('GraphQL Date Scalar parser expected a `string`')
},
parseLiteral (ast) {
if (ast.kind === Kind.STRING) {
// Convert hard-coded AST string to integer and then to Date
return new Date(ast.value)
}
// Invalid hard-coded value (not an integer)
return null
}
})
2021-03-25 19:29:24 +00:00
2023-11-22 16:30:43 +00:00
const limit = createIntScalar({
name: 'Limit',
description: 'Limit custom scalar type',
maximum: 1000
})
2022-05-12 18:44:21 +00:00
export default [user, item, message, wallet, lnurl, notifications, invite, sub,
backend payment optimism (#1195) * wip backend optimism * another inch * make action state transitions only happen once * another inch * almost ready for testing * use interactive txs * another inch * ready for basic testing * lint fix * inches * wip item update * get item update to work * donate and downzap * inchy inch * fix territory paid actions * wip usePaidMutation * usePaidMutation error handling * PENDING_HELD and HELD transitions, gql paidAction return types * mostly working pessimism * make sure invoice field is present in optimisticResponse * inches * show optimistic values to current me * first pass at notifications and payment status reporting * fix migration to have withdrawal hash * reverse optimism on payment failure * Revert "Optimistic updates via pending sats in item context (#1229)" This reverts commit 93713b33df9bc3701dc5a692b86a04ff64e8cfb1. * add onCompleted to usePaidMutation * onPaid and onPayError for new comments * use 'IS DISTINCT FROM' for NULL invoiceActionState columns * make usePaidMutation easier to read * enhance invoice qr * prevent actions on unpaid items * allow navigation to action's invoice * retry create item * start edit window after item is paid for * fix ux of retries from notifications * refine retries * fix optimistic downzaps * remember item updates can't be retried * store reference to action item in invoice * remove invoice modal layout shift * fix destructuring * fix zap undos * make sure ItemAct is paid in aggregate queries * dont toast on long press zap undo * fix delete and remindme bots * optimistic poll votes with retries * fix retry notifications and invoice item context * fix pessimisitic typo * item mentions and mention notifications * dont show payment retry on item popover * make bios work * refactor paidAction transitions * remove stray console.log * restore docker compose nwc settings * add new todos * persist qr modal on post submission + unify item form submission * fix post edit threshold * make bounty payments work * make job posting work * remove more store procedure usage ... document serialization concerns * dont use dynamic imports for paid action modules * inline comment denormalization * create item starts with median votes * fix potential of serialization anomalies in zaps * dont trigger notification indicator on successful paid action invoices * ignore invoiceId on territory actions and add optimistic concurrency control * begin docs for paid actions * better error toasts and fix apollo cache warnings * small documentation enhancements * improve paid action docs * optimistic concurrency control for territory updates * use satsToMsats and msatsToSats helpers * explictly type raw query template parameters * improve consistency of nested relation names * complete paid action docs * useEffect for canEdit on payment * make sure invoiceId is provided when required * don't return null when expecting array * remove buy credits * move verifyPayment to paidAction * fix comments invoicePaidAt time zone * close nwc connections once * grouped logs for paid actions * stop invoiceWaitUntilPaid if not attempting to pay * allow actionState to transition directly from HELD to PAID * make paid mutation wait until pessimistic are fully paid * change button text when form submits/pays * pulsing form submit button * ignore me in notification indicator for territory subscription * filter unpaid items from more queries * fix donation stike timing * fix pending poll vote * fix recent item notifcation padding * no default form submitting button text * don't show paying on submit button on free edits * fix territory autorenew with fee credits * reorg readme * allow jobs to be editted forever * fix image uploads * more filter fixes for aggregate views * finalize paid action invoice expirations * remove unnecessary async * keep clientside cache normal/consistent * add more detail to paid action doc * improve paid action table * remove actionType guard * fix top territories * typo api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * typo components/use-paid-mutation.js Co-authored-by: ekzyis <ek@stacker.news> * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> * encorporate ek feeback * more ek suggestions * fix 'cost to post' hover on items * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> --------- Co-authored-by: ekzyis <ek@stacker.news>
2024-07-01 17:02:29 +00:00
upload, search, growth, rewards, referrals, price, admin, blockHeight, chainFee,
Encrypted device sync (#1373) * user vault * code cleanup and fixes * improve ui * prevent name collisions between users on the same device * some improvements * implement storage migration * comments and cleanup * make connect button primary instead of warning * move show passphrase in new line (improvement for small screen devices) * make show passphrase field readOnly * fixes * fix vault key unsync * implicit migration * move device sync under general tab * fix locally disabled wallets and default wallet selection * improve text * remove useless SSR check * add auth checks * Rename variables * Fix missing await * Refactor local<>vault storage interface I've changed quite some things here. Attempt of a summary: * storageKey is now only controlled by useVaultStorageState I've noticed that dealing with how storage keys are generated (to apply user scope) was handled in two places: the existing wallet code and in the new vault code. This was confusing and error-prone. I've fixed that by completely relying on the new vault code to generate correct storage keys. * refactored migration Migration now simply encrypts any existing local wallets and sends them to the server. On success, the local unencrypted version is deleted. The previous code seemed to unnecessarily generate new local entries prefixed by 'vault:'. However, since we either use unencrypted local state OR use the encrypted vault on the server for the data, I didn't see any need for these. Migration seems to work just as well as before. * removed unnecessary state In the <DeviceSync> component, enabled & connected were using a unnecessary combo of useState+useEffect. They were only using variables that are always available during render so simple assignments were enough. * other minor changes include: * early returns * remove unnecessary SSR checks in useEffect or useCallback * formatting, comments * remove unnecessary me? to expose possible bugs * Fix missing dependency for useZap This didn't cause any bugs because useWallet returns everything we need on first render. This caused a bug with E2EE device sync branch though since there the wallet is loaded async. This meant that during payment, the wallet config was undefined. * Assume JSON during encryption and decryption * Fix stale value from cache served on next fetches * Add wallet.perDevice field This adds 'perDevice' as a new wallet field to force local storage. For example, WebLN should not be synced across devices. * Remove debug buttons * Rename userVault -> vault * Update console.log's * revert some of the migration and key handling changes. restore debug buttons for testing * Fix existing wallets not loaded * Pass in localOnly and generate localStorageKey once * Small refactor of migration * Fix wallet drag and drop * Add passphrase copy button * Fix priorityOnly -> skipTests * Disable autocompletion for reset confirmation prompt * Show wrong passphrase as input error * Move code into components/device-sync.js * Import/export passphrase via QR code * Fix modal back button invisible in light mode * Fix modal closed even on connect error * Use me-2 for cancel/close button * Some rephrasing * Fix wallet detach * Remove debug buttons * Fix QR code scan in dark mode * Don't allow custom passphrases * More rephrasing * Only use schema if not enabled * Fix typo in comment * Replace 'generate passphrase' button with reload icon * Add comment about IV reuse in GCM * Use 600k iterations as recommended by OWASP * Set extractable to false where not needed * use-vault fallbacks to local storage only for anonymous users * fix localStorage reset on logout * add copy button * move reset out of modals * hide server side errors * hardened passphrase storage * do not show passphrase even if hardened storage is disabled (ie. indexeddb not supported) * show qr code button on passphrase creation * use toast for serverside error * Move key (de)serialization burden to get/setLocalKey functions * password textarea and remove qr * don't print plaintext vault values into console --------- Co-authored-by: ekzyis <ek@stacker.news> Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com> Co-authored-by: k00b <k00b@stacker.news>
2024-10-01 19:55:01 +00:00
{ JSONObject }, { Date: date }, { Limit: limit }, paidAction, vault]