Repository: maybe-finance/maybe-archive Branch: main Commit: 04bf3d135bdb Files: 1004 Total size: 2.6 MB Directory structure: gitextract_0nt4pr3f/ ├── .dockerignore ├── .editorconfig ├── .eslintrc.json ├── .github/ │ ├── ISSUE_TEMPLATE/ │ │ ├── bug_report.md │ │ └── feature-request-or-improvement.md │ └── workflows/ │ └── docker-publish.yml ├── .gitignore ├── .husky/ │ └── pre-commit ├── .prettierignore ├── .prettierrc ├── .storybook/ │ ├── main.js │ └── tsconfig.json ├── .vscode/ │ ├── extensions.json │ ├── launch.json │ └── settings.json ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── apps/ │ ├── .gitkeep │ ├── client/ │ │ ├── .babelrc.json │ │ ├── .eslintrc.json │ │ ├── .storybook/ │ │ │ ├── main.js │ │ │ ├── manager.js │ │ │ ├── preview.js │ │ │ ├── theme.js │ │ │ └── tsconfig.json │ │ ├── Dockerfile │ │ ├── components/ │ │ │ ├── APM.tsx │ │ │ ├── Maintenance.stories.tsx │ │ │ ├── Maintenance.tsx │ │ │ ├── Meta.tsx │ │ │ └── account-views/ │ │ │ ├── DefaultView.tsx │ │ │ ├── InvestmentView.tsx │ │ │ ├── LoanView.tsx │ │ │ └── index.ts │ │ ├── env.sh │ │ ├── env.ts │ │ ├── jest.config.ts │ │ ├── next-env.d.ts │ │ ├── next.config.js │ │ ├── pages/ │ │ │ ├── 404.tsx │ │ │ ├── _app.tsx │ │ │ ├── _document.tsx │ │ │ ├── accounts/ │ │ │ │ ├── [accountId].tsx │ │ │ │ └── index.tsx │ │ │ ├── api/ │ │ │ │ ├── auth/ │ │ │ │ │ └── [...nextauth].ts │ │ │ │ └── card.tsx │ │ │ ├── card/ │ │ │ │ └── [id].tsx │ │ │ ├── data-editor.tsx │ │ │ ├── index.tsx │ │ │ ├── login.tsx │ │ │ ├── onboarding.tsx │ │ │ ├── plans/ │ │ │ │ ├── [planId].tsx │ │ │ │ ├── create.tsx │ │ │ │ └── index.tsx │ │ │ ├── register.tsx │ │ │ ├── settings.tsx │ │ │ └── upgrade.tsx │ │ ├── postcss.config.js │ │ ├── public/ │ │ │ ├── .gitkeep │ │ │ ├── __appenv.js │ │ │ └── assets/ │ │ │ ├── browserconfig.xml │ │ │ └── site.webmanifest │ │ ├── stories/ │ │ │ └── 404.stories.tsx │ │ ├── styles.css │ │ ├── tailwind.config.js │ │ ├── tsconfig.json │ │ └── tsconfig.spec.json │ ├── e2e/ │ │ ├── .eslintrc.json │ │ ├── cypress.config.ts │ │ ├── src/ │ │ │ ├── e2e/ │ │ │ │ ├── accounts.cy.ts │ │ │ │ ├── auth.cy.ts │ │ │ │ └── subscription.cy.ts │ │ │ ├── fixtures/ │ │ │ │ └── stripe/ │ │ │ │ ├── checkoutSessionCompleted.ts │ │ │ │ ├── customerSubscriptionCreated.ts │ │ │ │ ├── customerSubscriptionDeleted.ts │ │ │ │ └── index.ts │ │ │ └── support/ │ │ │ ├── commands.ts │ │ │ ├── e2e.ts │ │ │ └── index.ts │ │ └── tsconfig.json │ ├── server/ │ │ ├── .eslintrc.json │ │ ├── Dockerfile │ │ ├── jest.config.ts │ │ ├── src/ │ │ │ ├── app/ │ │ │ │ ├── __tests__/ │ │ │ │ │ ├── account.integration.spec.ts │ │ │ │ │ ├── balance-sync.integration.spec.ts │ │ │ │ │ ├── connection.integration.spec.ts │ │ │ │ │ ├── insights.integration.spec.ts │ │ │ │ │ ├── net-worth.integration.spec.ts │ │ │ │ │ ├── prisma.integration.spec.ts │ │ │ │ │ ├── stripe.integration.spec.ts │ │ │ │ │ ├── test-data/ │ │ │ │ │ │ ├── portfolio-1/ │ │ │ │ │ │ │ ├── holdings.csv │ │ │ │ │ │ │ ├── securities.csv │ │ │ │ │ │ │ └── transactions.csv │ │ │ │ │ │ └── portfolio-2/ │ │ │ │ │ │ ├── holdings.csv │ │ │ │ │ │ ├── securities.csv │ │ │ │ │ │ └── transactions.csv │ │ │ │ │ └── utils/ │ │ │ │ │ ├── account.ts │ │ │ │ │ ├── axios.ts │ │ │ │ │ ├── csv.ts │ │ │ │ │ ├── server.ts │ │ │ │ │ └── user.ts │ │ │ │ ├── admin/ │ │ │ │ │ └── views/ │ │ │ │ │ ├── pages/ │ │ │ │ │ │ ├── dashboard.ejs │ │ │ │ │ │ └── index.ejs │ │ │ │ │ └── partials/ │ │ │ │ │ └── head.ejs │ │ │ │ ├── app.ts │ │ │ │ ├── lib/ │ │ │ │ │ ├── ability.ts │ │ │ │ │ ├── email.ts │ │ │ │ │ ├── endpoint.ts │ │ │ │ │ ├── logger.ts │ │ │ │ │ ├── prisma.ts │ │ │ │ │ ├── stripe.ts │ │ │ │ │ ├── teller.ts │ │ │ │ │ ├── types.ts │ │ │ │ │ └── webhook.ts │ │ │ │ ├── middleware/ │ │ │ │ │ ├── auth-error-handler.ts │ │ │ │ │ ├── dev-only.ts │ │ │ │ │ ├── error-handler.ts │ │ │ │ │ ├── identify-user.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── maintenance.ts │ │ │ │ │ ├── superjson.ts │ │ │ │ │ ├── validate-auth-jwt.ts │ │ │ │ │ └── validate-teller-signature.ts │ │ │ │ ├── routes/ │ │ │ │ │ ├── account-rollup.router.ts │ │ │ │ │ ├── accounts.router.ts │ │ │ │ │ ├── admin.router.ts │ │ │ │ │ ├── connections.router.ts │ │ │ │ │ ├── e2e.router.ts │ │ │ │ │ ├── holdings.router.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── institutions.router.ts │ │ │ │ │ ├── plans.router.ts │ │ │ │ │ ├── public.router.ts │ │ │ │ │ ├── securities.router.ts │ │ │ │ │ ├── teller.router.ts │ │ │ │ │ ├── tools.router.ts │ │ │ │ │ ├── transactions.router.ts │ │ │ │ │ ├── users.router.ts │ │ │ │ │ ├── valuations.router.ts │ │ │ │ │ └── webhooks.router.ts │ │ │ │ └── trpc.ts │ │ │ ├── assets/ │ │ │ │ ├── script.js │ │ │ │ └── styles.css │ │ │ ├── env.ts │ │ │ ├── environments/ │ │ │ │ ├── environment.prod.ts │ │ │ │ └── environment.ts │ │ │ └── main.ts │ │ ├── tsconfig.app.json │ │ ├── tsconfig.json │ │ └── tsconfig.spec.json │ └── workers/ │ ├── .eslintrc.json │ ├── Dockerfile │ ├── jest.config.ts │ ├── src/ │ │ ├── app/ │ │ │ ├── __tests__/ │ │ │ │ ├── helpers/ │ │ │ │ │ └── user.test-helper.ts │ │ │ │ ├── queue.integration.spec.ts │ │ │ │ ├── security-sync.integration.spec.ts │ │ │ │ └── teller.integration.spec.ts │ │ │ ├── lib/ │ │ │ │ ├── di.ts │ │ │ │ ├── email.ts │ │ │ │ ├── logger.ts │ │ │ │ ├── prisma.ts │ │ │ │ ├── stripe.ts │ │ │ │ └── teller.ts │ │ │ └── services/ │ │ │ ├── bull-queue-event-handler.ts │ │ │ ├── index.ts │ │ │ └── worker-error.service.ts │ │ ├── assets/ │ │ │ └── .gitkeep │ │ ├── env.ts │ │ ├── environments/ │ │ │ ├── environment.prod.ts │ │ │ └── environment.ts │ │ ├── main.ts │ │ └── utils.ts │ ├── tsconfig.app.json │ ├── tsconfig.json │ └── tsconfig.spec.json ├── babel.config.json ├── custom-express.d.ts ├── docker-compose.test.yml ├── docker-compose.yml ├── jest.config.ts ├── jest.preset.js ├── libs/ │ ├── .gitkeep │ ├── client/ │ │ ├── features/ │ │ │ ├── .babelrc │ │ │ ├── .eslintrc.json │ │ │ ├── jest.config.ts │ │ │ ├── src/ │ │ │ │ ├── account/ │ │ │ │ │ ├── AccountMenu.tsx │ │ │ │ │ ├── AccountsSidebar.tsx │ │ │ │ │ ├── PageTitle.tsx │ │ │ │ │ └── index.ts │ │ │ │ ├── accounts-list/ │ │ │ │ │ ├── Account.tsx │ │ │ │ │ ├── AccountDevTools.tsx │ │ │ │ │ ├── AccountGroup.tsx │ │ │ │ │ ├── AccountGroupContainer.tsx │ │ │ │ │ ├── ConnectedAccountGroup.tsx │ │ │ │ │ ├── DeleteConnectionDialog.tsx │ │ │ │ │ ├── DisconnectedAccountGroup.tsx │ │ │ │ │ ├── ManualAccountGroup.tsx │ │ │ │ │ └── index.ts │ │ │ │ ├── accounts-manager/ │ │ │ │ │ ├── AccountTypeGrid.tsx │ │ │ │ │ ├── AccountTypeSelector.tsx │ │ │ │ │ ├── AccountValuationFormFields.tsx │ │ │ │ │ ├── AccountsManager.tsx │ │ │ │ │ ├── DeleteAccount.tsx │ │ │ │ │ ├── EditAccount.tsx │ │ │ │ │ ├── InstitutionGrid.tsx │ │ │ │ │ ├── InstitutionList.tsx │ │ │ │ │ ├── asset/ │ │ │ │ │ │ ├── AddAsset.tsx │ │ │ │ │ │ ├── AssetForm.tsx │ │ │ │ │ │ ├── EditAsset.tsx │ │ │ │ │ │ └── index.ts │ │ │ │ │ ├── connected/ │ │ │ │ │ │ ├── ConnectedAccountForm.tsx │ │ │ │ │ │ ├── EditConnectedAccount.tsx │ │ │ │ │ │ └── index.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── liability/ │ │ │ │ │ │ ├── AddLiability.tsx │ │ │ │ │ │ ├── EditLiability.tsx │ │ │ │ │ │ ├── LiabilityForm.tsx │ │ │ │ │ │ └── index.ts │ │ │ │ │ ├── property/ │ │ │ │ │ │ ├── AddProperty.tsx │ │ │ │ │ │ ├── EditProperty.tsx │ │ │ │ │ │ ├── PropertyForm.tsx │ │ │ │ │ │ └── index.ts │ │ │ │ │ ├── stock/ │ │ │ │ │ │ ├── AddStock.tsx │ │ │ │ │ │ ├── CreateStockAccount.tsx │ │ │ │ │ │ ├── StockForm.tsx │ │ │ │ │ │ └── index.ts │ │ │ │ │ └── vehicle/ │ │ │ │ │ ├── AddVehicle.tsx │ │ │ │ │ ├── EditVehicle.tsx │ │ │ │ │ ├── VehicleForm.tsx │ │ │ │ │ └── index.ts │ │ │ │ ├── data-editor/ │ │ │ │ │ ├── account/ │ │ │ │ │ │ ├── AccountEditor.tsx │ │ │ │ │ │ └── index.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ └── transaction/ │ │ │ │ │ ├── TransactionEditor.tsx │ │ │ │ │ └── index.ts │ │ │ │ ├── holdings-list/ │ │ │ │ │ ├── CostBasisForm.tsx │ │ │ │ │ ├── HoldingList.tsx │ │ │ │ │ ├── HoldingPopout.tsx │ │ │ │ │ ├── HoldingsTable.tsx │ │ │ │ │ ├── SecurityPriceChart.tsx │ │ │ │ │ └── index.ts │ │ │ │ ├── index.ts │ │ │ │ ├── insights/ │ │ │ │ │ ├── explainers/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── investments/ │ │ │ │ │ │ │ ├── AverageReturn.tsx │ │ │ │ │ │ │ ├── Contributions.tsx │ │ │ │ │ │ │ ├── PotentialGainLoss.tsx │ │ │ │ │ │ │ ├── SectorAllocation.tsx │ │ │ │ │ │ │ ├── TotalFees.tsx │ │ │ │ │ │ │ └── index.ts │ │ │ │ │ │ └── net-worth/ │ │ │ │ │ │ ├── BadDebt.tsx │ │ │ │ │ │ ├── GoodDebt.tsx │ │ │ │ │ │ ├── IlliquidAssets.tsx │ │ │ │ │ │ ├── IncomePayingDebt.tsx │ │ │ │ │ │ ├── LiquidAssets.tsx │ │ │ │ │ │ ├── NetWorthTrend.tsx │ │ │ │ │ │ ├── SafetyNet.tsx │ │ │ │ │ │ ├── TotalDebtRatio.tsx │ │ │ │ │ │ ├── YieldingAssets.tsx │ │ │ │ │ │ └── index.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ └── insight-states.ts │ │ │ │ ├── investment-transactions-list/ │ │ │ │ │ ├── InvestmentTransactionList.tsx │ │ │ │ │ ├── InvestmentTransactionListItem.tsx │ │ │ │ │ └── index.ts │ │ │ │ ├── layout/ │ │ │ │ │ ├── DesktopLayout.tsx │ │ │ │ │ ├── FullPageLayout.tsx │ │ │ │ │ ├── MenuPopover.tsx │ │ │ │ │ ├── MobileLayout.tsx │ │ │ │ │ ├── NotFound.tsx │ │ │ │ │ ├── SidebarNav.tsx │ │ │ │ │ ├── WithOnboardingLayout.tsx │ │ │ │ │ ├── WithSidebarLayout.tsx │ │ │ │ │ └── index.ts │ │ │ │ ├── loan-details/ │ │ │ │ │ ├── LoanCard.tsx │ │ │ │ │ ├── LoanDetail.tsx │ │ │ │ │ └── index.ts │ │ │ │ ├── net-worth-insights/ │ │ │ │ │ ├── NetWorthInsightBadge.tsx │ │ │ │ │ ├── NetWorthInsightCard.tsx │ │ │ │ │ ├── NetWorthInsightDetail.tsx │ │ │ │ │ ├── NetWorthInsightStateAxis.tsx │ │ │ │ │ ├── NetWorthPrimaryCardGroup.tsx │ │ │ │ │ ├── breakdown-slider/ │ │ │ │ │ │ ├── NetWorthBreakdownSlider.tsx │ │ │ │ │ │ └── index.ts │ │ │ │ │ ├── breakdown-table/ │ │ │ │ │ │ ├── BreakdownTableIcon.tsx │ │ │ │ │ │ ├── NetWorthBreakdownTable.tsx │ │ │ │ │ │ └── index.ts │ │ │ │ │ ├── income-debt/ │ │ │ │ │ │ ├── IncomeDebtBlock.tsx │ │ │ │ │ │ ├── IncomeDebtDialog.tsx │ │ │ │ │ │ └── index.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ └── safety-net/ │ │ │ │ │ ├── SafetyNetDialog.tsx │ │ │ │ │ ├── SafetyNetOpportunityCost.tsx │ │ │ │ │ ├── SliderBlock.tsx │ │ │ │ │ └── index.ts │ │ │ │ ├── onboarding/ │ │ │ │ │ ├── ExampleApp.tsx │ │ │ │ │ ├── OnboardingBackground.tsx │ │ │ │ │ ├── OnboardingGuard.tsx │ │ │ │ │ ├── OnboardingNavbar.tsx │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── sidebar/ │ │ │ │ │ │ ├── SidebarOnboarding.tsx │ │ │ │ │ │ └── index.ts │ │ │ │ │ └── steps/ │ │ │ │ │ ├── Intro.tsx │ │ │ │ │ ├── Profile.tsx │ │ │ │ │ ├── StepProps.ts │ │ │ │ │ ├── Welcome.tsx │ │ │ │ │ ├── YourMaybe.tsx │ │ │ │ │ ├── index.ts │ │ │ │ │ └── setup/ │ │ │ │ │ ├── AddFirstAccount.tsx │ │ │ │ │ ├── EmailVerification.tsx │ │ │ │ │ ├── OtherAccounts.tsx │ │ │ │ │ └── index.ts │ │ │ │ ├── plans/ │ │ │ │ │ ├── AddPlanScenario.tsx │ │ │ │ │ ├── NewPlanForm.tsx │ │ │ │ │ ├── PlanContext.ts │ │ │ │ │ ├── PlanEventCard.tsx │ │ │ │ │ ├── PlanEventForm.tsx │ │ │ │ │ ├── PlanEventList.tsx │ │ │ │ │ ├── PlanEventPopout.tsx │ │ │ │ │ ├── PlanExplainer.tsx │ │ │ │ │ ├── PlanMenu.tsx │ │ │ │ │ ├── PlanMilestones.tsx │ │ │ │ │ ├── PlanParameterCard.tsx │ │ │ │ │ ├── PlanRangeInput.tsx │ │ │ │ │ ├── PlanRangeSelector.tsx │ │ │ │ │ ├── RetirementMilestoneForm.tsx │ │ │ │ │ ├── RetirementPlanChart.tsx │ │ │ │ │ ├── icon-utils.ts │ │ │ │ │ └── index.ts │ │ │ │ ├── transactions-list/ │ │ │ │ │ ├── ExcludeTransactionDialog.tsx │ │ │ │ │ ├── TransactionList.tsx │ │ │ │ │ ├── TransactionListItem.tsx │ │ │ │ │ └── index.ts │ │ │ │ ├── user-billing/ │ │ │ │ │ ├── BillingPreferences.tsx │ │ │ │ │ ├── PlanSelector.tsx │ │ │ │ │ ├── PremiumIcon.tsx │ │ │ │ │ ├── SubscriberGuard.tsx │ │ │ │ │ ├── UpgradePrompt.tsx │ │ │ │ │ ├── UpgradeTakeover.tsx │ │ │ │ │ ├── graphics/ │ │ │ │ │ │ ├── FeaturesGlow.tsx │ │ │ │ │ │ ├── SideGrid.tsx │ │ │ │ │ │ └── index.ts │ │ │ │ │ └── index.ts │ │ │ │ ├── user-details/ │ │ │ │ │ ├── DeleteUserButton.tsx │ │ │ │ │ ├── DeleteUserModal.tsx │ │ │ │ │ ├── UserDetails.tsx │ │ │ │ │ ├── UserDevTools.tsx │ │ │ │ │ └── index.ts │ │ │ │ ├── user-security/ │ │ │ │ │ ├── PasswordReset.tsx │ │ │ │ │ ├── SecurityPreferences.tsx │ │ │ │ │ └── index.ts │ │ │ │ └── valuations-list/ │ │ │ │ ├── PerformanceMetric.tsx │ │ │ │ ├── ValuationList.tsx │ │ │ │ ├── ValuationsDateCell.tsx │ │ │ │ ├── ValuationsTable.tsx │ │ │ │ ├── ValuationsTableForm.tsx │ │ │ │ ├── index.ts │ │ │ │ └── types.ts │ │ │ ├── tsconfig.json │ │ │ ├── tsconfig.lib.json │ │ │ └── tsconfig.spec.json │ │ └── shared/ │ │ ├── .babelrc │ │ ├── .eslintrc.json │ │ ├── README.md │ │ ├── jest.config.ts │ │ ├── src/ │ │ │ ├── api/ │ │ │ │ ├── index.ts │ │ │ │ ├── useAccountApi.ts │ │ │ │ ├── useAccountConnectionApi.ts │ │ │ │ ├── useAuthUserApi.ts │ │ │ │ ├── useHoldingApi.ts │ │ │ │ ├── useInstitutionApi.ts │ │ │ │ ├── usePlanApi.ts │ │ │ │ ├── useSecurityApi.ts │ │ │ │ ├── useTellerApi.ts │ │ │ │ ├── useTransactionApi.ts │ │ │ │ ├── useUserApi.ts │ │ │ │ └── useValuationApi.ts │ │ │ ├── components/ │ │ │ │ ├── cards/ │ │ │ │ │ ├── MaybeCard.tsx │ │ │ │ │ ├── MaybeCardShareModal.tsx │ │ │ │ │ └── index.ts │ │ │ │ ├── charts/ │ │ │ │ │ ├── index.ts │ │ │ │ │ └── time-series/ │ │ │ │ │ ├── AxisBottom.tsx │ │ │ │ │ ├── AxisLeft.tsx │ │ │ │ │ ├── BaseChart.tsx │ │ │ │ │ ├── Chart.tsx │ │ │ │ │ ├── DefaultTooltip.tsx │ │ │ │ │ ├── FloatingIcon.tsx │ │ │ │ │ ├── Line.tsx │ │ │ │ │ ├── LineRange.tsx │ │ │ │ │ ├── LoadingChart.tsx │ │ │ │ │ ├── MultiColorGradient.tsx │ │ │ │ │ ├── PlusCircleGlyph.tsx │ │ │ │ │ ├── ZeroPointGradient.tsx │ │ │ │ │ ├── colorScales.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── types.ts │ │ │ │ │ ├── useSeries.ts │ │ │ │ │ └── useTooltip.ts │ │ │ │ ├── dialogs/ │ │ │ │ │ ├── NonUSDDialog.tsx │ │ │ │ │ └── index.ts │ │ │ │ ├── explainers/ │ │ │ │ │ ├── ExplainerExternalLink.tsx │ │ │ │ │ ├── ExplainerInfoBlock.tsx │ │ │ │ │ ├── ExplainerPerformanceBlock.tsx │ │ │ │ │ ├── ExplainerSection.tsx │ │ │ │ │ └── index.ts │ │ │ │ ├── generic/ │ │ │ │ │ ├── BoxIcon.tsx │ │ │ │ │ ├── Confetti.tsx │ │ │ │ │ ├── InfiniteScroll.tsx │ │ │ │ │ ├── InsightGroup.tsx │ │ │ │ │ ├── InsightPopout.tsx │ │ │ │ │ ├── ProfileCircle.tsx │ │ │ │ │ ├── RelativeTime.tsx │ │ │ │ │ ├── TakeoverBackground.tsx │ │ │ │ │ ├── Toaster.tsx │ │ │ │ │ ├── TrendBadge.tsx │ │ │ │ │ ├── index.ts │ │ │ │ │ └── small-decimals/ │ │ │ │ │ ├── SmallDecimals.test.tsx │ │ │ │ │ ├── SmallDecimals.tsx │ │ │ │ │ └── index.ts │ │ │ │ ├── index.ts │ │ │ │ ├── loaders/ │ │ │ │ │ ├── MainContentLoader.tsx │ │ │ │ │ └── index.ts │ │ │ │ ├── overlays/ │ │ │ │ │ ├── BlurredContentOverlay.tsx │ │ │ │ │ ├── ErrorFallbackOverlay.tsx │ │ │ │ │ ├── MainContentOverlay.tsx │ │ │ │ │ ├── Overlay.tsx │ │ │ │ │ └── index.ts │ │ │ │ └── tables/ │ │ │ │ ├── data-table/ │ │ │ │ │ ├── DataTable.tsx │ │ │ │ │ ├── DefaultCell.tsx │ │ │ │ │ ├── EditableBooleanCell.tsx │ │ │ │ │ ├── EditableCell.tsx │ │ │ │ │ ├── EditableDateCell.tsx │ │ │ │ │ ├── EditableDropdownCell.tsx │ │ │ │ │ ├── EditableStringCell.tsx │ │ │ │ │ ├── index.ts │ │ │ │ │ └── types.ts │ │ │ │ └── index.ts │ │ │ ├── hooks/ │ │ │ │ ├── index.ts │ │ │ │ ├── useAccountNotifications.ts │ │ │ │ ├── useAxiosWithAuth.ts │ │ │ │ ├── useDebounce.ts │ │ │ │ ├── useFrame.ts │ │ │ │ ├── useInterval.ts │ │ │ │ ├── useLastUpdated.ts │ │ │ │ ├── useLocalStorage.ts │ │ │ │ ├── useLogger.ts │ │ │ │ ├── useModalManager.ts │ │ │ │ ├── useProviderStatus.ts │ │ │ │ ├── useQueryParam.ts │ │ │ │ ├── useScreenSize.ts │ │ │ │ └── useTeller.ts │ │ │ ├── index.ts │ │ │ ├── providers/ │ │ │ │ ├── AccountContextProvider.tsx │ │ │ │ ├── AxiosProvider.tsx │ │ │ │ ├── LayoutContextProvider.tsx │ │ │ │ ├── LogProvider.tsx │ │ │ │ ├── PopoutProvider.tsx │ │ │ │ ├── QueryProvider.tsx │ │ │ │ ├── UserAccountContextProvider.tsx │ │ │ │ └── index.ts │ │ │ ├── types/ │ │ │ │ ├── client-side-feature-flags.ts │ │ │ │ ├── index.ts │ │ │ │ └── react-types.ts │ │ │ └── utils/ │ │ │ ├── account-utils.ts │ │ │ ├── browser-utils.ts │ │ │ ├── form-utils.ts │ │ │ ├── image-loaders.ts │ │ │ └── index.ts │ │ ├── tsconfig.json │ │ ├── tsconfig.lib.json │ │ └── tsconfig.spec.json │ ├── design-system/ │ │ ├── .babelrc │ │ ├── .eslintrc.json │ │ ├── .storybook/ │ │ │ ├── main.js │ │ │ ├── manager.js │ │ │ ├── preview.js │ │ │ ├── theme.js │ │ │ └── tsconfig.json │ │ ├── README.md │ │ ├── assets/ │ │ │ └── styles.css │ │ ├── docs/ │ │ │ ├── Getting Started/ │ │ │ │ ├── About.stories.mdx │ │ │ │ ├── Colors.stories.mdx │ │ │ │ └── Typography.stories.mdx │ │ │ └── util/ │ │ │ ├── Swatch.tsx │ │ │ └── SwatchGroup.tsx │ │ ├── jest.config.ts │ │ ├── jest.setup.js │ │ ├── package.json │ │ ├── postcss.config.js │ │ ├── src/ │ │ │ ├── index.ts │ │ │ └── lib/ │ │ │ ├── AccordionRow/ │ │ │ │ ├── AccordionRow.spec.tsx │ │ │ │ ├── AccordionRow.stories.tsx │ │ │ │ ├── AccordionRow.tsx │ │ │ │ ├── __snapshots__/ │ │ │ │ │ └── AccordionRow.spec.tsx.snap │ │ │ │ └── index.ts │ │ │ ├── Alert/ │ │ │ │ ├── Alert.stories.tsx │ │ │ │ ├── Alert.tsx │ │ │ │ └── index.ts │ │ │ ├── Badge/ │ │ │ │ ├── Badge.spec.tsx │ │ │ │ ├── Badge.stories.tsx │ │ │ │ ├── Badge.tsx │ │ │ │ ├── __snapshots__/ │ │ │ │ │ └── Badge.spec.tsx.snap │ │ │ │ └── index.ts │ │ │ ├── Breadcrumb/ │ │ │ │ ├── Breadcrumb.spec.tsx │ │ │ │ ├── Breadcrumb.stories.tsx │ │ │ │ ├── Breadcrumb.tsx │ │ │ │ ├── __snapshots__/ │ │ │ │ │ └── Breadcrumb.spec.tsx.snap │ │ │ │ └── index.ts │ │ │ ├── Button/ │ │ │ │ ├── Button.spec.tsx │ │ │ │ ├── Button.stories.tsx │ │ │ │ ├── Button.tsx │ │ │ │ ├── __snapshots__/ │ │ │ │ │ └── Button.spec.tsx.snap │ │ │ │ └── index.ts │ │ │ ├── Checkbox/ │ │ │ │ ├── Checkbox.spec.tsx │ │ │ │ ├── Checkbox.stories.tsx │ │ │ │ ├── Checkbox.tsx │ │ │ │ ├── __snapshots__/ │ │ │ │ │ └── Checkbox.spec.tsx.snap │ │ │ │ └── index.ts │ │ │ ├── DatePicker/ │ │ │ │ ├── DatePicker.spec.tsx │ │ │ │ ├── DatePicker.stories.tsx │ │ │ │ ├── DatePicker.tsx │ │ │ │ ├── DatePickerCalendar.tsx │ │ │ │ ├── DatePickerInput.tsx │ │ │ │ ├── DatePickerMonth.tsx │ │ │ │ ├── DatePickerQuickSelect.tsx │ │ │ │ ├── DatePickerRange/ │ │ │ │ │ ├── DatePickerRange.spec.tsx │ │ │ │ │ ├── DatePickerRange.stories.tsx │ │ │ │ │ ├── DatePickerRange.tsx │ │ │ │ │ ├── DatePickerRangeButton.tsx │ │ │ │ │ ├── DatePickerRangeCalendar.tsx │ │ │ │ │ ├── DatePickerRangeTabs.tsx │ │ │ │ │ ├── __snapshots__/ │ │ │ │ │ │ └── DatePickerRange.spec.tsx.snap │ │ │ │ │ └── index.ts │ │ │ │ ├── DatePickerYear.tsx │ │ │ │ ├── __snapshots__/ │ │ │ │ │ └── DatePicker.spec.tsx.snap │ │ │ │ ├── index.ts │ │ │ │ ├── selectableRanges.ts │ │ │ │ ├── utils.spec.tsx │ │ │ │ └── utils.tsx │ │ │ ├── Dialog/ │ │ │ │ ├── Dialog.spec.tsx │ │ │ │ ├── Dialog.stories.tsx │ │ │ │ ├── Dialog.tsx │ │ │ │ ├── DialogV2.tsx │ │ │ │ ├── __snapshots__/ │ │ │ │ │ └── Dialog.spec.tsx.snap │ │ │ │ └── index.ts │ │ │ ├── FormGroup/ │ │ │ │ ├── FormGroup.spec.tsx │ │ │ │ ├── FormGroup.tsx │ │ │ │ ├── __snapshots__/ │ │ │ │ │ └── FormGroup.spec.tsx.snap │ │ │ │ └── index.ts │ │ │ ├── FractionalCircle/ │ │ │ │ ├── FractionalCircle.stories.tsx │ │ │ │ ├── FractionalCircle.tsx │ │ │ │ └── index.ts │ │ │ ├── IndexTabs/ │ │ │ │ ├── IndexTabs.spec.tsx │ │ │ │ ├── IndexTabs.stories.tsx │ │ │ │ ├── IndexTabs.tsx │ │ │ │ ├── __snapshots__/ │ │ │ │ │ └── IndexTabs.spec.tsx.snap │ │ │ │ └── index.ts │ │ │ ├── Listbox/ │ │ │ │ ├── Listbox.spec.tsx │ │ │ │ ├── Listbox.stories.tsx │ │ │ │ ├── Listbox.tsx │ │ │ │ ├── __snapshots__/ │ │ │ │ │ └── Listbox.spec.tsx.snap │ │ │ │ └── index.ts │ │ │ ├── LoadingPlaceholder/ │ │ │ │ ├── LoadingPlaceholder.spec.tsx │ │ │ │ ├── LoadingPlaceholder.stories.tsx │ │ │ │ ├── LoadingPlaceholder.tsx │ │ │ │ ├── __snapshots__/ │ │ │ │ │ └── LoadingPlaceholder.spec.tsx.snap │ │ │ │ └── index.ts │ │ │ ├── LoadingSpinner/ │ │ │ │ ├── LoadingSpinner.spec.tsx │ │ │ │ ├── LoadingSpinner.stories.tsx │ │ │ │ ├── LoadingSpinner.tsx │ │ │ │ ├── __snapshots__/ │ │ │ │ │ └── LoadingSpinner.spec.tsx.snap │ │ │ │ └── index.ts │ │ │ ├── Menu/ │ │ │ │ ├── Menu.spec.tsx │ │ │ │ ├── Menu.stories.tsx │ │ │ │ ├── Menu.tsx │ │ │ │ ├── __snapshots__/ │ │ │ │ │ └── Menu.spec.tsx.snap │ │ │ │ └── index.ts │ │ │ ├── Popover/ │ │ │ │ ├── Popover.spec.tsx │ │ │ │ ├── Popover.stories.tsx │ │ │ │ ├── Popover.tsx │ │ │ │ ├── __snapshots__/ │ │ │ │ │ └── Popover.spec.tsx.snap │ │ │ │ └── index.ts │ │ │ ├── RTEditor/ │ │ │ │ ├── RTEditor.tsx │ │ │ │ └── index.ts │ │ │ ├── RadioGroup/ │ │ │ │ ├── RadioGroup.stories.tsx │ │ │ │ ├── RadioGroup.tsx │ │ │ │ └── index.ts │ │ │ ├── Slider/ │ │ │ │ ├── Slider.spec.tsx │ │ │ │ ├── Slider.stories.tsx │ │ │ │ ├── Slider.tsx │ │ │ │ ├── __snapshots__/ │ │ │ │ │ └── Slider.spec.tsx.snap │ │ │ │ └── index.ts │ │ │ ├── Step/ │ │ │ │ ├── Step.spec.tsx │ │ │ │ ├── Step.stories.tsx │ │ │ │ ├── Step.tsx │ │ │ │ ├── __snapshots__/ │ │ │ │ │ └── Step.spec.tsx.snap │ │ │ │ └── index.ts │ │ │ ├── Tab/ │ │ │ │ ├── Tab.spec.tsx │ │ │ │ ├── Tab.stories.tsx │ │ │ │ ├── Tab.tsx │ │ │ │ ├── __snapshots__/ │ │ │ │ │ └── Tab.spec.tsx.snap │ │ │ │ └── index.ts │ │ │ ├── Takeover/ │ │ │ │ ├── Takeover.spec.tsx │ │ │ │ ├── Takeover.stories.tsx │ │ │ │ ├── Takeover.tsx │ │ │ │ ├── __snapshots__/ │ │ │ │ │ └── Takeover.spec.tsx.snap │ │ │ │ └── index.ts │ │ │ ├── Toast/ │ │ │ │ ├── Toast.spec.tsx │ │ │ │ ├── Toast.stories.tsx │ │ │ │ ├── Toast.tsx │ │ │ │ ├── __snapshots__/ │ │ │ │ │ └── Toast.spec.tsx.snap │ │ │ │ └── index.ts │ │ │ ├── Toggle/ │ │ │ │ ├── Toggle.spec.tsx │ │ │ │ ├── Toggle.stories.tsx │ │ │ │ ├── Toggle.tsx │ │ │ │ ├── __snapshots__/ │ │ │ │ │ └── Toggle.spec.tsx.snap │ │ │ │ └── index.ts │ │ │ ├── Tooltip/ │ │ │ │ ├── Tooltip.spec.tsx │ │ │ │ ├── Tooltip.stories.tsx │ │ │ │ ├── Tooltip.tsx │ │ │ │ ├── __snapshots__/ │ │ │ │ │ └── Tooltip.spec.tsx.snap │ │ │ │ └── index.ts │ │ │ ├── TrendLine/ │ │ │ │ ├── TrendLine.stories.tsx │ │ │ │ ├── TrendLine.tsx │ │ │ │ ├── Trendline.spec.tsx │ │ │ │ ├── __snapshots__/ │ │ │ │ │ └── Trendline.spec.tsx.snap │ │ │ │ └── index.ts │ │ │ └── inputs/ │ │ │ ├── Input/ │ │ │ │ ├── Input.spec.tsx │ │ │ │ ├── Input.stories.tsx │ │ │ │ ├── Input.tsx │ │ │ │ ├── __snapshots__/ │ │ │ │ │ └── Input.spec.tsx.snap │ │ │ │ └── index.ts │ │ │ ├── InputColorHint/ │ │ │ │ ├── InputColorHint.tsx │ │ │ │ └── index.ts │ │ │ ├── InputCurrency/ │ │ │ │ ├── InputCurrency.spec.tsx │ │ │ │ ├── InputCurrency.stories.tsx │ │ │ │ ├── InputCurrency.tsx │ │ │ │ ├── __snapshots__/ │ │ │ │ │ └── InputCurrency.spec.tsx.snap │ │ │ │ └── index.ts │ │ │ ├── InputHint/ │ │ │ │ ├── InputHint.tsx │ │ │ │ └── index.ts │ │ │ ├── InputPassword/ │ │ │ │ ├── InputPassword.spec.tsx │ │ │ │ ├── InputPassword.stories.tsx │ │ │ │ ├── InputPassword.tsx │ │ │ │ ├── __snapshots__/ │ │ │ │ │ └── InputPassword.spec.tsx.snap │ │ │ │ └── index.ts │ │ │ └── index.ts │ │ ├── tailwind.config.js │ │ ├── tsconfig.json │ │ ├── tsconfig.lib.json │ │ └── tsconfig.spec.json │ ├── server/ │ │ ├── features/ │ │ │ ├── .babelrc │ │ │ ├── .eslintrc.json │ │ │ ├── README.md │ │ │ ├── jest.config.ts │ │ │ ├── src/ │ │ │ │ ├── account/ │ │ │ │ │ ├── account-query.service.ts │ │ │ │ │ ├── account.processor.ts │ │ │ │ │ ├── account.provider.ts │ │ │ │ │ ├── account.schema.ts │ │ │ │ │ ├── account.service.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ └── insight.service.ts │ │ │ │ ├── account-balance/ │ │ │ │ │ ├── balance-sync.strategy.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── investment-transaction-balance-sync.strategy.ts │ │ │ │ │ ├── loan-balance-sync.strategy.ts │ │ │ │ │ ├── transaction-balance-sync.strategy.ts │ │ │ │ │ └── valuation-balance-sync.strategy.ts │ │ │ │ ├── account-connection/ │ │ │ │ │ ├── account-connection.processor.ts │ │ │ │ │ ├── account-connection.provider.ts │ │ │ │ │ ├── account-connection.service.ts │ │ │ │ │ └── index.ts │ │ │ │ ├── auth-user/ │ │ │ │ │ ├── auth-user.service.ts │ │ │ │ │ └── index.ts │ │ │ │ ├── email/ │ │ │ │ │ ├── email.processor.ts │ │ │ │ │ ├── email.schema.ts │ │ │ │ │ ├── email.service.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ └── providers/ │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── postmark.provider.ts │ │ │ │ │ └── smtp.provider.ts │ │ │ │ ├── holding/ │ │ │ │ │ ├── holding.schema.ts │ │ │ │ │ ├── holding.service.ts │ │ │ │ │ └── index.ts │ │ │ │ ├── index.ts │ │ │ │ ├── institution/ │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── institution.provider.ts │ │ │ │ │ └── institution.service.ts │ │ │ │ ├── investment-transaction/ │ │ │ │ │ ├── index.ts │ │ │ │ │ └── investment-transaction.schema.ts │ │ │ │ ├── plan/ │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── plan.schema.ts │ │ │ │ │ ├── plan.service.ts │ │ │ │ │ └── projection/ │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── monte-carlo.spec.ts │ │ │ │ │ ├── monte-carlo.ts │ │ │ │ │ ├── projection-calculator.spec.ts │ │ │ │ │ ├── projection-calculator.ts │ │ │ │ │ ├── projection-value.spec.ts │ │ │ │ │ └── projection-value.ts │ │ │ │ ├── providers/ │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── property/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── property.service.ts │ │ │ │ │ ├── teller/ │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── teller.etl.ts │ │ │ │ │ │ ├── teller.service.ts │ │ │ │ │ │ └── teller.webhook.ts │ │ │ │ │ └── vehicle/ │ │ │ │ │ ├── index.ts │ │ │ │ │ └── vehicle.service.ts │ │ │ │ ├── security-pricing/ │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── security-pricing.processor.ts │ │ │ │ │ └── security-pricing.service.ts │ │ │ │ ├── stripe/ │ │ │ │ │ ├── index.ts │ │ │ │ │ └── stripe.webhook.ts │ │ │ │ ├── transaction/ │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── transaction.schema.ts │ │ │ │ │ └── transaction.service.ts │ │ │ │ ├── user/ │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── onboarding.schema.ts │ │ │ │ │ ├── onboarding.service.ts │ │ │ │ │ ├── user.processor.ts │ │ │ │ │ └── user.service.ts │ │ │ │ └── valuation/ │ │ │ │ ├── index.ts │ │ │ │ └── valuation.service.ts │ │ │ ├── tsconfig.json │ │ │ ├── tsconfig.lib.json │ │ │ └── tsconfig.spec.json │ │ └── shared/ │ │ ├── .babelrc │ │ ├── .eslintrc.json │ │ ├── README.md │ │ ├── jest.config.ts │ │ ├── src/ │ │ │ ├── endpoint.ts │ │ │ ├── etl.ts │ │ │ ├── index.ts │ │ │ ├── logger.ts │ │ │ ├── services/ │ │ │ │ ├── cache.service.ts │ │ │ │ ├── crypto.service.ts │ │ │ │ ├── index.ts │ │ │ │ ├── market-data.service.spec.ts │ │ │ │ ├── market-data.service.ts │ │ │ │ ├── pg.service.ts │ │ │ │ ├── queue/ │ │ │ │ │ ├── bull-queue.ts │ │ │ │ │ ├── in-memory-queue.ts │ │ │ │ │ └── index.ts │ │ │ │ └── queue.service.ts │ │ │ ├── sql-template-tag.ts │ │ │ └── utils/ │ │ │ ├── db-utils.ts │ │ │ ├── error-utils.ts │ │ │ ├── index.ts │ │ │ ├── server-utils.ts │ │ │ └── teller-utils.ts │ │ ├── tsconfig.json │ │ ├── tsconfig.lib.json │ │ └── tsconfig.spec.json │ ├── shared/ │ │ ├── .babelrc │ │ ├── .eslintrc.json │ │ ├── README.md │ │ ├── jest.config.ts │ │ ├── src/ │ │ │ ├── index.ts │ │ │ ├── superjson.spec.ts │ │ │ ├── superjson.ts │ │ │ ├── types/ │ │ │ │ ├── account-types.ts │ │ │ │ ├── api-types.ts │ │ │ │ ├── email-types.ts │ │ │ │ ├── general-types.ts │ │ │ │ ├── holding-types.ts │ │ │ │ ├── index.ts │ │ │ │ ├── institution-types.ts │ │ │ │ ├── investment-transaction-types.ts │ │ │ │ ├── plan-types.ts │ │ │ │ ├── security-types.ts │ │ │ │ ├── transaction-types.ts │ │ │ │ └── user-types.ts │ │ │ └── utils/ │ │ │ ├── account-utils.ts │ │ │ ├── date-utils.spec.ts │ │ │ ├── date-utils.ts │ │ │ ├── geo-utils.ts │ │ │ ├── index.ts │ │ │ ├── market-utils.ts │ │ │ ├── number-utils.spec.ts │ │ │ ├── number-utils.ts │ │ │ ├── plan-utils.ts │ │ │ ├── shared-utils.spec.ts │ │ │ ├── shared-utils.ts │ │ │ ├── stats-utils.spec.ts │ │ │ ├── stats-utils.ts │ │ │ ├── test-utils.ts │ │ │ ├── transaction-utils.ts │ │ │ └── user-utils.ts │ │ ├── tsconfig.json │ │ ├── tsconfig.lib.json │ │ └── tsconfig.spec.json │ └── teller-api/ │ ├── .eslintrc.json │ ├── jest.config.ts │ ├── src/ │ │ ├── index.ts │ │ ├── teller-api.ts │ │ └── types/ │ │ ├── account-balance.ts │ │ ├── account-details.ts │ │ ├── accounts.ts │ │ ├── authentication.ts │ │ ├── enrollment.ts │ │ ├── error.ts │ │ ├── identity.ts │ │ ├── index.ts │ │ ├── institutions.ts │ │ ├── transactions.ts │ │ └── webhooks.ts │ ├── tsconfig.json │ ├── tsconfig.lib.json │ └── tsconfig.spec.json ├── nx.json ├── package.json ├── prisma/ │ ├── migrations/ │ │ ├── 20211005200319_init/ │ │ │ └── migration.sql │ │ ├── 20211019194924_unique_constraint_on_account_balances/ │ │ │ └── migration.sql │ │ ├── 20211019214200_default_values/ │ │ │ └── migration.sql │ │ ├── 20211025200206_account_balance_schema_update/ │ │ │ └── migration.sql │ │ ├── 20211026174357_default_text_type/ │ │ │ └── migration.sql │ │ ├── 20211026175641_default_values/ │ │ │ └── migration.sql │ │ ├── 20211102165759_account_status/ │ │ │ └── migration.sql │ │ ├── 20211102183151_add_account_types_and_subtypes/ │ │ │ └── migration.sql │ │ ├── 20211104155259_account_uniqueness/ │ │ │ └── migration.sql │ │ ├── 20211105234550_posted_date_type/ │ │ │ └── migration.sql │ │ ├── 20211109151750_account_type_seed/ │ │ │ └── migration.sql │ │ ├── 20211110044559_manual_accounts_rename_fk/ │ │ │ └── migration.sql │ │ ├── 20211116235652_investment_data/ │ │ │ └── migration.sql │ │ ├── 20211117190140_add_manual_account_types/ │ │ │ └── migration.sql │ │ ├── 20211117190719_updated_at_default/ │ │ │ └── migration.sql │ │ ├── 20211117210112_valuation_date/ │ │ │ └── migration.sql │ │ ├── 20211117233026_add_date_indices/ │ │ │ └── migration.sql │ │ ├── 20211118160716_account_balance_update/ │ │ │ └── migration.sql │ │ ├── 20211118191000_account_balance_timestamps/ │ │ │ └── migration.sql │ │ ├── 20211118194940_account_functions/ │ │ │ └── migration.sql │ │ ├── 20211118214727_txn_date_naming/ │ │ │ └── migration.sql │ │ ├── 20211129155121_connection_status_codes/ │ │ │ └── migration.sql │ │ ├── 20211130184227_new_accounts_available_flag/ │ │ │ └── migration.sql │ │ ├── 20211201023540_account_single_table_inheritance/ │ │ │ └── migration.sql │ │ ├── 20211203180216_security_pricing/ │ │ │ └── migration.sql │ │ ├── 20211204053810_account_balance_hypertable/ │ │ │ └── migration.sql │ │ ├── 20211207192726_add_valuation_generated_cols/ │ │ │ └── migration.sql │ │ ├── 20211208162929_transaction_date/ │ │ │ └── migration.sql │ │ ├── 20211209041710_remove_initial_txn/ │ │ │ └── migration.sql │ │ ├── 20211209050532_update_fns/ │ │ │ └── migration.sql │ │ ├── 20211211140103_add_institution_id_to_connection/ │ │ │ └── migration.sql │ │ ├── 20211213211517_account_user_index/ │ │ │ └── migration.sql │ │ ├── 20211214162659_security_pricing_source/ │ │ │ └── migration.sql │ │ ├── 20211215195518_add_account_start_date/ │ │ │ └── migration.sql │ │ ├── 20211230035441_account_sync_status/ │ │ │ └── migration.sql │ │ ├── 20220106215040_add_mask_to_account/ │ │ │ └── migration.sql │ │ ├── 20220107170334_hypertable_chunk_size_tuning/ │ │ │ └── migration.sql │ │ ├── 20220112171128_update_fn/ │ │ │ └── migration.sql │ │ ├── 20220121175453_account_liability_json/ │ │ │ └── migration.sql │ │ ├── 20220124193549_add_plaid_valuation_valuation_type/ │ │ │ └── migration.sql │ │ ├── 20220124211317_update_valuation_types_and_sources/ │ │ │ └── migration.sql │ │ ├── 20220125211038_add_unique_constraint_to_valuations/ │ │ │ └── migration.sql │ │ ├── 20220202184342_account_balances_gapfilled_fn/ │ │ │ └── migration.sql │ │ ├── 20220203234737_update_fn/ │ │ │ └── migration.sql │ │ ├── 20220214175713_narrow_transaction_category/ │ │ │ └── migration.sql │ │ ├── 20220215201534_transaction_remove_subcategory_add_plaid_category/ │ │ │ └── migration.sql │ │ ├── 20220215212216_add_transaction_indexes/ │ │ │ └── migration.sql │ │ ├── 20220217040807_add_merchant_name_to_transactions/ │ │ │ └── migration.sql │ │ ├── 20220228233043_change_money_type/ │ │ │ └── migration.sql │ │ ├── 20220302181536_add_price_as_of_to_security_pricing/ │ │ │ └── migration.sql │ │ ├── 20220307200633_remove_price_from_holding/ │ │ │ └── migration.sql │ │ ├── 20220307211701_valuation_trigger/ │ │ │ └── migration.sql │ │ ├── 20220311165323_add_shares_per_contract_to_security/ │ │ │ └── migration.sql │ │ ├── 20220315172110_institution/ │ │ │ └── migration.sql │ │ ├── 20220316200652_reset_plaid_derivative_prices/ │ │ │ └── migration.sql │ │ ├── 20220317191949_reset_plaid_derivative_prices_again/ │ │ │ └── migration.sql │ │ ├── 20220323203441_multi_provider_updates/ │ │ │ └── migration.sql │ │ ├── 20220323212807_fix_function/ │ │ │ └── migration.sql │ │ ├── 20220411193518_stop_generating_and_enumize_account_category/ │ │ │ └── migration.sql │ │ ├── 20220426190758_add_url_and_logo_url_to_institution/ │ │ │ └── migration.sql │ │ ├── 20220504231954_finicity_updates/ │ │ │ └── migration.sql │ │ ├── 20220518005502_finicity_customer_id_uniqueness/ │ │ │ └── migration.sql │ │ ├── 20220519192445_institution_refactor/ │ │ │ └── migration.sql │ │ ├── 20220520161223_institution_search_algo/ │ │ │ └── migration.sql │ │ ├── 20220606160203_add_finicity_username_to_user/ │ │ │ └── migration.sql │ │ ├── 20220607162542_add_crisp_session_token_to_user/ │ │ │ └── migration.sql │ │ ├── 20220608171009_add_success_rate_and_oauth_to_provider_institutions/ │ │ │ └── migration.sql │ │ ├── 20220608190342_add_unique_constraint_to_institution/ │ │ │ └── migration.sql │ │ ├── 20220608202739_add_success_rate_updated_to_provider_institution/ │ │ │ └── migration.sql │ │ ├── 20220609195136_remove_success_rate_from_provider_institution/ │ │ │ └── migration.sql │ │ ├── 20220622160129_add_finicity_error/ │ │ │ └── migration.sql │ │ ├── 20220623171212_remove_holding_unique_constraint/ │ │ │ └── migration.sql │ │ ├── 20220630005107_category_overrides/ │ │ │ └── migration.sql │ │ ├── 20220701013813_merge_updates/ │ │ │ └── migration.sql │ │ ├── 20220707195013_user_overrides/ │ │ │ └── migration.sql │ │ ├── 20220708191740_txn_excluded_flag/ │ │ │ └── migration.sql │ │ ├── 20220713134742_add_provider_field/ │ │ │ └── migration.sql │ │ ├── 20220714180514_update_account_start_date_fn/ │ │ │ └── migration.sql │ │ ├── 20220714180819_account_category_consolidation/ │ │ │ └── migration.sql │ │ ├── 20220714181018_update_account_type_model/ │ │ │ └── migration.sql │ │ ├── 20220715191415_add_liability_fields/ │ │ │ └── migration.sql │ │ ├── 20220719200317_plaid_txn_category/ │ │ │ └── migration.sql │ │ ├── 20220720191551_generated_loan_credit_fields/ │ │ │ └── migration.sql │ │ ├── 20220725143246_map_credit_loan_data/ │ │ │ └── migration.sql │ │ ├── 20220726003918_reset_loan_account_balances/ │ │ │ └── migration.sql │ │ ├── 20220727145316_loan_credit_json_nullable/ │ │ │ └── migration.sql │ │ ├── 20220727202956_loan_account_start_date/ │ │ │ └── migration.sql │ │ ├── 20220729012630_security_fields/ │ │ │ └── migration.sql │ │ ├── 20220729202323_txn_updates/ │ │ │ └── migration.sql │ │ ├── 20220804180126_holdings_view/ │ │ │ └── migration.sql │ │ ├── 20220804191558_add_excluded_to_holding/ │ │ │ └── migration.sql │ │ ├── 20220808171116_investment_txn_fees/ │ │ │ └── migration.sql │ │ ├── 20220808174032_update_holdings_view/ │ │ │ └── migration.sql │ │ ├── 20220810190306_transaction_category_update/ │ │ │ └── migration.sql │ │ ├── 20220817180833_dietz/ │ │ │ └── migration.sql │ │ ├── 20220819151658_add_investment_transaction_category/ │ │ │ └── migration.sql │ │ ├── 20220915200544_add_plans/ │ │ │ └── migration.sql │ │ ├── 20220919203059_make_dob_optional/ │ │ │ └── migration.sql │ │ ├── 20220929161359_remove_crisp_session_token/ │ │ │ └── migration.sql │ │ ├── 20221004193621_security_brokerage_cash_flag/ │ │ │ └── migration.sql │ │ ├── 20221007143103_dietz_div0_fix/ │ │ │ └── migration.sql │ │ ├── 20221017145454_plan_events_milestones/ │ │ │ └── migration.sql │ │ ├── 20221021162836_remove_dob_from_plan/ │ │ │ └── migration.sql │ │ ├── 20221024203133_plan_event_milestone_category/ │ │ │ └── migration.sql │ │ ├── 20221027180912_cascade_plan_milestone_deletion/ │ │ │ └── migration.sql │ │ ├── 20221109192536_add_stripe_fields/ │ │ │ └── migration.sql │ │ ├── 20221111192223_ata/ │ │ │ └── migration.sql │ │ ├── 20221115201138_advisor_approval_status/ │ │ │ └── migration.sql │ │ ├── 20221117150434_update_advisor_profile/ │ │ │ └── migration.sql │ │ ├── 20221117213140_add_stripe_trial_reminder_sent/ │ │ │ └── migration.sql │ │ ├── 20221121214349_add_user_goals/ │ │ │ └── migration.sql │ │ ├── 20221129201601_conversation_advisor_unique_key/ │ │ │ └── migration.sql │ │ ├── 20221202213727_notification_preferences/ │ │ │ └── migration.sql │ │ ├── 20221206153642_conversation_user_required/ │ │ │ └── migration.sql │ │ ├── 20221207235557_expiry_email_sent/ │ │ │ └── migration.sql │ │ ├── 20221209041210_user_advisor_notes/ │ │ │ └── migration.sql │ │ ├── 20221212164355_update_risk_data_type/ │ │ │ └── migration.sql │ │ ├── 20221214145140_add_audit_table_and_trigger/ │ │ │ └── migration.sql │ │ ├── 20221222200240_add_onboarding_profile_fields/ │ │ │ └── migration.sql │ │ ├── 20230105203751_add_maybe_and_title/ │ │ │ └── migration.sql │ │ ├── 20230105210810_add_member_number/ │ │ │ └── migration.sql │ │ ├── 20230105221446_user_audit/ │ │ │ └── migration.sql │ │ ├── 20230106172727_add_user_residence/ │ │ │ └── migration.sql │ │ ├── 20230106221847_user_profile/ │ │ │ └── migration.sql │ │ ├── 20230110173017_add_user_member_id/ │ │ │ └── migration.sql │ │ ├── 20230112163100_add_agreements_table/ │ │ │ └── migration.sql │ │ ├── 20230113230312_user_email_required/ │ │ │ └── migration.sql │ │ ├── 20230117131125_update_ama_onboarding/ │ │ │ └── migration.sql │ │ ├── 20230117150048_user_name/ │ │ │ └── migration.sql │ │ ├── 20230117192734_update_agreement_types/ │ │ │ └── migration.sql │ │ ├── 20230119114411_add_onboarding_steps/ │ │ │ └── migration.sql │ │ ├── 20230123121401_separate_onboarding_flows/ │ │ │ └── migration.sql │ │ ├── 20230123192138_user_country_state/ │ │ │ └── migration.sql │ │ ├── 20230126230520_user_deletion/ │ │ │ └── migration.sql │ │ ├── 20230127003359_store_link_tokens/ │ │ │ └── migration.sql │ │ ├── 20230130161915_account_value_start_date/ │ │ │ └── migration.sql │ │ ├── 20230207111117_user_account_linking/ │ │ │ └── migration.sql │ │ ├── 20230207181233_add_conversation_relations/ │ │ │ └── migration.sql │ │ ├── 20230207230108_account_balance_strategy/ │ │ │ └── migration.sql │ │ ├── 20230210163006_add_user_trial_end/ │ │ │ └── migration.sql │ │ ├── 20230211134603_advisor_crm/ │ │ │ └── migration.sql │ │ ├── 20230220194746_remove_stripe_trials/ │ │ │ └── migration.sql │ │ ├── 20230223020847_txn_view/ │ │ │ └── migration.sql │ │ ├── 20240111031553_remove_advisor_and_related_data/ │ │ │ └── migration.sql │ │ ├── 20240111213125_next_auth_models/ │ │ │ └── migration.sql │ │ ├── 20240111213725_add_password_to_auth_user/ │ │ │ └── migration.sql │ │ ├── 20240112000538_remove_agreement_code/ │ │ │ └── migration.sql │ │ ├── 20240112001215_remove_convert_kit_usage/ │ │ │ └── migration.sql │ │ ├── 20240112201750_remove_auth0id_from_user/ │ │ │ └── migration.sql │ │ ├── 20240112204004_add_first_last_to_authuser/ │ │ │ └── migration.sql │ │ ├── 20240115222631_add_fields_for_teller/ │ │ │ └── migration.sql │ │ ├── 20240116023100_add_additional_teller_fields/ │ │ │ └── migration.sql │ │ ├── 20240116185600_add_teller_provider/ │ │ │ └── migration.sql │ │ ├── 20240116224800_add_enrollment_id_for_teller/ │ │ │ └── migration.sql │ │ ├── 20240117191553_categories_for_teller/ │ │ │ └── migration.sql │ │ ├── 20240118234302_remove_finicity_investment_transaction_categories/ │ │ │ └── migration.sql │ │ ├── 20240118234302_remove_finicity_transaction_categories/ │ │ │ └── migration.sql │ │ ├── 20240118234303_remove_finicity_usage/ │ │ │ └── migration.sql │ │ ├── 20240120213022_remove_transaction_category_generation/ │ │ │ └── migration.sql │ │ ├── 20240120215821_remove_investment_transaction_category_generation/ │ │ │ └── migration.sql │ │ ├── 20240121003016_add_asset_class_to_security/ │ │ │ └── migration.sql │ │ ├── 20240121011219_add_provider_name_to_security/ │ │ │ └── migration.sql │ │ ├── 20240121013630_add_exchange_info_to_security/ │ │ │ └── migration.sql │ │ ├── 20240121084645_create_unique_fields_for_security/ │ │ │ └── migration.sql │ │ ├── 20240121204146_add_auth_user_role/ │ │ │ └── migration.sql │ │ ├── 20240124090855_add_options_asset_class/ │ │ │ └── migration.sql │ │ ├── 20240124102931_remove_plaid_usage/ │ │ │ └── migration.sql │ │ └── migration_lock.toml │ ├── schema.prisma │ └── seed.ts ├── redis.Dockerfile ├── redis.conf ├── render.yaml ├── tools/ │ ├── generators/ │ │ ├── .gitkeep │ │ ├── index.ts │ │ └── tellerGenerator.ts │ ├── pages/ │ │ └── projections.html │ ├── scripts/ │ │ ├── gen-cloudfront-signing-keys.sh │ │ ├── gen-secret.sh │ │ ├── getAffectedApps.sh │ │ ├── runStagingE2ETests.sh │ │ ├── vercelBuildIgnore.js │ │ └── wait-for-it.sh │ ├── test-data/ │ │ ├── index.ts │ │ └── polygon/ │ │ ├── exchanges.ts │ │ ├── index.ts │ │ ├── snapshots.ts │ │ └── tickers.ts │ └── tsconfig.tools.json ├── tsconfig.base.json ├── vercel.json └── workspace.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .dockerignore ================================================ # Ignores everything except dist/ prisma/ apps/ * !dist/ !prisma/ !package.json !apps/client/env.sh ================================================ FILE: .editorconfig ================================================ # Editor configuration, see http://editorconfig.org root = true [*] charset = utf-8 indent_style = space indent_size = 2 insert_final_newline = true trim_trailing_whitespace = true [*.md] max_line_length = off trim_trailing_whitespace = false ================================================ FILE: .eslintrc.json ================================================ { "root": true, "ignorePatterns": ["**/*", "**/*.png"], "plugins": ["@nrwl/nx", "eslint-plugin-json"], "overrides": [ { "files": ["*.ts", "*.tsx", "*.js", "*.jsx"], "rules": { "@nrwl/nx/enforce-module-boundaries": [ "error", { "enforceBuildableLibDependency": true, "allow": [], "depConstraints": [ { "sourceTag": "scope:shared", "onlyDependOnLibsWithTags": ["scope:shared"] }, { "sourceTag": "scope:app", "onlyDependOnLibsWithTags": ["*"] }, { "sourceTag": "scope:client-shared", "onlyDependOnLibsWithTags": ["scope:client-shared", "scope:shared"] }, { "sourceTag": "scope:server-shared", "onlyDependOnLibsWithTags": ["scope:server-shared", "scope:shared"] }, { "sourceTag": "scope:server", "onlyDependOnLibsWithTags": [ "scope:server", "scope:server-shared", "scope:shared" ] }, { "sourceTag": "scope:client", "onlyDependOnLibsWithTags": [ "scope:client", "scope:client-shared", "scope:shared" ] } ] } ] } }, { "files": ["*.ts", "*.tsx"], "extends": ["plugin:@nrwl/nx/typescript"], "rules": { "@typescript-eslint/no-unused-vars": ["warn", { "argsIgnorePattern": "^_" }], "@typescript-eslint/no-non-null-assertion": "off", "@typescript-eslint/no-explicit-any": "off", "@typescript-eslint/ban-types": "off", "@typescript-eslint/ban-ts-comment": "off", "@typescript-eslint/consistent-type-assertions": "error", "@typescript-eslint/consistent-type-imports": [ "error", { "fixStyle": "inline-type-imports" } ] } }, { "files": ["*.js", "*.jsx"], "extends": ["plugin:@nrwl/nx/javascript"], "rules": {} }, { "files": ["*.tsx", "*.jsx"], "rules": { "jsx-a11y/anchor-is-valid": [ "error", { "components": ["Link"], "specialLink": ["hrefLeft", "hrefRight"], "aspects": ["invalidHref", "preferButton"] } ] } } ] } ================================================ FILE: .github/ISSUE_TEMPLATE/bug_report.md ================================================ --- name: Bug report about: Create a report to help us improve title: '' labels: bug assignees: '' --- **Describe the bug** A clear and concise description of what the bug is. **To Reproduce** Steps to reproduce the behavior: 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' 4. See error **Expected behavior** A clear and concise description of what you expected to happen. **Screenshots** If applicable, add screenshots to help explain your problem. **Desktop (please complete the following information):** - OS: [e.g. iOS] - Browser [e.g. chrome, safari] - Version [e.g. 22] **Smartphone (please complete the following information):** - Device: [e.g. iPhone6] - OS: [e.g. iOS8.1] - Browser [e.g. stock browser, safari] - Version [e.g. 22] **Additional context** Add any other context about the problem here. ================================================ FILE: .github/ISSUE_TEMPLATE/feature-request-or-improvement.md ================================================ --- name: Feature request or improvement about: Suggest a new feature or improvement title: '' labels: '' assignees: '' --- **Is your request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context or screenshots about the feature request here. ================================================ FILE: .github/workflows/docker-publish.yml ================================================ name: Docker on: push: branches: [ "main" ] tags: [ 'v*.*.*' ] pull_request: branches: [ "main" ] env: REGISTRY: ghcr.io IMAGE_NAME: ${{ github.repository }} NODE_ENV: production jobs: build: runs-on: ubuntu-latest permissions: contents: read packages: write id-token: write strategy: fail-fast: false matrix: image: ["ghcr.io/${{ github.repository }}", "ghcr.io/${{ github.repository }}-worker", "ghcr.io/${{ github.repository }}-client"] include: - image: "ghcr.io/${{ github.repository }}" dockerfile: "./apps/server/Dockerfile" nx: "server:build" - image: "ghcr.io/${{ github.repository }}-worker" dockerfile: "./apps/workers/Dockerfile" nx: "workers:build" - image: "ghcr.io/${{ github.repository }}-client" dockerfile: "./apps/client/Dockerfile" nx: "client:build" steps: - name: Checkout repository uses: actions/checkout@v3 - name: Install cosign if: github.event_name != 'pull_request' uses: sigstore/cosign-installer@6e04d228eb30da1757ee4e1dd75a0ec73a653e06 #v3.1.1 with: cosign-release: 'v2.1.1' - name: Set up Docker Buildx uses: docker/setup-buildx-action@f95db51fddba0c2d1ec667646a06c2ce06100226 # v3.0.0 - name: Log into registry ${{ env.REGISTRY }} if: github.event_name != 'pull_request' uses: docker/login-action@343f7c4344506bcbf9b4de18042ae17996df046d # v3.0.0 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - name: Extract Docker metadata id: meta uses: docker/metadata-action@96383f45573cb7f253c731d3b3ab81c87ef81934 # v5.0.0 with: images: ${{ matrix.image }} - name: Setup node uses: actions/setup-node@v4 with: node-version: '16' - uses: pnpm/action-setup@v2 name: Install pnpm with: version: 8 run_install: false - name: Get pnpm store directory shell: bash run: | echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV - uses: actions/cache@v3 name: Setup pnpm cache with: path: ${{ env.STORE_PATH }} key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} restore-keys: | ${{ runner.os }}-pnpm-store- - name: Install dependencies run: pnpm install --frozen-lockfile --production=false - name: Run nx target run: npx nx run ${{ matrix.nx }} - name: Build and push Docker image id: build-and-push uses: docker/build-push-action@0565240e2d4ab88bba5387d719585280857ece09 # v5.0.0 with: context: . file: ${{ matrix.dockerfile }} push: ${{ github.event_name != 'pull_request' }} tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} cache-from: type=gha cache-to: type=gha,mode=max - name: Sign the published Docker image if: ${{ github.event_name != 'pull_request' }} env: TAGS: ${{ steps.meta.outputs.tags }} DIGEST: ${{ steps.build-and-push.outputs.digest }} run: echo "${TAGS}" | xargs -I {} cosign sign --yes {}@${DIGEST} ================================================ FILE: .gitignore ================================================ # See http://help.github.com/ignore-files/ for more about ignoring files. # compiled output **/dist **/tmp **/out-tsc # dependencies **/node_modules # IDEs and editors /.idea .project .classpath .c9/ *.launch .settings/ *.sublime-workspace # IDE - VSCode .vscode/* !.vscode/settings.json !.vscode/tasks.json !.vscode/launch.json !.vscode/extensions.json # misc /.sass-cache /connect.lock /coverage /libpeerconnection.log npm-debug.log yarn-error.log testem.log /typings exceptions.log error.log combined.log /tools/output # System Files .DS_Store Thumbs.db # ENV **/.env **/.env.local # Next.js .next # nx migrations.json # Shouldn't happen, but backup since we have a script that generates these locally *.pem certs/ ================================================ FILE: .husky/pre-commit ================================================ #!/bin/sh . "$(dirname "$0")/_/husky.sh" pnpm lint-staged ================================================ FILE: .prettierignore ================================================ # Add files here to ignore them from prettier formatting /dist /coverage ================================================ FILE: .prettierrc ================================================ { "trailingComma": "es5", "printWidth": 100, "tabWidth": 4, "semi": false, "singleQuote": true } ================================================ FILE: .storybook/main.js ================================================ module.exports = { stories: [], addons: ['@storybook/addon-essentials'], // uncomment the property below if you want to apply some webpack config globally // webpackFinal: async (config, { configType }) => { // // Make whatever fine-grained changes you need that should apply to all storybook configs // // Return the altered config // return config; // }, } ================================================ FILE: .storybook/tsconfig.json ================================================ { "extends": "../tsconfig.base.json", "exclude": ["../**/*.spec.js", "../**/*.spec.ts", "../**/*.spec.tsx", "../**/*.spec.jsx"], "include": ["../**/*"] } ================================================ FILE: .vscode/extensions.json ================================================ { "recommendations": [ "nrwl.angular-console", "esbenp.prettier-vscode", "firsttris.vscode-jest-runner", "dbaeumer.vscode-eslint", "prisma.prisma" ] } ================================================ FILE: .vscode/launch.json ================================================ { "version": "0.2.0", "configurations": [ { "type": "pwa-node", "request": "launch", "name": "Jest run current file", "program": "${workspaceFolder}/node_modules/.bin/nx", "cwd": "${workspaceFolder}", "args": [ "test", "--testPathPattern=${fileBasenameNoExtension}", "--runInBand", "--skip-nx-cache" ], "skipFiles": ["/**", "${workspaceFolder/node_modules/**/*}"], "console": "integratedTerminal", "internalConsoleOptions": "neverOpen", "env": { "IS_VSCODE_DEBUG": "true", "NX_DATABASE_URL": "postgresql://maybe:maybe@localhost:5432/maybe_local" } }, { "name": "server debug", "type": "node", "request": "attach", "restart": false, "port": 9228, "address": "localhost", "localRoot": "${workspaceFolder}", "skipFiles": ["/**"], "remoteRoot": "/app" }, { "name": "workers debug", "type": "node", "request": "attach", "restart": false, "port": 9227, "address": "localhost", "localRoot": "${workspaceFolder}", "skipFiles": ["/**"], "remoteRoot": "/app" } ] } ================================================ FILE: .vscode/settings.json ================================================ { "css.customData": [".vscode/css_custom_data.json"], "[typescript]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[typescriptreact]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[html]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "typescript.enablePromptUseWorkspaceTsdk": true, "typescript.tsdk": "node_modules/typescript/lib" } ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing to Maybe It means so much that you're interested in contributing to Maybe! Seriously. Thank you. The entire community benefits from these contributions! Before submitting a new issue or PR, check if it already exists in [issues](https://github.com/maybe-finance/maybe/issues) or [PRs](https://github.com/maybe-finance/maybe/pulls) so you have an idea of where things stand. Then, once you're ready to begin work, submit a draft PR with your high-level plan (or the full solution). Given the speed at which we're moving on the codebase, we don't assign issues or "give" issues to anyone. When multiple PRs are submitted for the same issue, we take the one that most succinctly & efficiently solves a given problem and stays within the scope of work. Priority is also generally given to previous committers as they've proven familiarity with the codebase and product. ================================================ FILE: LICENSE ================================================ GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . ================================================ FILE: README.md ================================================ **🚨 NOTE: This codebase is no longer being maintained. The repo we're actively working on is located at [maybe-finance/maybe](https://github.com/maybe-finance/maybe).** --- ![](https://github.com/maybe-finance/maybe/assets/35243/79d97b31-7fad-4031-9e83-5005bc1d7fd0) # Maybe: Open-source personal finance app Get involved: [Discord](https://link.maybe.co/discord) • [Website](https://maybe.co) • [Issues](https://github.com/maybe-finance/maybe/issues) ## Backstory We spent the better part of 2021/2022 building a personal finance + wealth management app called, Maybe. Very full-featured, including an "Ask an Advisor" feature which connected users with an actual CFP/CFA to help them with their finances (all included in your subscription). The business end of things didn't work out, and so we shut things down mid-2023. We spent the better part of $1,000,000 building the app (employees + contractors, data providers/services, infrastructure, etc.). We're now reviving the product as a fully open-source project. The goal is to let you run the app yourself, for free, and use it to manage your own finances and eventually offer a hosted version of the app for a small monthly fee. ## End goal Ultimately we want to rebuild this so that you can self-host, but we also have plans to offer a hosted version for a fee. That means some decisions will be made that don't explicitly make sense for self-hosted but _do_ support the goal of us offering a for-pay hosted version. ## Features As a personal finance + wealth management app, Maybe has a lot of features. Here's a brief overview of some of the main ones... - Net worth tracking - Financial account syncing - Investment benchmarking - Investment portfolio allocation - Debt insights - Retirement forecasting + planning - Investment return simulation - Manual account/investment tracking And dozens upon dozens of smaller features. ## Getting started This is the current state of building the app. We're actively working to make this process much more streamlined! _You'll need Docker installed to run the app locally._ [Docker Desktop](https://www.docker.com/products/docker-desktop/) is an easy way to get started. First, copy the `.env.example` file to `.env`: ``` cp .env.example .env ``` Then, create a new secret using `openssl rand -base64 32` and populate `NEXTAUTH_SECRET` in your `.env` file with it. To enable transactional emails, you'll need to create a [Postmark](https://postmarkapp.com/) account and add your API key to your `.env` file (`NX_EMAIL_PROVIDER_API_TOKEN`) and set `NX_EMAIL_PROVIDER` to `postmark`. You can also set the from and reply-to email addresses (`NX_EMAIL_FROM_ADDRESS` and `NX_EMAIL_REPLY_TO_ADDRESS`). If you want to run the app without email, you can set `NX_EMAIL_PROVIDER_API_TOKEN` to a dummy value or leave `NX_EMAIL_PROVIDER` blank. We also support SMTP for sending emails, see information about configuring environment variables in the `.env.example` file. Maybe uses [Teller](https://teller.io/) for connecting financial accounts. To get started with Teller, you'll need to create an account. Once you've created an account: - Add your Teller application id to your `.env` file (`NEXT_PUBLIC_TELLER_APP_ID`). - Download your authentication certificates from Teller, create a `certs` folder in the root of the project, and place your certs in that directory. You should have both a `certificate.pem` and `private_key.pem`. **NEVER** check these files into source control, the `.gitignore` file will prevent the `certs/` directory from being added, but please double-check. - Set your `NEXT_PUBLIC_TELLER_ENV` and `NX_TELLER_ENV` to your desired environment. The default is `sandbox` which allows for testing with mock data. The login credentials for the sandbox environment are `username` and `password`. To connect to real financial accounts, you'll need to use the `development` environment. - Webhooks are not implemented yet, but you can populate the `NX_TELLER_SIGNING_SECRET` with the value from your Teller account. - We highly recommend checking out the [Teller docs](https://teller.io/docs) for more info. Then run the following pnpm commands: ```shell pnpm install pnpm run dev:services:all pnpm prisma:migrate:dev pnpm prisma:seed pnpm dev ``` ## Set Up Ngrok External data providers require HTTPS/SSL webhook URLs for sending data. To test this locally/during development, you will need to setup `ngrok`. 1. Visit [ngrok.com](https://ngrok.com/) 2. Create a free account 3. Visit [this page](https://dashboard.ngrok.com/get-started/your-authtoken) to access your auth token 4. Paste it into your `.env` file: `NGROK_AUTH_TOKEN=your_auth_token` You should claim your free static domain to avoid needing to change the URL each time you start/stop the server. To do so: 1. Visit the [domains](https://dashboard.ngrok.com/cloud-edge/domains) page 2. Click on Create Domain 3. Copy the domain and paste it into your `.env` file: `NGROK_DOMAIN=your_domain` That's it! As long as you run the project locally using `docker` with `pnpm dev:services:all` you'll be good to go. ## External data To pull market data in (for investments), you'll need a Polygon.io API key. You can get one for free [here](https://polygon.io/) and then add it to your `.env` file (`NX_POLYGON_API_KEY`). **Note:** If you're using the free "basic" plan, you'll need to manually sync stock tickers using the dev tools in the app the first time you run it. It will then be re-synced automatically every 24 hours. If you're using a paid tier, be sure to update your `.env` file with the correct tier (`NX_POLYGON_API_TIER`) and tickers and pricing will be synced automatically. ## Tech stack - Next.js - Tailwind - Node.js - Express - Postgres (w/ Timescale) ## Credits The original app was built by [Zach Gollwitzer](https://twitter.com/zg_dev), [Nick Arciero](https://www.narciero.com/) and [Tim Wilson](https://twitter.com/actualTimWilson), with design work by [Justin Farrugia](https://twitter.com/justinmfarrugia). ## Copyright & license Maybe is distributed under an [AGPLv3 license](https://github.com/maybe-finance/maybe-archive/blob/main/LICENSE). "Maybe" is a trademark of Maybe Finance, Inc. ================================================ FILE: apps/.gitkeep ================================================ ================================================ FILE: apps/client/.babelrc.json ================================================ { "presets": ["next/babel"], "plugins": [] } ================================================ FILE: apps/client/.eslintrc.json ================================================ { "extends": [ "plugin:@nrwl/nx/react-typescript", "../../.eslintrc.json", "next", "next/core-web-vitals" ], "ignorePatterns": [ "!**/*", "styles.css", "**/*.csv", "**/public/*", "**/.next/*", "**/*.sh", "Dockerfile" ], "overrides": [ { "files": ["*.ts", "*.tsx", "*.js", "*.jsx"], "rules": { "@next/next/no-img-element": "off", "@next/next/no-html-link-for-pages": "off" } }, { "files": ["*.ts", "*.tsx"], "rules": {} }, { "files": ["*.js", "*.jsx"], "rules": {} } ], "env": { "jest": true }, "settings": { "next": { "rootDir": "apps/advisor" } } } ================================================ FILE: apps/client/.storybook/main.js ================================================ const rootMain = require('../../../.storybook/main') module.exports = { ...rootMain, core: { ...rootMain.core, builder: 'webpack5' }, stories: ['../**/*.stories.@(js|jsx|ts|tsx)', '../stories/**/*.stories.@(js|jsx|ts|tsx)'], addons: [...rootMain.addons, '@nrwl/react/plugins/storybook'], webpackFinal: async (config, { configType }) => { // apply any global webpack configs that might have been specified in .storybook/main.js if (rootMain.webpackFinal) { config = await rootMain.webpackFinal(config, { configType }) } // add your own webpack tweaks if needed return config }, } ================================================ FILE: apps/client/.storybook/manager.js ================================================ import { addons } from '@storybook/addons' import theme from './theme' addons.setConfig({ theme, }) ================================================ FILE: apps/client/.storybook/preview.js ================================================ import '../styles.css' import theme from './theme' export const parameters = { docs: { theme, }, } ================================================ FILE: apps/client/.storybook/theme.js ================================================ import { create } from '@storybook/theming' import logo from '../assets/logo.svg' export default create({ base: 'dark', brandTitle: 'Maybe', brandUrl: 'https://maybe.co', brandImage: logo, fontBase: '"General Sans", sans-serif', colorPrimary: '#4361EE', colorSecondary: '#F12980', appBg: '#1C1C20', appContentBg: '#16161A', }) ================================================ FILE: apps/client/.storybook/tsconfig.json ================================================ { "extends": "../tsconfig.json", "compilerOptions": { "allowImportingTsExtensions": true }, "include": ["**/*.ts", "**/*.tsx", "**/**/*.ts", "**/**/*.tsx"] } ================================================ FILE: apps/client/Dockerfile ================================================ # ------------------------------------------ # BUILD STAGE # ------------------------------------------ FROM node:18-alpine3.18 as builder WORKDIR /app COPY ./dist/apps/client ./prisma ./package.json ./ # Install dependencies RUN npm install -g pnpm # nrwl/nx#20079, generated lockfile is completely broken RUN rm -f pnpm-lock.yaml RUN pnpm install --no-frozen-lockfile --production=false # ------------------------------------------ # PROD STAGE # ------------------------------------------ FROM node:18-alpine3.18 as prod COPY ./apps/client/env.sh /env.sh RUN chmod +x /env.sh # Used for container health checks and env handling RUN apk add --no-cache curl gawk bash WORKDIR /app USER node COPY --from=builder --chown=node:node /app . ENTRYPOINT ["/env.sh"] CMD ["npx", "next", "start"] ================================================ FILE: apps/client/components/APM.tsx ================================================ import { useEffect } from 'react' import * as Sentry from '@sentry/react' import { useSession } from 'next-auth/react' export default function APM() { const { data: session } = useSession() // Identify Sentry user useEffect(() => { if (session && session.user) { Sentry.setUser({ id: session.user['sub'] ?? undefined, email: session.user['https://maybe.co'] ?? undefined, }) } }, [session]) return null } ================================================ FILE: apps/client/components/Maintenance.stories.tsx ================================================ import type { Story, Meta } from '@storybook/react' import Maintenance from './Maintenance' import React from 'react' export default { title: 'components/Maintenance.tsx', component: Maintenance, } as Meta const Template: Story = () => { return ( <> ) } export const Base = Template.bind({}) ================================================ FILE: apps/client/components/Maintenance.tsx ================================================ export default function Maintenance() { return (

We'll be back soon!

We are currently doing some site maintenance and will be back up shortly.

) } ================================================ FILE: apps/client/components/Meta.tsx ================================================ import Head from 'next/head' import React from 'react' import env from '../env' export default function Meta() { return ( {/* */} Maybe {/* */} {/* */} {/* */} {/* */} {/* */} ) } ================================================ FILE: apps/client/components/account-views/DefaultView.tsx ================================================ import type { ReactNode } from 'react' import type { Account } from '@prisma/client' import type { SharedType } from '@maybe-finance/shared' import type { SelectableDateRange, SelectableRangeKeys } from '@maybe-finance/design-system' import { AccountMenu, PageTitle } from '@maybe-finance/client/features' import { TSeries } from '@maybe-finance/client/shared' import { DatePickerRange, getRangeDescription } from '@maybe-finance/design-system' import { NumberUtil } from '@maybe-finance/shared' import { DateTime } from 'luxon' import { useMemo } from 'react' export type DefaultViewProps = { account?: SharedType.AccountDetail balances?: SharedType.AccountBalanceResponse dateRange: SharedType.DateRange onDateChange: (range: SharedType.DateRange) => void getContent: (accountId: Account['id']) => ReactNode isLoading: boolean isError: boolean selectableDateRanges?: Array } export default function DefaultView({ account, balances, dateRange, onDateChange, getContent, isLoading, isError, selectableDateRanges, }: DefaultViewProps) { const allTimeRange = useMemo(() => { return { label: 'All', labelShort: 'All', start: balances?.minDate ?? DateTime.now().minus({ years: 2 }).toISODate(), end: DateTime.now().toISODate(), } }, [balances]) return (
({ date: v.date, values: { balance: v.balance }, }))} series={[ { key: 'balances', accessorFn: (d) => d.values.balance?.toNumber(), negative: account?.classification === 'liability', }, ]} >
{account &&
{getContent(account.id)}
}
) } ================================================ FILE: apps/client/components/account-views/InvestmentView.tsx ================================================ import { type InsightCardOption, InsightPopout, usePopoutContext, useAccountApi, InsightGroup, TSeries, } from '@maybe-finance/client/shared' import { AccountMenu, Explainers, HoldingList, InvestmentTransactionList, PageTitle, } from '@maybe-finance/client/features' import { Checkbox, DatePickerRange, getRangeDescription, Listbox, } from '@maybe-finance/design-system' import { type SharedType, NumberUtil } from '@maybe-finance/shared' import { DateTime } from 'luxon' import { useCallback, useEffect, useMemo, useState } from 'react' import { RiAddLine, RiArrowUpDownLine, RiCoinLine, RiLineChartLine, RiPercentLine, RiScalesFill, RiStackLine, RiSubtractLine, } from 'react-icons/ri' import type { IconType } from 'react-icons' import classNames from 'classnames' type Props = { account?: SharedType.AccountDetail balances?: SharedType.AccountBalanceResponse dateRange: SharedType.DateRange onDateChange: (range: SharedType.DateRange) => void isLoading: boolean isError: boolean } const stockInsightCards: InsightCardOption[] = [ { id: 'profit-loss', display: 'Potential gain or loss', category: 'General', tooltip: 'The amount you would gain or lose if you sold this entire portfolio today. This is commonly referred to as "capital gains / losses".', }, { id: 'avg-return', display: 'Average return', category: 'General', tooltip: 'The average return you have achieved over the time period on this portfolio of holdings', }, { id: 'net-deposits', display: 'Contributions', category: 'General', tooltip: 'The total amount you have contributed to this brokerage account. Deposits increase this number and withdrawals decrease it.', }, { id: 'fees', display: 'Fees', category: 'Cost', tooltip: 'The total brokerage and other fees you have incurred while buying and selling holdings', }, { id: 'sector-allocation', display: 'Sector allocation', category: 'Market', tooltip: 'Shows how diverse your portfolio is', }, ] const transactionsFilters: { name: string icon: IconType data: { category?: SharedType.InvestmentTransactionCategory } }[] = [ { name: 'Show all', icon: RiStackLine, data: {}, }, { name: 'Buys', icon: RiAddLine, data: { category: 'buy' }, }, { name: 'Sales', icon: RiSubtractLine, data: { category: 'sell' }, }, { name: 'Dividends', icon: RiPercentLine, data: { category: 'dividend' }, }, { name: 'Transfers', icon: RiArrowUpDownLine, data: { category: 'transfer' }, }, { name: 'Fees', icon: RiCoinLine, data: { category: 'fee' }, }, ] const returnPeriods: { key: 'ytd' | '1y' | '1m'; display: string }[] = [ { key: 'ytd', display: 'This year' }, { key: '1y', display: 'Past year' }, { key: '1m', display: 'Past month' }, ] const contributionPeriods = [ { key: 'ytd', display: 'This year' }, { key: 'lastYear', display: 'Last year' }, ] const chartViews = [ { key: 'value', display: 'Value', icon: RiLineChartLine }, { key: 'return', display: 'Return', icon: RiLineChartLine }, ] type Comparison = { ticker: string; display: string; color: string } const comparisonTickers: Comparison[] = [ { ticker: 'VOO', display: 'S&P 500', color: 'teal', }, { ticker: 'DIA', display: 'Dow Jones Industrial Avg', color: 'red', }, { ticker: 'VONE', display: 'Russell 1000', color: 'indigo', }, { ticker: 'QQQ', display: 'NASDAQ 100', color: 'grape', }, { ticker: 'VT', display: 'Total World Stock Index', color: 'yellow', }, { ticker: 'GLDM', display: 'Gold', color: 'blue', }, { ticker: 'X:BTCUSD', display: 'Bitcoin', color: 'orange', }, { ticker: 'X:ETHUSD', display: 'Ethereum', color: 'gray', }, ] export default function InvestmentView({ account, balances, dateRange, onDateChange, isLoading, isError, }: Props) { const [selectedComparisons, setSelectedComparisons] = useState([]) const [chartView, setChartView] = useState(chartViews[0]) const [showContributions, setShowContributions] = useState(false) const { open: openPopout } = usePopoutContext() const [returnPeriod, setReturnPeriod] = useState(returnPeriods[0]) const [contributionPeriod, setContributionPeriod] = useState(contributionPeriods[0]) const { useAccountInsights, useAccountReturns } = useAccountApi() const returns = useAccountReturns( { id: account?.id ?? -1, start: dateRange.start, end: dateRange.end, compare: selectedComparisons.map((c) => c.ticker), }, { enabled: !!account?.id, keepPreviousData: true, } ) const insights = useAccountInsights(account?.id ?? -1, { enabled: !!account?.id }) const stocksAllocation = useMemo(() => { const stockPercent = insights.data?.portfolio?.holdingBreakdown .find((hb) => hb.asset_class === 'stocks') ?.percentage.toNumber() ?? 0 return { stocks: Math.round(stockPercent * 100), other: Math.round(100 - stockPercent * 100), } }, [insights.data]) const allTimeRange = useMemo(() => { return { label: 'All', labelShort: 'All', start: balances?.minDate ?? DateTime.now().minus({ years: 2 }).toISODate(), end: DateTime.now().toISODate(), } }, [balances]) const returnColorAccessorFn = useCallback< TSeries.AccessorFn<{ rateOfReturn: SharedType.Decimal }, string> >((datum) => { return datum.values?.rateOfReturn?.lessThan(0) ? '#FF8787' : '#38D9A9' // text-red and text-teal }, []) const [transactionFilter, setTransactionFilter] = useState(transactionsFilters[0]) // Whenever user modifies the comparisons dropdown, always go to "Returns" view useEffect(() => { if (selectedComparisons.length > 0) { setChartView(chartViews[1]) } }, [selectedComparisons]) return (
{chartView.display} {chartViews.map((view) => ( {view.display} ))} Compare {comparisonTickers.map((comparison) => ( {comparison.display} ))} {chartView.key === 'value' && (
)}
> id="investment-account-chart" isLoading={isLoading} isError={isError || returns.isError} dateRange={dateRange} data={{ balances: balances?.series.data.map((d) => ({ date: d.date, values: { balance: d.balance }, })) ?? [], returns: returns.data?.data.map((d) => ({ date: d.date, values: { ...d.account, ...d.comparisons }, })) ?? [], }} series={[ { key: 'portfolio-balance', dataKey: 'balances', accessorFn: (d) => d?.values?.balance?.toNumber(), isActive: chartView.key === 'value', }, { key: 'contributions', dataKey: 'returns', accessorFn: (d) => d.values.contributions?.toNumber(), isActive: showContributions && chartView.key === 'value', color: TSeries.tailwindScale('grape'), }, { key: 'portfolio-return', dataKey: 'returns', accessorFn: (d) => d.values.rateOfReturn?.toNumber(), isActive: chartView.key === 'return', format: 'percent', label: 'Portfolio return', color: selectedComparisons.length > 0 ? TSeries.tailwindScale('cyan') : returnColorAccessorFn, }, ...selectedComparisons.map(({ ticker, display, color }) => ({ key: ticker, dataKey: 'returns', accessorFn: (d) => { return d.values?.[ticker]?.toNumber() }, isActive: chartView.key === 'return' && selectedComparisons.length > 0, label: `${display} return`, format: 'percent' as SharedType.FormatString, color: TSeries.tailwindScale(color), })), ]} y1Axis={ NumberUtil.format( v as number, chartView.key === 'return' ? 'percent' : 'short-currency' ) } /> } // If showing returns graph, render a date range for the tooltip title tooltipOptions={ chartView.key === 'return' && returns.data && returns.data.data.length > 0 ? { tooltipTitle: (tooltipData) => `${DateTime.fromISO(returns.data.data[0].date).toFormat( 'MMM dd, yyyy' )} - ${DateTime.fromISO(tooltipData.date).toFormat( 'MMM dd, yyyy' )}`, } : undefined } > {selectedComparisons.map((comparison) => ( ))}
{account && (
openPopout( ) } headerRight={ e.stopPropagation()} > e.stopPropagation()} > {returnPeriod.display} {returnPeriods.map((rp) => ( {rp.display} ))} } > {(() => { const returnValues = insights.data?.portfolio?.return?.[returnPeriod.key] return ( <>

{NumberUtil.format( returnValues?.percentage, 'percent', { signDisplay: 'auto', maximumFractionDigits: 1 } )}

{NumberUtil.format( returnValues?.amount, 'currency', { signDisplay: 'exceptZero', } )} {' '} {returnPeriod.display.toLowerCase()} ) })()}
openPopout( ) } >

{NumberUtil.format( insights.data?.portfolio?.pnl?.amount, 'currency', { signDisplay: 'exceptZero' } )}

as of today
openPopout( ) } headerRight={ e.stopPropagation()} > e.stopPropagation()} > {contributionPeriod.display} {contributionPeriods.map((cp) => ( {cp.display} ))} } >

{NumberUtil.format( insights?.data?.portfolio?.contributions[contributionPeriod.key] .amount, 'currency', { signDisplay: 'exceptZero' } )}

Average: {NumberUtil.format( insights?.data?.portfolio?.contributions[contributionPeriod.key] .monthlyAvg, 'short-currency', { signDisplay: 'exceptZero' } )} /mo
openPopout( ) } >

{NumberUtil.format(insights.data?.portfolio?.fees, 'currency', { signDisplay: 'auto', })}

all time
openPopout( ) } >

{stocksAllocation.stocks}/{stocksAllocation.other} split

{stocksAllocation.stocks}% in stocks and {stocksAllocation.other}% in other
Holdings
Transactions
{transactionFilter.name} {transactionsFilters.map((filter) => ( {filter.name} ))}
)}
) } ================================================ FILE: apps/client/components/account-views/LoanView.tsx ================================================ import type { SharedType } from '@maybe-finance/shared' import { AccountMenu, LoanDetail, PageTitle, TransactionList } from '@maybe-finance/client/features' import { TSeries, useAccountContext } from '@maybe-finance/client/shared' import { Button, DatePickerRange, getRangeDescription } from '@maybe-finance/design-system' import { NumberUtil } from '@maybe-finance/shared' import { DateTime } from 'luxon' import { useMemo, useEffect, useState } from 'react' export type LoanViewProps = { account?: SharedType.AccountDetail balances?: SharedType.AccountBalanceResponse dateRange: SharedType.DateRange onDateChange: (range: SharedType.DateRange) => void isLoading: boolean isError: boolean } export default function LoanView({ account, balances, dateRange, onDateChange, isLoading, isError, }: LoanViewProps) { const { editAccount } = useAccountContext() const [showOverlay, setShowOverlay] = useState(false) const allTimeRange = useMemo(() => { return { label: 'All', labelShort: 'All', start: balances?.minDate ?? DateTime.now().minus({ years: 2 }).toISODate(), end: DateTime.now().toISODate(), } }, [balances]) useEffect(() => { const loanValid = ({ loan }: SharedType.AccountDetail) => { return ( loan && loan.originationDate && loan.originationPrincipal && loan.maturityDate && loan.interestRate && loan.loanDetail ) } if (account && !loanValid(account)) { setShowOverlay(true) } else { setShowOverlay(false) } }, [account, editAccount]) return (
({ date: v.date, values: { balance: v.balance }, }))} series={[ { key: 'balances', accessorFn: (d) => d.values.balance?.toNumber(), negative: true, }, ]} renderOverlay={ showOverlay && account ? () => ( <>

Chart unavailable

Please provide us with more details for this account so that we can build your chart with accurate values.

) : undefined } >
{account && (
{account.transactions.length > 0 && (
Payments
)}
)}
) } ================================================ FILE: apps/client/components/account-views/index.ts ================================================ export { default as DefaultView } from './DefaultView' export { default as LoanView } from './LoanView' ================================================ FILE: apps/client/env.sh ================================================ #!/bin/bash # https://github.com/vercel/next.js/discussions/17641#discussioncomment-5919914 # Config ENVSH_ENV="${ENVSH_ENV:-"./.env"}" ENVSH_PREFIX="${ENVSH_PREFIX:-"NEXT_PUBLIC_"}" ENVSH_PREFIX_STRIP="${ENVSH_PREFIX_STRIP:-false}" # Can be `window.__appenv = {` or `const APPENV = {` or whatever you want ENVSH_PREPEND="${ENVSH_PREPEND:-"window.__appenv = {"}" ENVSH_APPEND="${ENVSH_APPEND:-"}"}" ENVSH_OUTPUT="${ENVSH_OUTPUT:-"./public/__appenv.js"}" [ -f "$ENVSH_ENV" ] && INPUT="$ENVSH_ENV" || INPUT=/dev/null # Add assignment echo "$ENVSH_PREPEND" >"$ENVSH_OUTPUT" gawk -v PREFIX="$ENVSH_PREFIX" -v STRIP_PREFIX="$ENVSH_PREFIX_STRIP" ' BEGIN { OFS=": "; FS="="; PATTERN="^" PREFIX; for (v in ENVIRON) if (v ~ PATTERN) vars[v] = ENVIRON[v] } $0 ~ PATTERN { v = $2; for (i = 3; i <= NF; i++) v = v FS $i; vars[$1] = (vars[$1] ? vars[$1] : v); } END { for (v in vars) { val = vars[v]; switch (val) { case /^true$/: break; case /^false$/: break; case /^'"'.*'"'$/: break; case /^".*"$/: break; case /^[[:digit:]]+$/: break; default: val = "\"" val "\""; break; } val = val "," if (STRIP_PREFIX == "true" || STRIP_PREFIX == "1") v = gensub(PATTERN, "", 1, v) print v, val; } } ' "$INPUT" >>"$ENVSH_OUTPUT" echo "$ENVSH_APPEND" >>"$ENVSH_OUTPUT" # Accepting commands (for Docker) exec "$@" ================================================ FILE: apps/client/env.ts ================================================ declare global { interface Window { __appenv: any } } function isBrowser() { return Boolean(typeof window !== 'undefined' && window.__appenv) } function getEnv(key: string): string | undefined { if (!key.length) { throw new Error('No env key provided') } if (isBrowser()) { return window.__appenv[key] } } const env = { NEXT_PUBLIC_API_URL: getEnv('NEXT_PUBLIC_API_URL') || process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3333', NEXT_PUBLIC_LD_CLIENT_SIDE_ID: getEnv('NEXT_PUBLIC_LD_CLIENT_SIDE_ID') || process.env.NEXT_PUBLIC_LD_CLIENT_SIDE_ID || 'REPLACE_THIS', NEXT_PUBLIC_SENTRY_DSN: getEnv('NEXT_PUBLIC_SENTRY_DSN') || process.env.NEXT_PUBLIC_SENTRY_DSN, NEXT_PUBLIC_SENTRY_ENV: getEnv('NEXT_PUBLIC_SENTRY_ENV') || process.env.NEXT_PUBLIC_SENTRY_ENV, } export default env ================================================ FILE: apps/client/jest.config.ts ================================================ /* eslint-disable */ export default { displayName: 'client', preset: '../../jest.preset.js', transform: { '^(?!.*\\.(js|jsx|ts|tsx|css|json)$)': '@nrwl/react/plugins/jest', '^.+\\.[tj]sx?$': 'babel-jest', }, moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'], coverageDirectory: '../../coverage/apps/client', } ================================================ FILE: apps/client/next-env.d.ts ================================================ /// /// // NOTE: This file should not be edited // see https://nextjs.org/docs/basic-features/typescript for more information. ================================================ FILE: apps/client/next.config.js ================================================ // eslint-disable-next-line @typescript-eslint/no-var-requires const withNx = require('@nrwl/next/plugins/with-nx') const withBundleAnalyzer = require('@next/bundle-analyzer')({ enabled: process.env.ANALYZE === 'true', }) /** * @type {import('@nrwl/next/plugins/with-nx').WithNxOptions} **/ const nextConfig = { nx: { // Set this to true if you would like to to use SVGR // See: https://github.com/gregberge/svgr svgr: false, }, images: { loader: 'custom', }, swcMinify: false, } module.exports = withBundleAnalyzer(withNx(nextConfig)) ================================================ FILE: apps/client/pages/404.tsx ================================================ import { NotFoundPage } from '@maybe-finance/client/features' export function Page404() { return } export default Page404 ================================================ FILE: apps/client/pages/_app.tsx ================================================ import { useEffect, type PropsWithChildren, type ReactElement } from 'react' import type { AppProps } from 'next/app' import { ErrorBoundary } from 'react-error-boundary' import { Analytics } from '@vercel/analytics/react' import { AxiosProvider, QueryProvider, ErrorFallback, LogProvider, UserAccountContextProvider, } from '@maybe-finance/client/shared' import { AccountsManager, OnboardingGuard } from '@maybe-finance/client/features' import { AccountContextProvider } from '@maybe-finance/client/shared' import * as Sentry from '@sentry/react' import { BrowserTracing } from '@sentry/tracing' import env from '../env' import '../styles.css' import { SessionProvider, useSession } from 'next-auth/react' import Meta from '../components/Meta' import APM from '../components/APM' import { useRouter } from 'next/router' Sentry.init({ dsn: env.NEXT_PUBLIC_SENTRY_DSN, environment: env.NEXT_PUBLIC_SENTRY_ENV, integrations: [ new BrowserTracing({ tracingOrigins: ['localhost', new URL(env.NEXT_PUBLIC_API_URL).hostname], }), ], tracesSampleRate: 0.6, }) // Providers and components only relevant to a logged-in user const WithAuth = function ({ children }: PropsWithChildren) { const { data: session, status } = useSession() const router = useRouter() useEffect(() => { if (status === 'loading') return if (!session) { router.push('/login') } }, [session, status, router]) if (session && status === 'authenticated') { return ( {children} ) } return null } export default function App({ Component: Page, pageProps, }: AppProps & { Component: AppProps['Component'] & { getLayout?: (component: ReactElement) => JSX.Element isPublic?: boolean } }) { const getLayout = Page.getLayout ?? ((page) => page) return ( { Sentry.captureException(err) console.error('React app crashed', err) }} > <> {Page.isPublic === true ? ( getLayout() ) : ( {getLayout()} )} ) } ================================================ FILE: apps/client/pages/_document.tsx ================================================ import { Html, Head, Main, NextScript } from 'next/document' export default function Document() { return ( {/* */} {/* eslint-disable-next-line @next/next/no-sync-scripts */} Maybe Finance ================================================ FILE: apps/server/src/app/app.ts ================================================ import type { RequestHandler } from 'express' import express from 'express' import cors from 'cors' import morgan from 'morgan' import * as Sentry from '@sentry/node' import * as SentryTracing from '@sentry/tracing' import * as trpcExpress from '@trpc/server/adapters/express' import { appRouter, createTRPCContext } from './trpc' /** * In Express 4.x, asynchronous errors are NOT automatically passed to next(). This middleware is a small * wrapper around Express that enables automatic async error handling * * Benefit: Eliminates the need for try / catch blocks in routes (i.e. `next(err)` will automatically be called on failed Promise) * * When stable Express 5.x is released, this won't be necessary - https://github.com/expressjs/express/issues/4543#issuecomment-789256044 */ import 'express-async-errors' import logger from './lib/logger' import prisma from './lib/prisma' import { defaultErrorHandler, validateAuthJwt, superjson, authErrorHandler, maintenance, identifySentryUser, devOnly, } from './middleware' import { usersRouter, accountsRouter, connectionsRouter, webhooksRouter, accountRollupRouter, valuationsRouter, institutionsRouter, tellerRouter, transactionsRouter, holdingsRouter, securitiesRouter, plansRouter, toolsRouter, publicRouter, e2eRouter, adminRouter, } from './routes' import env from '../env' const app = express() // put health check before maintenance and other middleware app.get('/health', (_req, res) => { res.status(200).json({ status: 'OK' }) }) if (process.env.NODE_ENV !== 'test') { maintenance(app) } // Mostly defaults recommended by quickstart // - https://docs.sentry.io/platforms/node/guides/express/ // - https://docs.sentry.io/platforms/node/guides/express/performance/ Sentry.init({ dsn: env.NX_SENTRY_DSN, environment: env.NX_SENTRY_ENV, maxValueLength: 8196, integrations: [ new Sentry.Integrations.Http({ tracing: true }), new SentryTracing.Integrations.Express({ app }), new SentryTracing.Integrations.Postgres(), new SentryTracing.Integrations.Prisma({ client: prisma }), ], tracesSampler: (ctx) => { return ctx.request?.method === 'OPTIONS' ? false : ctx.parentSampled ?? true }, }) app.use(Sentry.Handlers.requestHandler()) app.use(Sentry.Handlers.tracingHandler()) app.get('/', (req, res) => { res.render('pages/index', { error: req.query.error }) }) // TODO: Replace "admin" concept from Auth0 with next-auth // Only Auth0 users with a role of "admin" can view these pages (i.e. Maybe Employees) app.use(express.static(__dirname + '/assets')) const origin = [env.NX_CLIENT_URL, ...env.NX_CORS_ORIGINS] logger.info(`CORS origins: ${origin}`) app.use(cors({ origin, credentials: true })) app.options('*', cors() as RequestHandler) app.set('view engine', 'ejs').set('views', __dirname + '/app/admin/views') app.use('/admin', adminRouter) app.use( morgan(env.NX_MORGAN_LOG_LEVEL, { stream: { write: function (message: string) { logger.http(message.trim()) // Trim because Morgan and Logger both add \n, so avoid duplicates here }, }, }) ) // Stripe webhooks require a raw request body app.use('/v1/stripe', express.raw({ type: 'application/json' })) app.use(express.urlencoded({ extended: true })) app.use(express.json()) // ========================================= // API ⬇️ // ========================================= app.use( '/trpc', validateAuthJwt, trpcExpress.createExpressMiddleware({ router: appRouter, createContext: createTRPCContext, }) ) /** * This intercepts the express.json() middleware and modifies both the outgoing and incoming requests * * It is necessary because our models use Date, BigInt, and other non serializable JSON types * * Outgoing requests are serialized, and will be in the format { data: { json, meta }, ...rest } * Incoming requests are deserialized (client sends a serialized object { json, meta }), and attached to req.body */ app.use(superjson) // Public routes // Keep this route public for Render health checks - https://render.com/docs/deploys#health-checks app.get('/v1', (_req, res) => { res.status(200).json({ msg: 'API Running' }) }) app.get('/debug-sentry', function mainHandler(_req, _res) { throw new Error('Server sentry is working correctly') }) app.use('/tools', devOnly, toolsRouter) app.use('/v1', webhooksRouter) app.use('/v1', publicRouter) // All routes AFTER this line are protected via OAuth app.use('/v1', validateAuthJwt) // Private routes app.use('/v1/users', usersRouter) app.use('/v1/e2e', e2eRouter) app.use('/v1/teller', tellerRouter) app.use('/v1/accounts', accountsRouter) app.use('/v1/account-rollup', accountRollupRouter) app.use('/v1/connections', connectionsRouter) app.use('/v1/valuations', valuationsRouter) app.use('/v1/institutions', institutionsRouter) app.use('/v1/transactions', transactionsRouter) app.use('/v1/holdings', holdingsRouter) app.use('/v1/securities', securitiesRouter) app.use('/v1/plans', plansRouter) // Sentry must be the *first* handler app.use(identifySentryUser) app.use(Sentry.Handlers.errorHandler()) // Errors will pass through in order listed, these MUST be at the bottom of this server file app.use(authErrorHandler) // Handles auth/authz specific errors app.use(defaultErrorHandler) // Fallback handler export default app ================================================ FILE: apps/server/src/app/lib/ability.ts ================================================ import type { Subjects } from '@casl/prisma' import { PrismaAbility, accessibleBy } from '@casl/prisma' import type { AbilityClass } from '@casl/ability' import { AbilityBuilder, ForbiddenError } from '@casl/ability' import type { User, Account, AccountBalance, AccountConnection, Transaction, Valuation, Holding, InvestmentTransaction, Security, SecurityPricing, Institution, ProviderInstitution, Plan, } from '@prisma/client' import { AuthUserRole } from '@prisma/client' type CRUDActions = 'create' | 'read' | 'update' | 'delete' type AppActions = CRUDActions | 'manage' type PrismaSubjects = Subjects<{ User: User Account: Account AccountBalance: AccountBalance AccountConnection: AccountConnection Transaction: Transaction Valuation: Valuation Security: Security SecurityPricing: SecurityPricing Holding: Holding InvestmentTransaction: InvestmentTransaction Institution: Institution ProviderInstitution: ProviderInstitution Plan: Omit }> type AppSubjects = PrismaSubjects | 'all' type AppAbility = PrismaAbility<[AppActions, AppSubjects]> export default function defineAbilityFor(user: (Pick & { role: AuthUserRole }) | null) { const { can, build } = new AbilityBuilder(PrismaAbility as AbilityClass) if (user) { if (user.role === AuthUserRole.admin) { can('manage', 'Account') can('manage', 'AccountConnection') can('manage', 'Valuation') can('manage', 'User') can('manage', 'Institution') can('manage', 'Plan') can('manage', 'Holding') can('manage', 'Security') } // Account can('create', 'Account') can('read', 'Account', { userId: user.id }) can('read', 'Account', { accountConnection: { is: { userId: user.id } } }) can('update', 'Account', { userId: user.id }) can('update', 'Account', { accountConnection: { is: { userId: user.id } } }) can('delete', 'Account', { userId: user.id }) can('delete', 'Account', { accountConnection: { is: { userId: user.id } } }) // Valuation can('create', 'Valuation') can('read', 'Valuation', { account: { is: { userId: user.id } } }) can('update', 'Valuation', { account: { is: { userId: user.id } } }) can('delete', 'Valuation', { account: { is: { userId: user.id } } }) // AccountConnection can('create', 'AccountConnection') can('read', 'AccountConnection', { userId: user.id }) can('update', 'AccountConnection', { userId: user.id }) can('delete', 'AccountConnection', { userId: user.id }) // User can('read', 'User', { id: user.id }) can('update', 'User', { id: user.id }) can('delete', 'User', { id: user.id }) // Institution can('read', 'Institution') // Security can('read', 'Security') // Transaction can('read', 'Transaction', { account: { is: { userId: user.id } } }) can('read', 'Transaction', { account: { is: { accountConnection: { is: { userId: user.id } } } }, }) can('update', 'Transaction', { account: { is: { userId: user.id } } }) can('update', 'Transaction', { account: { is: { accountConnection: { is: { userId: user.id } } } }, }) // Holding can('read', 'Holding', { account: { is: { userId: user.id } } }) can('read', 'Holding', { account: { is: { accountConnection: { is: { userId: user.id } } } }, }) can('update', 'Holding', { account: { is: { userId: user.id } } }) can('update', 'Holding', { account: { is: { accountConnection: { is: { userId: user.id } } } }, }) // Plan can('create', 'Plan') can('read', 'Plan', { userId: user.id }) can('update', 'Plan', { userId: user.id }) can('delete', 'Plan', { userId: user.id }) } const ability = build() return { can: ability.can, throwUnlessCan: (...args: Parameters) => { ForbiddenError.from(ability).throwUnlessCan(...args) }, where: accessibleBy(ability), } } ================================================ FILE: apps/server/src/app/lib/email.ts ================================================ import { ServerClient as PostmarkServerClient } from 'postmark' import nodemailer from 'nodemailer' import type SMTPTransport from 'nodemailer/lib/smtp-transport' import env from '../../env' export function initializeEmailClient() { switch (env.NX_EMAIL_PROVIDER) { case 'postmark': if (env.NX_EMAIL_PROVIDER_API_TOKEN) { return new PostmarkServerClient(env.NX_EMAIL_PROVIDER_API_TOKEN) } else { return undefined } case 'smtp': if ( !process.env.NX_EMAIL_SMTP_HOST || !process.env.NX_EMAIL_SMTP_PORT || !process.env.NX_EMAIL_SMTP_USERNAME || !process.env.NX_EMAIL_SMTP_PASSWORD ) { return undefined } else { const transportOptions: SMTPTransport.Options = { host: process.env.NX_EMAIL_SMTP_HOST, port: Number(process.env.NX_EMAIL_SMTP_PORT), secure: process.env.NX_EMAIL_SMTP_SECURE === 'true', auth: { user: process.env.NX_EMAIL_SMTP_USERNAME, pass: process.env.NX_EMAIL_SMTP_PASSWORD, }, } return nodemailer.createTransport(transportOptions) } default: return undefined } } ================================================ FILE: apps/server/src/app/lib/endpoint.ts ================================================ import type { IMarketDataService } from '@maybe-finance/server/shared' import type { IAccountQueryService, IInstitutionService, IInsightService, ISecurityPricingService, IPlanService, } from '@maybe-finance/server/features' import { CryptoService, EndpointFactory, QueueService, PgService, PolygonMarketDataService, CacheService, ServerUtil, RedisCacheBackend, BullQueueFactory, InMemoryQueueFactory, } from '@maybe-finance/server/shared' import type { Request } from 'express' import Redis from 'ioredis' import { AccountService, AccountConnectionService, AuthUserService, UserService, EmailService, AccountQueryService, ValuationService, InstitutionService, AccountConnectionProviderFactory, BalanceSyncStrategyFactory, ValuationBalanceSyncStrategy, TransactionBalanceSyncStrategy, InvestmentTransactionBalanceSyncStrategy, InstitutionProviderFactory, TellerService, TellerETL, TellerWebhookHandler, InsightService, SecurityPricingService, TransactionService, HoldingService, LoanBalanceSyncStrategy, PlanService, ProjectionCalculator, StripeWebhookHandler, } from '@maybe-finance/server/features' import prisma from './prisma' import teller, { getTellerWebhookUrl } from './teller' import stripe from './stripe' import defineAbilityFor from './ability' import env from '../../env' import logger from '../lib/logger' import { initializeEmailClient } from './email' // shared services const redis = new Redis(env.NX_REDIS_URL, { retryStrategy: ServerUtil.redisRetryStrategy({ maxAttempts: 5 }), }) export const queueService = new QueueService( logger.child({ service: 'QueueService' }), process.env.NODE_ENV === 'test' ? new InMemoryQueueFactory() : new BullQueueFactory(logger.child({ service: 'BullQueueFactory' }), env.NX_REDIS_URL) ) export const emailService: EmailService = new EmailService( logger.child({ service: 'EmailService' }), initializeEmailClient(), { from: env.NX_EMAIL_FROM_ADDRESS, replyTo: env.NX_EMAIL_REPLY_TO_ADDRESS, } ) const cryptoService = new CryptoService(env.NX_DATABASE_SECRET) const pgService = new PgService(logger.child({ service: 'PgService' }), env.NX_DATABASE_URL) const cacheService = new CacheService( logger.child({ service: 'CacheService' }), new RedisCacheBackend(redis) ) const marketDataService: IMarketDataService = new PolygonMarketDataService( logger.child({ service: 'PolygonMarketDataService' }), env.NX_POLYGON_API_KEY, cacheService ) const securityPricingService: ISecurityPricingService = new SecurityPricingService( logger.child({ service: 'SecurityPricingService' }), prisma, marketDataService ) const insightService: IInsightService = new InsightService( logger.child({ service: 'InsightService' }), prisma ) const planService: IPlanService = new PlanService( prisma, new ProjectionCalculator(), insightService ) // providers const tellerService = new TellerService( logger.child({ service: 'TellerService' }), prisma, teller, new TellerETL(logger.child({ service: 'TellerETL' }), prisma, teller, cryptoService), cryptoService, getTellerWebhookUrl(), env.NX_TELLER_ENV === 'sandbox' ) // account-connection const accountConnectionProviderFactory = new AccountConnectionProviderFactory({ teller: tellerService, }) const transactionStrategy = new TransactionBalanceSyncStrategy( logger.child({ service: 'TransactionBalanceSyncStrategy' }), prisma ) const investmentTransactionStrategy = new InvestmentTransactionBalanceSyncStrategy( logger.child({ service: 'InvestmentTransactionBalanceSyncStrategy' }), prisma ) const valuationStrategy = new ValuationBalanceSyncStrategy( logger.child({ service: 'ValuationBalanceSyncStrategy' }), prisma ) const loanStrategy = new LoanBalanceSyncStrategy( logger.child({ service: 'LoanBalanceSyncStrategy' }), prisma ) const balanceSyncStrategyFactory = new BalanceSyncStrategyFactory({ INVESTMENT: investmentTransactionStrategy, DEPOSITORY: transactionStrategy, CREDIT: transactionStrategy, LOAN: loanStrategy, PROPERTY: valuationStrategy, VEHICLE: valuationStrategy, OTHER_ASSET: valuationStrategy, OTHER_LIABILITY: valuationStrategy, }) const accountConnectionService = new AccountConnectionService( logger.child({ service: 'AccountConnectionService' }), prisma, accountConnectionProviderFactory, balanceSyncStrategyFactory, securityPricingService, queueService.getQueue('sync-account-connection') ) // account const accountQueryService: IAccountQueryService = new AccountQueryService( logger.child({ service: 'AccountQueryService' }), pgService ) const accountService = new AccountService( logger.child({ service: 'AccountService' }), prisma, accountQueryService, queueService.getQueue('sync-account'), queueService.getQueue('sync-account-connection'), balanceSyncStrategyFactory ) // auth-user const authUserService = new AuthUserService(logger.child({ service: 'AuthUserService' }), prisma) // user const userService = new UserService( logger.child({ service: 'UserService' }), prisma, accountQueryService, balanceSyncStrategyFactory, queueService.getQueue('sync-user'), queueService.getQueue('purge-user'), stripe ) // institution const institutionProviderFactory = new InstitutionProviderFactory({ TELLER: tellerService, }) const institutionService: IInstitutionService = new InstitutionService( logger.child({ service: 'InstitutionService' }), prisma, pgService, institutionProviderFactory ) // valuation const valuationService = new ValuationService( logger.child({ service: 'ValuationService' }), prisma, accountQueryService ) // transaction const transactionService = new TransactionService( logger.child({ service: 'TransactionService' }), prisma ) // holding const holdingService = new HoldingService(logger.child({ service: 'HoldingService' }), prisma) // webhooks const stripeWebhooks = new StripeWebhookHandler( logger.child({ service: 'StripeWebhookHandler' }), prisma, stripe ) const tellerWebhooks = new TellerWebhookHandler( logger.child({ service: 'TellerWebhookHandler' }), prisma, teller, accountConnectionService ) // helper function for parsing JWT and loading User record // TODO: update this with roles, identity, and metadata async function getCurrentUser(jwt: NonNullable) { if (!jwt.sub) throw new Error(`jwt missing sub`) if (!jwt['https://maybe.co/email']) throw new Error(`jwt missing email`) const user = (await prisma.user.findUnique({ where: { authId: jwt.sub }, })) ?? (await prisma.user.upsert({ where: { authId: jwt.sub }, create: { authId: jwt.sub, email: jwt['https://maybe.co/email'], picture: jwt['picture'], firstName: jwt['firstName'], lastName: jwt['lastName'], }, update: {}, })) return { ...user, role: jwt.role, // TODO: Replace Auth0 concepts with next-auth primaryIdentity: {}, userMetadata: {}, appMetadata: {}, } } export async function createContext(req: Request) { const user = req.user ? await getCurrentUser(req.user) : null return { prisma, stripe, logger, user, ability: defineAbilityFor(user), accountService, transactionService, holdingService, accountConnectionService, authUserService, userService, valuationService, institutionService, cryptoService, queueService, stripeWebhooks, tellerService, tellerWebhooks, insightService, marketDataService, planService, emailService, } } export default new EndpointFactory({ createContext, onSuccess: (req, res, data) => res.status(200).superjson(data), }) ================================================ FILE: apps/server/src/app/lib/logger.ts ================================================ import { createLogger } from '@maybe-finance/server/shared' const logger = createLogger({ level: process.env.LOG_LEVEL ?? 'info', }) export default logger ================================================ FILE: apps/server/src/app/lib/prisma.ts ================================================ import { PrismaClient } from '@prisma/client' import { DbUtil } from '@maybe-finance/server/shared' import globalLogger from './logger' const logger = globalLogger.child({ service: 'PrismaClient' }) // https://stackoverflow.com/a/68328402 declare global { var prisma: PrismaClient // eslint-disable-line } function createPrismaClient() { const prisma = new PrismaClient({ log: [ { emit: 'event', level: 'query' }, { emit: 'event', level: 'info' }, { emit: 'event', level: 'warn' }, { emit: 'event', level: 'error' }, ], }) prisma.$on('query', ({ query, params, duration, ...data }) => { logger.silly(`Query: ${query}, Params: ${params}, Duration: ${duration}`, { ...data }) }) prisma.$on('info', ({ message, ...data }) => { logger.info(message, { ...data }) }) prisma.$on('warn', ({ message, ...data }) => { logger.warn(message, { ...data }) }) prisma.$on('error', ({ message, ...data }) => { logger.error(message, { ...data }) }) prisma.$use(DbUtil.slowQueryMiddleware(logger)) return prisma } // Prevent multiple instances of Prisma Client in development // https://www.prisma.io/docs/guides/performance-and-optimization/connection-management#prevent-hot-reloading-from-creating-new-instances-of-prismaclient // https://www.prisma.io/docs/concepts/components/prisma-client/working-with-prismaclient/instantiate-prisma-client#the-number-of-prismaclient-instances-matters const prisma = global.prisma || createPrismaClient() if (process.env.NODE_ENV === 'development') global.prisma = prisma export default prisma ================================================ FILE: apps/server/src/app/lib/stripe.ts ================================================ import Stripe from 'stripe' import env from '../../env' const stripe = new Stripe(env.NX_STRIPE_SECRET_KEY, { apiVersion: '2022-08-01' }) export default stripe ================================================ FILE: apps/server/src/app/lib/teller.ts ================================================ import { TellerApi } from '@maybe-finance/teller-api' import { getWebhookUrl } from './webhook' const teller = new TellerApi() export default teller export async function getTellerWebhookUrl() { const webhookUrl = await getWebhookUrl() return `${webhookUrl}/v1/teller/webhook` } ================================================ FILE: apps/server/src/app/lib/types.ts ================================================ import type { Response, Request, NextFunction } from 'express' interface TypedRequest extends Omit { body: T } interface TypedResponse extends Response { superjson(data: T): TypedResponse } export type DefaultHandler = ( req: TypedRequest, res: TypedResponse, next: NextFunction ) => void // GET requests have optional request type, mandatory response type export type GetHandler = ( req: TypedRequest, // eslint-disable-line res: TypedResponse, next: NextFunction ) => void // Aliases for semantics and convenience export type PostHandler = DefaultHandler export type PutHandler = DefaultHandler export type DeleteHandler = DefaultHandler ================================================ FILE: apps/server/src/app/lib/webhook.ts ================================================ import axios from 'axios' import isCI from 'is-ci' import env from '../../env' import logger from './logger' export async function getWebhookUrl(): Promise { if (process.env.NODE_ENV === 'development' && !isCI && !env.NX_WEBHOOK_URL) { const ngrokUrl = await axios.get(`${env.NX_NGROK_URL}/api/tunnels`).then((res) => { const httpsTunnel = res.data.tunnels.find((t) => t.proto === 'https') return httpsTunnel.public_url }) logger.info(`Generated dynamic ngrok webhook URL: ${ngrokUrl}`) return ngrokUrl } logger.info(`Using ${env.NX_WEBHOOK_URL ? env.NX_WEBHOOK_URL : env.NX_API_URL} for webhook URL`) return env.NX_WEBHOOK_URL || env.NX_API_URL } ================================================ FILE: apps/server/src/app/middleware/auth-error-handler.ts ================================================ import type { ErrorRequestHandler } from 'express' import { ForbiddenError } from '@casl/ability' export const authErrorHandler: ErrorRequestHandler = (err, req, res, next) => { if (err instanceof ForbiddenError) { return res.status(403).json({ errors: [ { status: '403', title: 'Unauthorized', detail: err.message, }, ], }) } next(err) } ================================================ FILE: apps/server/src/app/middleware/dev-only.ts ================================================ import createError from 'http-errors' export const devOnly = (_req, _res, next) => { if (process.env.NODE_ENV !== 'development') { return next(createError(401, 'Route only available in dev mode')) } next() } ================================================ FILE: apps/server/src/app/middleware/error-handler.ts ================================================ import type { ErrorRequestHandler } from 'express' import type { SharedType } from '@maybe-finance/shared' import logger from '../lib/logger' import { ErrorUtil } from '@maybe-finance/server/shared' export const defaultErrorHandler: ErrorRequestHandler = async (err, req, res, _next) => { const parsedError = ErrorUtil.parseError(err) // A custom redirect if user tries to access admin dashboard without Admin role (see /apps/server/src/app/admin/admin-router.ts) if (parsedError.message === 'ADMIN_UNAUTHORIZED') { return res.redirect('/?error=invalid-credentials') } const errors: SharedType.ErrorResponse = { errors: [ { status: parsedError.statusCode || '500', title: parsedError.message, }, ], } logger.error(`[default-express-handler] ${parsedError.message}`, { metadata: parsedError.metadata, stackTrace: parsedError.stackTrace, user: req.user?.sub, request: { method: req.method, url: req.url, }, }) logger.debug(parsedError.stackTrace) res.status(+(parsedError.statusCode || 500)).json(errors) } ================================================ FILE: apps/server/src/app/middleware/identify-user.ts ================================================ import type { ErrorRequestHandler } from 'express' import * as Sentry from '@sentry/node' export const identifySentryUser: ErrorRequestHandler = (err, req, _res, next) => { Sentry.setUser({ authId: req.user?.sub, }) next(err) } ================================================ FILE: apps/server/src/app/middleware/index.ts ================================================ export * from './dev-only' export * from './error-handler' export * from './auth-error-handler' export * from './superjson' export * from './validate-auth-jwt' export * from './validate-teller-signature' export { default as maintenance } from './maintenance' export * from './identify-user' ================================================ FILE: apps/server/src/app/middleware/maintenance.ts ================================================ import type { Express } from 'express' type MaintenanceOptions = { statusCode?: number path?: string featureKey?: string } export default function maintenance( app: Express, { statusCode = 503, path = '/maintenance' }: MaintenanceOptions = {} ) { const enabled = false app.get(path, async (req, res) => { res.status(200).json({ enabled }) }) app.use(async (req, res, next) => { if (enabled) { return res.status(statusCode).json({ message: 'Maintenance in progress' }) } next() }) } ================================================ FILE: apps/server/src/app/middleware/superjson.ts ================================================ import type { RequestHandler } from 'express' import type { SharedType } from '@maybe-finance/shared' import { superjson as sj } from '@maybe-finance/shared' export const superjson: RequestHandler = (req, res, next) => { // Client *should* make requests with valid superjson format, { json: any, meta?: any } if ('json' in req.body) { req.body = sj.deserialize(req.body) } const _json = res.json.bind(res) res.superjson = (data) => { const serialized = sj.serialize(data) const responsePayload: SharedType.SuccessResponse = { data: serialized } return _json(responsePayload) } next() } ================================================ FILE: apps/server/src/app/middleware/validate-auth-jwt.ts ================================================ import cookieParser from 'cookie-parser' import { decode } from 'next-auth/jwt' import type { Request } from 'express' const SECRET = process.env.NEXTAUTH_SECRET ?? 'REPLACE_THIS' const getNextAuthCookie = (req: Request) => { if (req.cookies) { if ('__Secure-next-auth.session-token' in req.cookies) { return req.cookies['__Secure-next-auth.session-token'] } else if ('next-auth.session-token' in req.cookies) { return req.cookies['next-auth.session-token'] } } return undefined } export const validateAuthJwt = async (req, res, next) => { cookieParser(SECRET)(req, res, async (err) => { if (err) { return res.status(500).json({ message: 'Internal Server Error' }) } if (req.cookies && getNextAuthCookie(req)) { try { const token = await decode({ token: getNextAuthCookie(req), secret: SECRET, }) if (token) { req.user = token return next() } else { return res.status(401).json({ message: 'Unauthorized' }) } } catch (error) { console.error('Error in token validation', error) return res.status(500).json({ message: 'Internal Server Error' }) } } else if (req.headers.authorization) { const token = req.headers.authorization.split(' ')[1] const decoded = await decode({ token, secret: SECRET, }) if (decoded) { req.user = decoded return next() } else { return res.status(401).json({ message: 'Unauthorized' }) } } else { return res.status(401).json({ message: 'Unauthorized' }) } }) } ================================================ FILE: apps/server/src/app/middleware/validate-teller-signature.ts ================================================ import crypto from 'crypto' import type { RequestHandler } from 'express' import type { TellerTypes } from '@maybe-finance/teller-api' import env from '../../env' // https://teller.io/docs/api/webhooks#verifying-messages export const validateTellerSignature: RequestHandler = (req, res, next) => { const signatureHeader = req.headers['teller-signature'] as string | undefined if (!signatureHeader) { return res.status(401).send('No Teller-Signature header found') } const { timestamp, signatures } = parseTellerSignatureHeader(signatureHeader) const threeMinutesAgo = Math.floor(Date.now() / 1000) - 3 * 60 if (parseInt(timestamp) < threeMinutesAgo) { return res.status(408).send('Signature timestamp is too old') } const signedMessage = `${timestamp}.${JSON.stringify(req.body as TellerTypes.WebhookData)}` const expectedSignature = createHmacSha256(signedMessage, env.NX_TELLER_SIGNING_SECRET) if (!signatures.includes(expectedSignature)) { return res.status(401).send('Invalid webhook signature') } next() } const parseTellerSignatureHeader = ( header: string ): { timestamp: string; signatures: string[] } => { const parts = header.split(',') const timestampPart = parts.find((p) => p.startsWith('t=')) const signatureParts = parts.filter((p) => p.startsWith('v1=')) if (!timestampPart) { throw new Error('No timestamp in Teller-Signature header') } const timestamp = timestampPart.split('=')[1] const signatures = signatureParts.map((p) => p.split('=')[1]) return { timestamp, signatures } } const createHmacSha256 = (message: string, secret: string): string => { return crypto.createHmac('sha256', secret).update(message).digest('hex') } ================================================ FILE: apps/server/src/app/routes/account-rollup.router.ts ================================================ import { Router } from 'express' import { z } from 'zod' import { DateUtil } from '@maybe-finance/shared' import endpoint from '../lib/endpoint' const router = Router() router.get( '/', endpoint.create({ input: z .object({ start: z.string().transform(DateUtil.dateTransform), end: z.string().transform(DateUtil.dateTransform), }) .partial(), resolve: ({ ctx, input: { start, end } }) => { return ctx.accountService.getAccountRollup(ctx.user!.id, start, end) }, }) ) export default router ================================================ FILE: apps/server/src/app/routes/accounts.router.ts ================================================ import type { Account } from '@prisma/client' import { AssetClass } from '@prisma/client' import type { SharedType } from '@maybe-finance/shared' import { Router } from 'express' import { subject } from '@casl/ability' import { z } from 'zod' import { DateUtil } from '@maybe-finance/shared' import { AccountCreateSchema, AccountUpdateSchema, InvestmentTransactionCategorySchema, } from '@maybe-finance/server/features' import endpoint from '../lib/endpoint' import keyBy from 'lodash/keyBy' import merge from 'lodash/merge' const router = Router() router.get( '/', endpoint.create({ resolve: async ({ ctx }) => { return ctx.accountService.getAll(ctx.user!.id) }, }) ) router.post( '/', endpoint.create({ input: AccountCreateSchema, resolve: async ({ input, ctx }) => { ctx.ability.throwUnlessCan('create', 'Account') let account: Account switch (input.type) { case 'LOAN': { const { currentBalance, ...rest } = input account = await ctx.accountService.create({ ...rest, userId: ctx.user!.id, currentBalanceProvider: currentBalance, currentBalanceStrategy: 'current', }) break } case 'INVESTMENT': { const { name, ...rest } = input account = await ctx.accountService.create({ ...rest, userId: ctx.user!.id, currentBalanceProvider: 0, currentBalanceStrategy: 'current', provider: 'user', name: name, }) break } default: { const { valuations: { originalBalance, currentBalance, currentDate }, startDate, ...rest } = input const initialValuations = [ { source: 'manual', date: startDate!, amount: originalBalance, }, ] if ( startDate && currentBalance && !DateUtil.isSameDate(DateUtil.datetimeTransform(startDate), currentDate) ) { initialValuations.push({ source: 'manual', date: currentDate.toJSDate(), amount: currentBalance, }) } account = await ctx.accountService.create( { ...rest, userId: ctx.user!.id, currentBalanceProvider: currentBalance, currentBalanceStrategy: 'current', }, { create: initialValuations, } ) break } } await ctx.accountService.syncBalances(account.id) return account }, }) ) router.get( '/:id', endpoint.create({ resolve: async ({ ctx, req }) => { const account = await ctx.accountService.getAccountDetails(+req.params.id) ctx.ability.throwUnlessCan('read', subject('Account', account)) return account }, }) ) router.put( '/:id', endpoint.create({ input: AccountUpdateSchema, resolve: async ({ input, ctx, req }) => { const account = await ctx.accountService.get(+req.params.id) ctx.ability.throwUnlessCan('update', subject('Account', account)) const updatedAccount = await ctx.accountService.update(account.id, { ...input.data, ...('currentBalance' in input.data ? { currentBalance: undefined, currentBalanceProvider: input.data.currentBalance, currentBalanceStrategy: 'current', } : {}), }) await ctx.accountService.syncBalances(updatedAccount.id) return updatedAccount }, }) ) router.delete( '/:id', endpoint.create({ resolve: async ({ ctx, req }) => { const account = await ctx.accountService.get(+req.params.id) ctx.ability.throwUnlessCan('delete', subject('Account', account)) return ctx.accountService.delete(account.id) }, }) ) router.get( '/:id/balances', endpoint.create({ input: z .object({ start: z.string().transform(DateUtil.dateTransform), end: z.string().transform(DateUtil.dateTransform), }) .partial(), resolve: async ({ ctx, input, req }) => { const account = await ctx.accountService.get(+req.params.id) ctx.ability.throwUnlessCan('read', subject('Account', account)) return ctx.accountService.getBalances(account.id, input.start, input.end) }, }) ) router.get( '/:id/returns', endpoint.create({ input: z.object({ start: z.string().transform((v) => DateUtil.datetimeTransform(v)), end: z.string().transform((v) => DateUtil.datetimeTransform(v)), compare: z .string() .optional() .transform((v) => v?.split(',')), // in format of /accounts/:id/returns?compare=VOO,AAPL,TSLA }), resolve: async ({ ctx, input, req }): Promise => { const account = await ctx.accountService.get(+req.params.id) ctx.ability.throwUnlessCan('read', subject('Account', account)) const returnSeries: SharedType.AccountReturnTimeSeriesData[] = await ctx.accountService.getReturns( account.id, input.start.toISODate(), input.end.toISODate() ) const baseSeries = { interval: 'days' as SharedType.TimeSeriesInterval, start: input.start.toISODate(), end: input.end.toISODate(), } if (!input.compare || input.compare.length < 1) return { ...baseSeries, data: returnSeries, } const comparisonData = await Promise.allSettled( input.compare.map(async (ticker) => { return { ticker, pricing: await ctx.marketDataService.getDailyPricing( { assetClass: AssetClass.other, currencyCode: 'USD', symbol: ticker }, input.start, input.end ), } }) ) const comparisonPrices = comparisonData .filter( ( data ): data is PromiseFulfilledResult<{ ticker: string pricing: SharedType.DailyPricing[] }> => { if (data.status === 'rejected') { ctx.logger.warn('Unable to generate comparison data', { reason: data.reason, }) } return data.status === 'fulfilled' } ) .map((data) => { return data.value.pricing.map((price) => ({ date: price.date.toISODate(), [data.value.ticker]: price.priceClose .dividedBy(data.value.pricing[0].priceClose) .minus(1), })) }) // Performs a "left join" of prices by ticker const merged: Record< string, SharedType.AccountReturnResponse['data'][number]['comparisons'] > = merge( keyBy( returnSeries.map((v) => ({ date: v.date })), // ensures we have a key for every single day 'date' ), ...comparisonPrices.map((prices) => keyBy(prices, 'date')) ) return { ...baseSeries, data: returnSeries.map((rs) => { return { ...rs, comparisons: merged[rs.date], } }), } }, }) ) router.get( '/:id/transactions', endpoint.create({ input: z .object({ start: z.string().transform(DateUtil.datetimeTransform), end: z.string().transform(DateUtil.datetimeTransform), page: z.string().transform((val) => parseInt(val)), }) .partial(), resolve: async ({ ctx, input, req }) => { const account = await ctx.accountService.get(+req.params.id) ctx.ability.throwUnlessCan('read', subject('Account', account)) return ctx.accountService.getTransactions( account.id, input.page, input.start, input.end ) }, }) ) router.get( '/:id/valuations', endpoint.create({ input: z .object({ start: z.string().transform(DateUtil.datetimeTransform), end: z.string().transform(DateUtil.datetimeTransform), }) .partial(), resolve: async ({ ctx, input, req }) => { const account = await ctx.accountService.get(+req.params.id) ctx.ability.throwUnlessCan('read', subject('Account', account)) return ctx.valuationService.getValuations(account.id, input.start, input.end) }, }) ) router.post( '/:id/valuations', endpoint.create({ input: z.object({ date: z.string().transform(DateUtil.datetimeTransform), amount: z.number(), }), resolve: async ({ ctx, input: { date, amount }, req }) => { const account = await ctx.accountService.get(+req.params.id) ctx.ability.throwUnlessCan('update', subject('Account', account)) if (!date) throw new Error('Invalid valuation date') const valuation = await ctx.valuationService.createValuation({ amount, date: date.toJSDate(), accountId: +req.params.id, source: 'manual', }) await ctx.accountService.syncBalances(+req.params.id) return valuation }, }) ) router.get( '/:id/holdings', endpoint.create({ input: z .object({ page: z.string().transform((val) => parseInt(val)), }) .partial(), resolve: async ({ ctx, input: { page }, req }) => { const account = await ctx.accountService.get(+req.params.id) ctx.ability.throwUnlessCan('read', subject('Account', account)) return ctx.accountService.getHoldings(account.id, page) }, }) ) router.get( '/:id/investment-transactions', endpoint.create({ input: z .object({ page: z.string().transform((val) => parseInt(val)), start: z.string().transform(DateUtil.datetimeTransform).optional(), end: z.string().transform(DateUtil.datetimeTransform).optional(), category: InvestmentTransactionCategorySchema.optional(), }) .partial(), resolve: async ({ ctx, input, req }) => { const account = await ctx.accountService.get(+req.params.id) ctx.ability.throwUnlessCan('read', subject('Account', account)) return ctx.accountService.getInvestmentTransactions( account.id, input.page, input.start, input.end, input.category ) }, }) ) router.get( '/:id/insights', endpoint.create({ resolve: async ({ ctx, req }) => { const account = await ctx.accountService.get(+req.params.id) ctx.ability.throwUnlessCan('read', subject('Account', account)) return ctx.insightService.getAccountInsights({ accountId: account.id }) }, }) ) router.post( '/:id/sync', endpoint.create({ resolve: async ({ ctx, req }) => { const account = await ctx.accountService.get(+req.params.id) ctx.ability.throwUnlessCan('update', subject('Account', account)) return ctx.accountService.sync(+req.params.id) }, }) ) // Syncs account balances without triggering a background worker (syncs balances much faster, ideal for smaller updates such as editing an account valuation) router.post( '/:id/sync/balances', endpoint.create({ resolve: async ({ ctx, req }) => { const account = await ctx.accountService.get(+req.params.id) ctx.ability.throwUnlessCan('update', subject('Account', account)) return ctx.accountService.syncBalances(+req.params.id) }, }) ) export default router ================================================ FILE: apps/server/src/app/routes/admin.router.ts ================================================ import { Router } from 'express' import { createBullBoard } from '@bull-board/api' import { BullAdapter } from '@bull-board/api/bullAdapter' import { ExpressAdapter } from '@bull-board/express' import { BullQueue } from '@maybe-finance/server/shared' import { queueService } from '../lib/endpoint' import { validateAuthJwt } from '../middleware' const router = Router() const serverAdapter = new ExpressAdapter().setBasePath('/admin/bullmq') createBullBoard({ queues: queueService.allQueues .filter((q): q is BullQueue => q instanceof BullQueue) .map((q) => new BullAdapter(q.queue)), serverAdapter, }) router.get('/', validateAuthJwt, (req, res) => { res.render('pages/dashboard', { user: req.user?.name, role: 'Admin', }) }) // Visit /admin/bullmq to see BullMQ Dashboard router.use('/bullmq', validateAuthJwt, serverAdapter.getRouter()) export default router ================================================ FILE: apps/server/src/app/routes/connections.router.ts ================================================ import { Router } from 'express' import { subject } from '@casl/ability' import { z } from 'zod' import endpoint from '../lib/endpoint' import { devOnly } from '../middleware' const router = Router() router.get( '/:id', endpoint.create({ resolve: async ({ ctx, req }) => { const connection = await ctx.accountConnectionService.get(+req.params.id) ctx.ability.throwUnlessCan('read', subject('AccountConnection', connection)) return connection }, }) ) router.put( '/:id', endpoint.create({ input: z.object({ syncStatus: z.enum(['IDLE', 'PENDING', 'SYNCING']) }), resolve: async ({ input, ctx, req }) => { const connection = await ctx.accountConnectionService.get(+req.params.id) ctx.ability.throwUnlessCan('update', subject('AccountConnection', connection)) const updatedConnection = await ctx.accountConnectionService.update( connection.id, input ) return updatedConnection }, }) ) router.post( '/:id/disconnect', endpoint.create({ resolve: async ({ ctx, req }) => { const connection = await ctx.accountConnectionService.get(+req.params.id) ctx.ability.throwUnlessCan('update', subject('AccountConnection', connection)) return ctx.accountConnectionService.disconnect(connection.id) }, }) ) router.post( '/:id/reconnect', endpoint.create({ resolve: async ({ ctx, req }) => { const connection = await ctx.accountConnectionService.get(+req.params.id) ctx.ability.throwUnlessCan('update', subject('AccountConnection', connection)) return ctx.accountConnectionService.reconnect(connection.id) }, }) ) router.post( '/:id/sync', endpoint.create({ resolve: async ({ ctx, req }) => { const connection = await ctx.accountConnectionService.get(+req.params.id) ctx.ability.throwUnlessCan('update', subject('AccountConnection', connection)) return ctx.accountConnectionService.sync(connection.id) }, }) ) router.post( '/:id/sync/:sync', endpoint.create({ resolve: async ({ ctx, req }) => { const connection = await ctx.accountConnectionService.get(+req.params.id) ctx.ability.throwUnlessCan('update', subject('AccountConnection', connection)) switch (req.params.sync) { case 'balances': { await ctx.accountConnectionService.syncBalances(connection.id) break } case 'securities': { await ctx.accountConnectionService.syncSecurities(connection.id) break } default: throw new Error(`unknown sync command: ${req.params.sync}`) } return connection }, }) ) router.delete( '/:id', endpoint.create({ resolve: async ({ ctx, req }) => { const connection = await ctx.accountConnectionService.get(+req.params.id) ctx.ability.throwUnlessCan('delete', subject('AccountConnection', connection)) return ctx.accountConnectionService.delete(connection.id) }, }) ) router.delete( '/', devOnly, endpoint.create({ resolve: async ({ ctx }) => { await ctx.prisma.accountConnection.deleteMany({ where: { userId: ctx.user!.id } }) return { success: true } }, }) ) export default router ================================================ FILE: apps/server/src/app/routes/e2e.router.ts ================================================ import type { OnboardingState } from '@maybe-finance/server/features' import { AuthUserRole } from '@prisma/client' import { Router } from 'express' import { DateTime } from 'luxon' import { z } from 'zod' import endpoint from '../lib/endpoint' const router = Router() router.use((req, res, next) => { const role = req.user?.role if (role === AuthUserRole.admin || role === AuthUserRole.ci) { next() } else { res.status(401).send('Route only available to CIUser and Admin roles') } }) // Validation endpoint for Cypress router.get( '/', endpoint.create({ resolve: async () => { return { success: true } }, }) ) router.post( '/reset', endpoint.create({ input: z.object({ mainOnboardingDisabled: z.boolean().default(true), sidebarOnboardingDisabled: z.boolean().default(true), trialLapsed: z.boolean().default(false), }), resolve: async ({ ctx, input }) => { const user = ctx.user! await ctx.prisma.$transaction([ ctx.prisma.$executeRaw`DELETE FROM "user" WHERE auth_id=${user.authId};`, ctx.prisma.user.create({ data: { authId: user.authId, email: user.email, firstName: user.firstName, lastName: user.lastName, dob: new Date('1990-01-01'), linkAccountDismissedAt: new Date(), // ensures our auto-account link doesn't trigger // Override onboarding flows to be complete for e2e testing onboarding: { main: { markedComplete: input.mainOnboardingDisabled, steps: [] }, sidebar: { markedComplete: input.sidebarOnboardingDisabled, steps: [] }, } as OnboardingState, trialEnd: input.trialLapsed ? DateTime.now().minus({ days: 1 }).toJSDate() : undefined, }, }), ]) return { success: true } }, }) ) router.post( '/clean', endpoint.create({ resolve: async ({ ctx }) => { const user = ctx.user! await ctx.prisma.$transaction([ ctx.prisma.$executeRaw`DELETE FROM "user" WHERE auth_id=${user.authId};`, ctx.prisma.$executeRaw`DELETE FROM "auth_user" WHERE id=${user.authId};`, ]) return { success: true } }, }) ) export default router ================================================ FILE: apps/server/src/app/routes/holdings.router.ts ================================================ import { Router } from 'express' import { subject } from '@casl/ability' import { HoldingUpdateInputSchema } from '@maybe-finance/server/features' import endpoint from '../lib/endpoint' const router = Router() router.get( '/:id', endpoint.create({ resolve: async ({ ctx, req }) => { const holding = await ctx.holdingService.get(+req.params.id) ctx.ability.throwUnlessCan('read', subject('Holding', holding)) return ctx.holdingService.getHoldingDetails(holding.id) }, }) ) router.get( '/:id/insights', endpoint.create({ resolve: async ({ ctx, req }) => { const holding = await ctx.holdingService.get(+req.params.id) ctx.ability.throwUnlessCan('read', subject('Holding', holding)) return ctx.insightService.getHoldingInsights({ holding }) }, }) ) router.put( '/:id', endpoint.create({ input: HoldingUpdateInputSchema, resolve: async ({ input, ctx, req }) => { const holding = await ctx.holdingService.get(+req.params.id) ctx.ability.throwUnlessCan('update', subject('Holding', holding)) const updatedHolding = await ctx.holdingService.update(+req.params.id, input) await ctx.accountService.syncBalances(holding.accountId) return updatedHolding }, }) ) export default router ================================================ FILE: apps/server/src/app/routes/index.ts ================================================ export { default as accountsRouter } from './accounts.router' export { default as accountRollupRouter } from './account-rollup.router' export { default as connectionsRouter } from './connections.router' export { default as usersRouter } from './users.router' export { default as webhooksRouter } from './webhooks.router' export { default as tellerRouter } from './teller.router' export { default as valuationsRouter } from './valuations.router' export { default as institutionsRouter } from './institutions.router' export { default as transactionsRouter } from './transactions.router' export { default as holdingsRouter } from './holdings.router' export { default as securitiesRouter } from './securities.router' export { default as plansRouter } from './plans.router' export { default as toolsRouter } from './tools.router' export { default as publicRouter } from './public.router' export { default as e2eRouter } from './e2e.router' export { default as adminRouter } from './admin.router' ================================================ FILE: apps/server/src/app/routes/institutions.router.ts ================================================ import { Router } from 'express' import { z } from 'zod' import endpoint from '../lib/endpoint' const router = Router() router.get( '/', endpoint.create({ input: z .object({ q: z.string(), page: z.string().transform((val) => parseInt(val)), }) .partial(), resolve: async ({ ctx, input }) => { ctx.ability.throwUnlessCan('read', 'Institution') return ctx.institutionService.getAll({ query: input.q, page: input.page }) }, }) ) router.post( '/sync', endpoint.create({ resolve: async ({ ctx }) => { ctx.ability.throwUnlessCan('update', 'Institution') // Sync all Teller institutions await ctx.queueService .getQueue('sync-institution') .addBulk([{ name: 'sync-teller-institutions', data: {} }]) return { success: true } }, }) ) router.post( '/deduplicate', endpoint.create({ resolve: async ({ ctx }) => { ctx.ability.throwUnlessCan('manage', 'Institution') await ctx.institutionService.deduplicateInstitutions() return { success: true } }, }) ) export default router ================================================ FILE: apps/server/src/app/routes/plans.router.ts ================================================ import { Router } from 'express' import { subject } from '@casl/ability' import { PlanCreateSchema, PlanTemplateSchema, PlanUpdateSchema, } from '@maybe-finance/server/features' import endpoint from '../lib/endpoint' import { DateUtil, PlanUtil } from '@maybe-finance/shared' const router = Router() router.get( '/', endpoint.create({ resolve: async ({ ctx }) => { const { plans } = await ctx.planService.getAll(ctx.user!.id) if (plans.length > 0) return { plans } /** * Generate a default plan so the user can start using the plan feature * without requiring any data inputs up-front. * * Defaults to "Retirement" template */ const plan = await ctx.planService.createWithTemplate(ctx.user!, { type: 'retirement', data: { // Defaults to user age of 30 and retirement age of 65 retirementYear: DateUtil.ageToYear( PlanUtil.RETIREMENT_MILESTONE_AGE, DateUtil.dobToAge(ctx.user?.dob) ?? PlanUtil.DEFAULT_AGE ), }, }) return { plans: [plan], } }, }) ) router.post( '/', endpoint.create({ input: PlanCreateSchema, resolve: async ({ input: { events, milestones, ...data }, ctx }) => { ctx.ability.throwUnlessCan('create', 'Plan') return await ctx.planService.create({ ...data, userId: ctx.user!.id, events: { create: events }, milestones: { create: milestones }, }) }, }) ) /** Create a new plan using a pre-defined template */ router.post( '/template', endpoint.create({ input: PlanTemplateSchema, resolve: async ({ input, ctx }) => { ctx.ability.throwUnlessCan('create', 'Plan') return await ctx.planService.createWithTemplate(ctx.user!, input) }, }) ) /** * Update an existing plan using a pre-defined template * * Can be used to reset a template to defaults or * add milestone-templates to an existing plan */ router.put( '/:id/template', endpoint.create({ input: PlanTemplateSchema, resolve: async ({ ctx, req, input }) => { const plan = await ctx.planService.get(+req.params.id) ctx.ability.throwUnlessCan('update', subject('Plan', plan)) const shouldReset = req.query.reset === 'true' return await ctx.planService.updateWithTemplate(plan.id, input, shouldReset) }, }) ) router.get( '/:id', endpoint.create({ resolve: async ({ ctx, req }) => { const plan = await ctx.planService.get(+req.params.id) ctx.ability.throwUnlessCan('read', subject('Plan', plan)) return plan }, }) ) router.put( '/:id', endpoint.create({ input: PlanUpdateSchema, resolve: async ({ input: { events, milestones, ...data }, ctx, req }) => { const plan = await ctx.planService.get(+req.params.id) ctx.ability.throwUnlessCan('update', subject('Plan', plan)) const updatedPlan = await ctx.planService.update(plan.id, { ...data, events: events ? { create: events.create, update: events.update ? events.update.map(({ id, data }) => ({ where: { id }, data })) : undefined, deleteMany: events.delete ? { id: { in: events.delete } } : undefined, } : undefined, milestones: milestones ? { create: milestones.create, update: milestones.update ? milestones.update.map(({ id, data }) => ({ where: { id }, data })) : undefined, deleteMany: milestones.delete ? { id: { in: milestones.delete } } : undefined, } : undefined, }) return updatedPlan }, }) ) router.delete( '/:id', endpoint.create({ resolve: async ({ ctx, req }) => { const plan = await ctx.planService.get(+req.params.id) ctx.ability.throwUnlessCan('delete', subject('Plan', plan)) return ctx.planService.delete(plan.id) }, }) ) router.get( '/:id/projections', endpoint.create({ resolve: async ({ ctx, req }) => { const plan = await ctx.planService.get(+req.params.id) ctx.ability.throwUnlessCan('read', subject('Plan', plan)) return ctx.planService.projections(plan.id) }, }) ) export default router ================================================ FILE: apps/server/src/app/routes/public.router.ts ================================================ import { Router } from 'express' import env from '../../env' import endpoint from '../lib/endpoint' const router = Router() router.get( '/users/card/:memberId', endpoint.create({ resolve: async ({ ctx, req }) => { const memberId = req.params.memberId if (!memberId) throw new Error('No memberId provided for member details.') const clientUrl = env.NX_CLIENT_URL_CUSTOM || env.NX_CLIENT_URL return ctx.userService.getMemberCard(memberId, clientUrl) }, }) ) export default router ================================================ FILE: apps/server/src/app/routes/securities.router.ts ================================================ import { Router } from 'express' import { DateTime } from 'luxon' import env from '../../env' import endpoint from '../lib/endpoint' const router = Router() router.get( '/', endpoint.create({ resolve: async ({ ctx }) => { ctx.ability.throwUnlessCan('read', 'Security') return await prisma.security.findMany({ select: { symbol: true, exchangeName: true, }, }) }, }) ) router.get( '/:id', endpoint.create({ resolve: async ({ ctx, req }) => { ctx.ability.throwUnlessCan('read', 'Security') return await ctx.prisma.security.findUniqueOrThrow({ where: { id: +req.params.id }, include: { pricing: { where: { date: { gte: DateTime.now().minus({ weeks: 52 }).toJSDate(), lte: DateTime.now().toJSDate(), }, }, orderBy: { date: 'asc', }, }, }, }) }, }) ) router.get( '/:id/details', endpoint.create({ resolve: async ({ ctx, req }) => { ctx.ability.throwUnlessCan('read', 'Security') const security = await ctx.prisma.security.findUniqueOrThrow({ where: { id: +req.params.id }, }) return await ctx.marketDataService.getSecurityDetails(security) }, }) ) router.post( '/sync/us-stock-tickers', endpoint.create({ resolve: async ({ ctx }) => { ctx.ability.throwUnlessCan('manage', 'Security') if (env.NX_POLYGON_API_KEY) { try { await ctx.queueService .getQueue('sync-security') .add('sync-us-stock-tickers', {}) return { success: true } } catch (err) { throw new Error('Failed to sync stock tickers') } } else { throw new Error('No Polygon API key found') } }, }) ) router.post( '/sync/stock-pricing', endpoint.create({ resolve: async ({ ctx }) => { ctx.ability.throwUnlessCan('manage', 'Security') if (env.NX_POLYGON_API_KEY) { try { await ctx.queueService.getQueue('sync-security').add('sync-all-securities', {}) return { success: true } } catch (err) { throw new Error('Failed to sync securities pricing') } } else { throw new Error('No Polygon API key found') } }, }) ) export default router ================================================ FILE: apps/server/src/app/routes/teller.router.ts ================================================ import { Router } from 'express' import { z } from 'zod' import endpoint from '../lib/endpoint' const router = Router() router.post( '/handle-enrollment', endpoint.create({ input: z.object({ institution: z.object({ name: z.string(), id: z.string(), }), enrollment: z.object({ accessToken: z.string(), user: z.object({ id: z.string(), }), enrollment: z.object({ id: z.string(), institution: z.object({ name: z.string(), }), }), signatures: z.array(z.string()).optional(), }), }), resolve: ({ input: { institution, enrollment }, ctx }) => { return ctx.tellerService.handleEnrollment(ctx.user!.id, institution, enrollment) }, }) ) router.post( '/institutions/sync', endpoint.create({ resolve: async ({ ctx }) => { ctx.ability.throwUnlessCan('manage', 'Institution') await ctx.queueService.getQueue('sync-institution').add('sync-teller-institutions', {}) }, }) ) export default router ================================================ FILE: apps/server/src/app/routes/tools.router.ts ================================================ import { Router } from 'express' import _ from 'lodash' import type Decimal from 'decimal.js' import type { ProjectionInput } from '@maybe-finance/server/features' import { AssetValue, monteCarlo, ProjectionCalculator } from '@maybe-finance/server/features' import { StatsUtil } from '@maybe-finance/shared' const router = Router() const params: Record = { stocks: ['0.05', '0.186'], bonds: ['0.02', '0.052'], cash: ['-0.02', '0.05'], crypto: ['1.0', '1.0'], property: ['0.1', '0.2'], other: ['-0.02', '0'], } function getInput(scenario: string, randomized = false): ProjectionInput { const Value = (value, mean, stddev) => new AssetValue(value, mean, randomized ? stddev : 0) const scenarios: Record = { portfolio_vizualizer: { years: 30, assets: [ { id: 'stock', value: Value(800_000, ...params.stocks), }, { id: 'bonds', value: Value(150_000, ...params.bonds), }, { id: 'cash', value: Value(50_000, ...params.cash), }, ], liabilities: [], events: [ { id: 'income', value: new AssetValue(100_000), end: 2032 }, { id: 'expenses', value: new AssetValue(-60_000) }, ], milestones: [ { id: 'retirement', type: 'net-worth', expenseMultiple: 25, expenseYears: 1 }, ], }, debug: { years: 56, assets: [ { id: 'cash', value: Value('283221', ...params.cash), }, { id: 'other', value: Value('221332', ...params.other), }, { id: 'property', value: Value('1300000', ...params.property), }, { id: 'stocks', value: Value('1421113', ...params.stocks), }, ], liabilities: [], events: [ { id: '3', value: new AssetValue('-10000', '0.01'), start: 2022, end: 2072, }, { id: '4', value: new AssetValue('12000'), start: 2050, end: 2072, }, { id: '5', value: new AssetValue('17148'), start: 2050, end: 2072, }, { id: '6', value: new AssetValue('-120000', '0.01'), start: 2022, end: 2076, }, ], milestones: [ { id: '2', type: 'year', year: 2057, }, ], }, } return scenarios[scenario] } router.post('/projections', (req, res) => { const calculator = new ProjectionCalculator() const scenario = 'debug' const N = 500 const tiles = ['0.1', '0.25', '0.5', '0.75', '0.9'] const inputTheo = getInput(scenario, false) const inputRandomized = getInput(scenario, true) const theo = calculator.calculate(inputTheo) const simulations = monteCarlo(() => calculator.calculate(inputRandomized), { n: N }) const simulationsWithStats = _.zipWith(...simulations, (...series) => { const year = series[0].year const netWorths = series.map((d) => d.netWorth) return { year, percentiles: StatsUtil.quantiles(netWorths, tiles), successRate: StatsUtil.rateOf(netWorths, (nw) => nw.gt(0)), ci95: StatsUtil.confidenceInterval(netWorths), avg: StatsUtil.mean(netWorths), netWorths: _.sortBy(netWorths, (nw) => +nw), stddev: StatsUtil.stddev(netWorths), } }) const simulationsByPercentile = tiles.map((percentile, idx) => ({ percentile, simulation: simulationsWithStats.map(({ year, percentiles }) => ({ year, netWorth: percentiles[idx], })), })) const result = { theo, simulations, simulationsWithStats, simulationsByPercentile, } // res.set('cache-control', 'public, max-age=60') res.status(200).json(result) }) export default router ================================================ FILE: apps/server/src/app/routes/transactions.router.ts ================================================ import { Router } from 'express' import { subject } from '@casl/ability' import endpoint from '../lib/endpoint' import { TransactionPaginateParams, TransactionUpdateInputSchema, } from '@maybe-finance/server/features' const router = Router() router.get( '/', endpoint.create({ input: TransactionPaginateParams, resolve: async ({ ctx, input }) => { return ctx.transactionService.getAll(ctx.user!.id, input.pageIndex, input.pageSize) }, }) ) router.get( '/:id', endpoint.create({ resolve: async ({ ctx, req }) => { const transaction = await ctx.transactionService.get(+req.params.id) ctx.ability.throwUnlessCan('read', subject('Transaction', transaction)) return transaction }, }) ) router.put( '/:id', endpoint.create({ input: TransactionUpdateInputSchema, resolve: async ({ input, ctx, req }) => { const transaction = await ctx.transactionService.get(+req.params.id) ctx.ability.throwUnlessCan('update', subject('Transaction', transaction)) const updatedTransaction = await ctx.transactionService.update(+req.params.id, input) await ctx.accountService.syncBalances(transaction.accountId) return updatedTransaction }, }) ) export default router ================================================ FILE: apps/server/src/app/routes/users.router.ts ================================================ import { Router } from 'express' import { subject } from '@casl/ability' import { z } from 'zod' import { DateUtil, type SharedType } from '@maybe-finance/shared' import endpoint from '../lib/endpoint' import env from '../../env' import { type OnboardingState, type RegisteredStep, UpdateOnboardingSchema, } from '@maybe-finance/server/features' const router = Router() router.get( '/', endpoint.create({ resolve: async ({ ctx }) => { return ctx.userService.get(ctx.user!.id) }, }) ) router.get( '/onboarding/:flow', endpoint.create({ resolve: async ({ ctx, req }) => { let onboarding: SharedType.OnboardingResponse switch (req.params.flow) { case 'main': onboarding = await ctx.userService.buildMainOnboarding(ctx.user!.id) break case 'sidebar': onboarding = await ctx.userService.buildSidebarOnboarding(ctx.user!.id) break default: throw new Error(`${req.params.flow} is not a valid onboarding flow key`) } const { steps, currentStep, progress, isComplete, isMarkedComplete } = onboarding return { steps, currentStep, progress, isComplete, isMarkedComplete, } }, }) ) router.put( '/onboarding', endpoint.create({ input: UpdateOnboardingSchema, resolve: async ({ ctx, input }) => { const user = await ctx.prisma.user.findFirstOrThrow({ where: { id: ctx.user!.id }, select: { id: true, onboarding: true }, }) const onboardingState = user.onboarding as OnboardingState | null // Initialize onboarding state const onboarding = onboardingState ? onboardingState : ({ main: { markedComplete: false, steps: [] }, sidebar: { markedComplete: false, steps: [] }, } as OnboardingState) input.updates.forEach((update: RegisteredStep) => { const oldStepIdx = onboarding[input.flow].steps.findIndex( (step) => step.key === update.key ) // Create or update if (oldStepIdx < 0) { onboarding[input.flow].steps.push(update) } else { onboarding[input.flow].steps[oldStepIdx] = update } }) if (input.flow === 'sidebar' && input.markedComplete != null) { onboarding['sidebar'].markedComplete = input.markedComplete } ctx.logger.info( `User onboarding updated. flow=${input.flow} updated=${input.updates.length} user=${ ctx.user!.id }`, input ) return ctx.prisma.user.update({ where: { id: ctx.user!.id }, data: { onboarding }, }) }, }) ) router.get( '/auth-profile', endpoint.create({ resolve: async ({ ctx }) => { return ctx.userService.getAuthProfile(ctx.user!.id) }, }) ) router.get( '/subscription', endpoint.create({ resolve: async ({ ctx }) => { if (!ctx.user || !ctx.user.id) { throw new Error('User not found') } return ctx.userService.getSubscription(ctx.user.id) }, }) ) router.put( '/', endpoint.create({ input: z .object({ monthlyDebtUser: z.number().nullable(), monthlyIncomeUser: z.number().nullable(), monthlyExpensesUser: z.number().nullable(), goals: z.string().array(), riskAnswers: z .object({ questionKey: z.string(), choiceKey: z.string() }) .array() .min(1), household: z.enum([ 'single', 'singleWithDependents', 'dual', 'dualWithDependents', 'retired', ]), country: z.string().nullable(), state: z.string().nullable(), maybeGoals: z.enum(['aggregate', 'advice', 'plan']).array(), maybeGoalsDescription: z.string().nullable(), maybe: z.string().nullable(), title: z.string().nullable(), firstName: z.string(), lastName: z.string(), dob: z.string().transform((d) => DateUtil.datetimeTransform(d).toJSDate()), linkAccountDismissedAt: z.date(), }) .partial(), resolve: ({ input, ctx }) => { if (!ctx.user || !ctx.user.id) { throw new Error('Could not update user. User not found') } return ctx.userService.update(ctx.user.id, input) }, }) ) router.get( '/net-worth', endpoint.create({ input: z .object({ start: z.string().transform(DateUtil.dateTransform), end: z.string().transform(DateUtil.dateTransform), }) .partial(), resolve: ({ ctx, input: { start, end } }) => { return ctx.userService.getNetWorthSeries(ctx.user!.id, start, end) }, }) ) router.get( '/:id/net-worth', endpoint.create({ input: z .object({ start: z.string().transform(DateUtil.dateTransform), end: z.string().transform(DateUtil.dateTransform), }) .partial(), resolve: async ({ ctx, req, input: { start, end } }) => { const user = await ctx.userService.get(+req.params.id) ctx.ability.throwUnlessCan('read', subject('User', user)) return ctx.userService.getNetWorthSeries(user.id, start, end) }, }) ) router.get( '/net-worth/:date', endpoint.create({ resolve: ({ ctx, req }) => { return ctx.userService.getNetWorth( ctx.user!.id, DateUtil.dateTransform(req.params.date) ) }, }) ) router.get( '/:id/net-worth/:date', endpoint.create({ resolve: async ({ ctx, req }) => { const user = await ctx.userService.get(+req.params.id) ctx.ability.throwUnlessCan('read', subject('User', user)) return ctx.userService.getNetWorth(user.id, DateUtil.dateTransform(req.params.date)) }, }) ) router.get( '/:id/account-rollup', endpoint.create({ input: z .object({ start: z.string().transform(DateUtil.dateTransform), end: z.string().transform(DateUtil.dateTransform), }) .partial(), resolve: async ({ ctx, input: { start, end }, req }) => { const user = await ctx.userService.get(+req.params.id) ctx.ability.throwUnlessCan('read', subject('User', user)) return ctx.accountService.getAccountRollup(user.id, start, end) }, }) ) router.get( '/insights', endpoint.create({ resolve: ({ ctx }) => { return ctx.insightService.getUserInsights({ userId: ctx.user!.id }) }, }) ) router.get( '/:id/insights', endpoint.create({ resolve: async ({ ctx, req }) => { const user = await ctx.userService.get(+req.params.id) ctx.ability.throwUnlessCan('read', subject('User', user)) return ctx.insightService.getUserInsights({ userId: user.id }) }, }) ) // TODO: Implement verification email using internal email service instead of Auth0 router.post( '/resend-verification-email', endpoint.create({ input: z.object({ authId: z.string().optional(), }), resolve: async ({ input, ctx }) => { const authId = input.authId ?? ctx.user?.authId if (!authId) throw new Error('User not found') //await ctx.managementClient.sendEmailVerification({ user_id: authId }) ctx.logger.info(`Sent verification email to ${authId}`) return { success: true } }, }) ) router.put( '/change-password', endpoint.create({ input: z.object({ newPassword: z.string(), currentPassword: z.string(), }), resolve: async ({ input, ctx, req }) => { if (!req.user || !req.user.sub) { throw new Error('Unable to update password. No user found.') } const { newPassword, currentPassword } = input try { await ctx.authUserService.updatePassword(req.user.sub, currentPassword, newPassword) } catch (err) { const errMessage = 'Could not reset password' // Do not log the full error here, the user's password could be in it! ctx.logger.error('Could not reset password') return { success: false, error: errMessage } } return { success: true } }, }) ) router.post( '/checkout-session', endpoint.create({ input: z.object({ plan: z.string(), }), resolve: async ({ ctx, req, input }) => { if (!req.user?.sub || !ctx.user) { throw new Error('Unable to create checkout session. No user found.') } const session = await ctx.stripe.checkout.sessions.create({ line_items: [ { price: input.plan === 'yearly' ? env.NX_STRIPE_PREMIUM_YEARLY_PRICE_ID : env.NX_STRIPE_PREMIUM_MONTHLY_PRICE_ID, quantity: 1, }, ], mode: 'subscription', success_url: `${req.headers.origin}/settings?tab=billing&status=success`, cancel_url: `${req.headers.origin}/settings?tab=billing&status=cancelled`, allow_promotion_codes: true, client_reference_id: req.user.sub, // Provide customer ID or user email, not both ...(ctx.user.stripeCustomerId ? { customer: ctx.user.stripeCustomerId, } : { customer_email: (await ctx.authUserService.get(req.user.sub)).email ?? undefined, }), }) if (!session.url) throw new Error('Failed to create checkout session with URL.') return { url: session.url } }, }) ) router.post( '/customer-portal-session', endpoint.create({ resolve: async ({ ctx, req }) => { if (!req.user?.sub || !ctx.user || !ctx.user.stripeCustomerId) { throw new Error('Unable to create customer portal session. No user/customer found.') } const session = await ctx.stripe.billingPortal.sessions.create({ customer: ctx.user.stripeCustomerId, return_url: `${req.headers.origin}/settings?tab=billing`, }) if (!session.url) throw new Error('Failed to create customer portal session with URL.') return { url: session.url } }, }) ) router.delete( '/', endpoint.create({ input: z.object({ confirm: z.literal(true), }), resolve: async ({ ctx }) => { const { id } = ctx.user! ctx.ability.throwUnlessCan('delete', subject('User', ctx.user!)) await ctx.userService.delete(id) }, }) ) router.delete( '/:id', endpoint.create({ input: z.object({ confirm: z.literal(true), }), resolve: async ({ ctx, req }) => { const user = await ctx.userService.get(+req.params.id) ctx.ability.throwUnlessCan('delete', subject('User', user)) await ctx.userService.delete(user.id) }, }) ) router.get( '/card', endpoint.create({ resolve: async ({ ctx }) => { return ctx.userService.getMemberCard( ctx.user!.memberId, env.NX_CLIENT_URL_CUSTOM || env.NX_CLIENT_URL ) }, }) ) router.post( '/send-test-email', endpoint.create({ input: z.object({ recipient: z.string(), subject: z.string(), body: z.string(), }), resolve: async ({ input, ctx, req }) => { if (!req.user || req.user.role !== 'admin') throw new Error('Unauthorized') try { await ctx.emailService.send({ to: input.recipient, subject: input.subject, textBody: input.body, htmlBody: input.body, }) } catch (err) { console.log('Error sending email', err) } ctx.logger.info(`Sent test email to ${input.recipient}`) return { success: true } }, }) ) export default router ================================================ FILE: apps/server/src/app/routes/valuations.router.ts ================================================ import { Router } from 'express' import { z } from 'zod' import { subject } from '@casl/ability' import endpoint from '../lib/endpoint' import { DateUtil } from '@maybe-finance/shared' const router = Router() router.get( '/:id', endpoint.create({ resolve: async ({ ctx, req }) => { const valuation = await ctx.valuationService.getValuation(+req.params.id) ctx.ability.throwUnlessCan('read', subject('Valuation', valuation)) return valuation }, }) ) router.put( '/:id', endpoint.create({ input: z .object({ date: z.string().transform((d) => DateUtil.datetimeTransform(d).toJSDate()), amount: z.number(), }) .optional(), resolve: async ({ ctx, input, req }) => { const valuation = await ctx.valuationService.getValuation(+req.params.id) ctx.ability.throwUnlessCan('update', subject('Valuation', valuation)) if (!input) return valuation const updatedValuation = await ctx.valuationService.updateValuation(+req.params.id, { date: input.date, ...(input.amount && { amount: input.amount }), }) await ctx.accountService.syncBalances(updatedValuation.accountId) return updatedValuation }, }) ) router.delete( '/:id', endpoint.create({ resolve: async ({ ctx, req }) => { const valuation = await ctx.valuationService.getValuation(+req.params.id) ctx.ability.throwUnlessCan('delete', subject('Valuation', valuation)) const deletedValuation = await ctx.valuationService.deleteValuation(+req.params.id) await ctx.accountService.syncBalances(deletedValuation.accountId) return deletedValuation }, }) ) export default router ================================================ FILE: apps/server/src/app/routes/webhooks.router.ts ================================================ import { Router } from 'express' import { z } from 'zod' import { validateTellerSignature } from '../middleware' import endpoint from '../lib/endpoint' import stripe from '../lib/stripe' import env from '../../env' import type { TellerTypes } from '@maybe-finance/teller-api' const router = Router() router.post( '/stripe/webhook', endpoint.create({ async resolve({ req, ctx }) { if (!req.headers['stripe-signature']) throw new Error('Missing `stripe-signature` header') let event try { event = stripe.webhooks.constructEvent( req.body, req.headers['stripe-signature'], env.NX_STRIPE_WEBHOOK_SECRET ) } catch (err) { ctx.logger.error(`Failed to construct Stripe event`, err) throw new Error('Failed to construct Stripe event') } ctx.logger.info(`rx[stripe_webhook] type=${event.type} id=${event.id}`, event.data) await ctx.stripeWebhooks.handleWebhook(event) return { status: 'ok' } }, onSuccess: (_, res, data) => res.status(200).json(data), }) ) router.post( '/teller/webhook', process.env.NODE_ENV !== 'development' ? validateTellerSignature : (_req, _res, next) => next(), endpoint.create({ input: z .object({ id: z.string(), payload: z.object({ enrollment_id: z.string(), reason: z.string(), }), timestamp: z.string(), type: z.string(), }) .passthrough(), async resolve({ input, ctx }) { const { type, id, payload } = input ctx.logger.info( `rx[teller_webhook] event eventType=${type} eventId=${id} enrollmentId=${payload.enrollment_id}` ) // May contain sensitive info, only print at the debug level ctx.logger.debug(`rx[teller_webhook] event payload`, input) try { console.log('handling webhook') await ctx.tellerWebhooks.handleWebhook(input as TellerTypes.WebhookData) } catch (err) { // record error but don't throw ctx.logger.error(`[teller_webhook] error handling webhook`, err) } return { status: 'ok' } }, }) ) export default router ================================================ FILE: apps/server/src/app/trpc.ts ================================================ import * as trpc from '@trpc/server' import type * as trpcExpress from '@trpc/server/adapters/express' import { superjson } from '@maybe-finance/shared' import { createContext } from './lib/endpoint' export async function createTRPCContext({ req }: trpcExpress.CreateExpressContextOptions) { return createContext(req) } type Context = trpc.inferAsyncReturnType const t = trpc.initTRPC.context().create({ transformer: superjson, }) /** * Middleware */ const isUser = t.middleware(({ ctx, next }) => { if (!ctx.user) { throw new trpc.TRPCError({ code: 'UNAUTHORIZED', message: 'You must be a user' }) } return next({ ctx: { ...ctx, user: ctx.user, }, }) }) /** * Routers */ export const appRouter = t.router({ users: t.router({ me: t.procedure.use(isUser).query(({ ctx }) => ctx.user), }), }) export type AppRouter = typeof appRouter ================================================ FILE: apps/server/src/assets/script.js ================================================ // eslint-disable-next-line function login() { window.location.href = '/admin/login' } // eslint-disable-next-line function logout() { window.location.href = '/admin/logout' } ================================================ FILE: apps/server/src/assets/styles.css ================================================ a { text-decoration: none; } .links { display: flex; justify-content: center; min-width: 350px; } .links .btn { margin-left: 10px; } body { background-color: #242629; height: 100vh; color: white; } .unauthorized { background-color: #f85c41; padding: 10px 20px; color: #f8f9fa; border-radius: 5px; margin-bottom: 40px; text-align: center; max-width: 250px; } .container { height: 100%; display: flex; flex-direction: column; justify-content: center; align-items: center; transform: translateY(-60px); } .btn { background-color: #3bc9db; padding: 10px; color: #242629; border: none; border-radius: 5px; } .btn:hover { background-color: rgba(102, 217, 232, 0.9); cursor: pointer; } ================================================ FILE: apps/server/src/env.ts ================================================ import { z } from 'zod' const toOriginArray = (s?: string) => { if (!s) return [] const originList = (s || '').split(',').map((s) => s.trim()) return originList.map((origin) => { const originParts = origin.split('.') // Search for the specific pattern: domain.tld (e.g. maybe.co) and enable wildcard access on domain if (originParts.length === 2) { return new RegExp(`${originParts[0]}\\.${originParts[1]}`) } else { return origin } }) } const envSchema = z.object({ NX_API_URL: z.string().url().default('http://localhost:3333'), NX_CDN_URL: z.string().url().default('https://staging-cdn.maybe.co'), NX_WEBHOOK_URL: z.string().url().optional(), NX_CLIENT_URL: z.string().url().default('http://localhost:4200'), NX_CLIENT_URL_CUSTOM: z.string().url().default('http://localhost:4200'), NX_REDIS_URL: z.string().default('redis://localhost:6379'), NX_DATABASE_URL: z.string(), NX_DATABASE_SECRET: z.string(), NX_NGROK_URL: z.string().default('http://localhost:4551'), NX_TELLER_SIGNING_SECRET: z.string().default('REPLACE_THIS'), NX_TELLER_APP_ID: z.string().default('REPLACE_THIS'), NX_TELLER_ENV: z.string().default('sandbox'), NX_SENTRY_DSN: z.string().optional(), NX_SENTRY_ENV: z.string().optional(), NX_POLYGON_API_KEY: z.string().default(''), NX_POLYGON_TIER: z.string().default('basic'), NX_PORT: z.string().default('3333'), NX_CORS_ORIGINS: z.string().default('https://localhost.maybe.co').transform(toOriginArray), NX_MORGAN_LOG_LEVEL: z .string() .default(process.env.NODE_ENV === 'development' ? 'dev' : 'combined'), NX_STRIPE_SECRET_KEY: z.string().default('REPLACE_THIS'), NX_STRIPE_WEBHOOK_SECRET: z.string().default('whsec_REPLACE_THIS'), NX_STRIPE_PREMIUM_MONTHLY_PRICE_ID: z.string().default('price_REPLACE_THIS'), NX_STRIPE_PREMIUM_YEARLY_PRICE_ID: z.string().default('price_REPLACE_THIS'), NX_CDN_PRIVATE_BUCKET: z.string().default('REPLACE_THIS'), NX_CDN_PUBLIC_BUCKET: z.string().default('REPLACE_THIS'), // Key to secrets manager value NX_CDN_SIGNER_SECRET_ID: z.string().default('/apps/maybe-app/CLOUDFRONT_SIGNER1_PRIV'), // Key to Cloudfront pub key NX_CDN_SIGNER_PUBKEY_ID: z.string().default('REPLACE_THIS'), NX_EMAIL_FROM_ADDRESS: z.string().default('account@maybe.co'), NX_EMAIL_REPLY_TO_ADDRESS: z.string().default('support@maybe.co'), NX_EMAIL_PROVIDER: z.string().optional(), NX_EMAIL_PROVIDER_API_TOKEN: z.string().optional(), }) const env = envSchema.parse(process.env) export default env ================================================ FILE: apps/server/src/environments/environment.prod.ts ================================================ export const environment = { production: true, } ================================================ FILE: apps/server/src/environments/environment.ts ================================================ export const environment = { production: false, } ================================================ FILE: apps/server/src/main.ts ================================================ import type { AddressInfo } from 'net' import env from './env' import app from './app/app' import logger from './app/lib/logger' import * as Sentry from '@sentry/node' process.on('uncaughtException', (error) => { Sentry.captureException(error) logger.error('server: uncaught exception', error) }) process.on('unhandledRejection', (reason, promise) => { Sentry.captureException(reason) logger.error(`server: unhandled promise rejection: ${promise}: ${reason}`) }) const server = app.listen(env.NX_PORT, () => { logger.info(`🚀 API listening at http://localhost:${(server.address() as AddressInfo).port}`) }) // Handle SIGTERM coming from ECS Fargate process.on('SIGTERM', () => server.close()) server.on('error', (err) => logger.error('Server failed to start from main.ts', err)) ================================================ FILE: apps/server/tsconfig.app.json ================================================ { "extends": "./tsconfig.json", "compilerOptions": { "outDir": "../../dist/out-tsc", "module": "commonjs", "types": ["node", "express"] }, "exclude": ["**/*.spec.ts", "**/*.test.ts", "jest.config.ts"], "include": ["**/*.ts", "../../custom-express.d.ts"] } ================================================ FILE: apps/server/tsconfig.json ================================================ { "extends": "../../tsconfig.base.json", "compilerOptions": { "esModuleInterop": true, "noImplicitAny": false, "strict": true, "strictNullChecks": true }, "files": [], "include": [], "references": [ { "path": "./tsconfig.app.json" }, { "path": "./tsconfig.spec.json" } ] } ================================================ FILE: apps/server/tsconfig.spec.json ================================================ { "extends": "./tsconfig.json", "compilerOptions": { "outDir": "../../dist/out-tsc", "module": "commonjs", "types": ["jest", "node"] }, "include": ["**/*.spec.ts", "**/*.test.ts", "../../custom-express.d.ts", "jest.config.ts"] } ================================================ FILE: apps/workers/.eslintrc.json ================================================ { "extends": ["../../.eslintrc.json"], "ignorePatterns": ["!**/*", "Dockerfile"], "overrides": [ { "files": ["*.ts", "*.tsx", "*.js", "*.jsx"], "rules": {} }, { "files": ["*.ts", "*.tsx"], "rules": {} }, { "files": ["*.js", "*.jsx"], "rules": {} }, { "files": ["*.ts"], "rules": { "@typescript-eslint/no-unused-vars": ["warn", { "argsIgnorePattern": "^_" }] } } ] } ================================================ FILE: apps/workers/Dockerfile ================================================ # ------------------------------------------ # BUILD STAGE # ------------------------------------------ FROM node:18-alpine3.18 as builder WORKDIR /app COPY ./dist/apps/workers ./prisma ./ RUN npm install -g pnpm # nrwl/nx#20079, generated lockfile is completely broken RUN rm -f pnpm-lock.yaml RUN pnpm install --prod --no-frozen-lockfile # ------------------------------------------ # PROD STAGE # ------------------------------------------ FROM node:18-alpine3.18 as prod # Used for container health checks RUN apk add --no-cache curl WORKDIR /app USER node COPY --from=builder /app . CMD ["node", "--es-module-specifier-resolution=node", "./main.js"] ================================================ FILE: apps/workers/jest.config.ts ================================================ /* eslint-disable */ export default { displayName: 'workers', preset: '../../jest.preset.js', globals: { 'ts-jest': { tsconfig: '/tsconfig.spec.json', }, }, testEnvironment: 'node', transform: { '^.+\\.[tj]s$': 'ts-jest', }, moduleFileExtensions: ['ts', 'js', 'html'], coverageDirectory: '../../coverage/apps/workers', } ================================================ FILE: apps/workers/src/app/__tests__/helpers/user.test-helper.ts ================================================ import type { PrismaClient, User } from '@prisma/client' import { faker } from '@faker-js/faker' export async function resetUser(prisma: PrismaClient, authId = '__TEST_USER_ID__'): Promise { try { // eslint-disable-next-line const [_, __, ___, user] = await prisma.$transaction([ prisma.$executeRaw`DELETE FROM "user" WHERE auth_id=${authId};`, // Deleting a user does not cascade to securities, so delete all security records prisma.$executeRaw`DELETE from security;`, prisma.$executeRaw`DELETE from security_pricing;`, prisma.user.create({ data: { authId, email: faker.internet.email(), tellerUserId: faker.string.uuid(), }, }), ]) return user } catch (e) { console.error('error in reset user transaction', e) throw e } } ================================================ FILE: apps/workers/src/app/__tests__/queue.integration.spec.ts ================================================ // ===================================================== // Keep these imports above the rest to avoid errors // ===================================================== import { TellerGenerator } from 'tools/generators' import type { User, AccountConnection } from '@prisma/client' import { AccountConnectionType } from '@prisma/client' import prisma from '../lib/prisma' import { default as _teller } from '../lib/teller' import { resetUser } from './helpers/user.test-helper' import { Interval } from 'luxon' // Import the workers process import '../../main' import { queueService } from '../lib/di' // For TypeScript support jest.mock('../lib/teller') const teller = jest.mocked(_teller) let user: User | null let connection: AccountConnection // When debugging, we don't want the tests to time out if (process.env.IS_VSCODE_DEBUG === 'true') { jest.setTimeout(100000) } beforeEach(async () => { jest.clearAllMocks() user = await resetUser(prisma) connection = await prisma.accountConnection.create({ data: { name: 'Chase Test', type: AccountConnectionType.teller, tellerEnrollmentId: 'test-teller-item-workers', tellerInstitutionId: 'chase_test', tellerAccessToken: 'U2FsdGVkX1+WMq9lfTS9Zkbgrn41+XT1hvSK5ain/udRPujzjVCAx/lyPG7EumVZA+nVKXPauGwI+d7GZgtqTA9R3iCZNusU6LFPnmFOCE4=', // need correct encoding here userId: user.id, syncStatus: 'PENDING', }, }) }) afterAll(async () => { await prisma.$disconnect() }) describe('Message queue tests', () => { it('Creates the correct number of queues', () => { expect(queueService.allQueues.map((q) => q.name)).toEqual([ 'sync-user', 'sync-account', 'sync-account-connection', 'sync-security', 'purge-user', 'sync-institution', 'send-email', ]) }) it('Should handle sync errors', async () => { const syncQueue = queueService.getQueue('sync-account-connection') teller.getAccounts.mockRejectedValueOnce(new Error('forced error for Jest tests')) await syncQueue.add('sync-connection', { accountConnectionId: connection.id }) const updatedConnection = await prisma.accountConnection.findUnique({ where: { id: connection.id }, }) expect(teller.getAccounts).toHaveBeenCalledTimes(1) expect(updatedConnection?.status).toEqual('ERROR') }) it('Should run all sync-account-connection queue jobs', async () => { const syncQueue = queueService.getQueue('sync-account-connection') let cnx = await prisma.accountConnection.findUnique({ where: { id: connection.id } }) expect(cnx?.status).toEqual('OK') expect(cnx?.syncStatus).toEqual('PENDING') await syncQueue.add('sync-connection', { accountConnectionId: connection.id }) cnx = await prisma.accountConnection.findUnique({ where: { id: connection.id }, }) expect(cnx?.syncStatus).toEqual('IDLE') }) xit('Should sync connected transaction account', async () => { const syncQueue = queueService.getQueue('sync-account-connection') // Mock will return a basic banking checking account const mockAccounts = TellerGenerator.generateAccountsWithBalances({ count: 1, institutionId: 'chase_test', enrollmentId: 'test-teller-item-workers', institutionName: 'Chase Test', accountType: 'depository', accountSubType: 'checking', }) teller.getAccounts.mockResolvedValueOnce(mockAccounts) const mockTransactions = TellerGenerator.generateTransactions(10, mockAccounts[0].id) teller.getTransactions.mockResolvedValueOnce(mockTransactions) await syncQueue.add('sync-connection', { accountConnectionId: connection.id }) expect(teller.getAccounts).toHaveBeenCalledTimes(1) expect(teller.getTransactions).toHaveBeenCalledTimes(1) const item = await prisma.accountConnection.findUniqueOrThrow({ where: { id: connection.id }, include: { accounts: { include: { balances: { where: TellerGenerator.testDates.prismaWhereFilter, orderBy: { date: 'asc' }, }, transactions: true, holdings: true, valuations: true, investmentTransactions: true, }, }, }, }) expect(item.accounts).toHaveLength(1) const [account] = item.accounts const intervalDates = Interval.fromDateTimes( TellerGenerator.lowerBound, TellerGenerator.now ) .splitBy({ day: 1 }) .map((date: Interval) => date.start.toISODate()) const startingBalance = Number(mockAccounts[0].balance.available) const balances = TellerGenerator.calculateDailyBalances( startingBalance, mockTransactions, intervalDates ) expect(account.transactions).toHaveLength(10) expect(account.balances.map((b) => b.balance)).toEqual(balances) expect(account.holdings).toHaveLength(0) expect(account.valuations).toHaveLength(0) expect(account.investmentTransactions).toHaveLength(0) }) }) ================================================ FILE: apps/workers/src/app/__tests__/security-sync.integration.spec.ts ================================================ import { PrismaClient, SecurityProvider } from '@prisma/client' import winston from 'winston' import Redis from 'ioredis' import nock from 'nock' import type { ISecurityPricingService } from '@maybe-finance/server/features' import { SecurityPricingService } from '@maybe-finance/server/features' import type { IMarketDataService } from '@maybe-finance/server/shared' import { RedisCacheBackend, CacheService, ServerUtil, PolygonMarketDataService, } from '@maybe-finance/server/shared' import { PolygonTestData } from '../../../../../tools/test-data' const prisma = new PrismaClient() const redis = new Redis(process.env.NX_REDIS_URL as string, { retryStrategy: ServerUtil.redisRetryStrategy({ maxAttempts: 1 }), }) beforeAll(() => { process.env.CI = 'true' nock.disableNetConnect() nock('https://api.polygon.io') .get((uri) => uri.includes('/v2/snapshot/locale/us/markets/stocks/tickers')) .reply(200, PolygonTestData.snapshotAllTickers) .persist() nock('https://api.polygon.io') .get((uri) => uri.includes('/v2/aggs/grouped/locale/us/market/stocks')) .reply(200, PolygonTestData.dailyPricing) .persist() nock('https://api.polygon.io') .get((uri) => uri.includes('/v3/reference/exchanges')) .reply(200, PolygonTestData.getExchanges) .persist() nock('https://api.polygon.io') .get( (uri) => uri.includes('/v3/reference/tickers') && uri.includes('market=stocks') && uri.includes('exchange=XNAS') ) .reply(200, PolygonTestData.getNASDAQTickers) .persist() nock('https://api.polygon.io') .get( (uri) => uri.includes('/v3/reference/tickers') && uri.includes('market=stocks') && uri.includes('exchange=XNYS') ) .reply(200, PolygonTestData.getNYSETickers) .persist() }) afterAll(async () => { process.env.CI = '' await Promise.allSettled([prisma.$disconnect(), redis.disconnect()]) }) describe('security pricing sync for non basic tier', () => { let securityPricingService: ISecurityPricingService beforeEach(async () => { const logger = winston.createLogger({ level: 'debug', transports: new winston.transports.Console({ format: winston.format.simple() }), }) const cacheService = new CacheService( logger.child({ service: 'CacheService' }), new RedisCacheBackend(redis) ) const marketDataService: IMarketDataService = new PolygonMarketDataService( logger.child({ service: 'PolygonMarketDataService' }), 'TEST', cacheService ) securityPricingService = new SecurityPricingService( logger.child({ service: 'SecurityPricingService' }), prisma, marketDataService ) // reset db records await prisma.security.deleteMany({ where: { providerName: SecurityProvider.other, }, }) await prisma.security.createMany({ data: [{ symbol: 'AAPL' }, { symbol: 'VOO' }], }) }) it('syncs', async () => { // sync 2x to catch any possible caching I/O issues await securityPricingService.syncSecuritiesPricing() await securityPricingService.syncSecuritiesPricing() }) }) describe('security pricing sync for basic tier', () => { let securityPricingService: ISecurityPricingService let initialPolygonTier: string | undefined beforeEach(async () => { initialPolygonTier = process.env.NX_POLYGON_TIER process.env.NX_POLYGON_TIER = 'basic' // Force basic tier to test code path const logger = winston.createLogger({ level: 'debug', transports: new winston.transports.Console({ format: winston.format.simple() }), }) const cacheService = new CacheService( logger.child({ service: 'CacheService' }), new RedisCacheBackend(redis) ) const marketDataService: IMarketDataService = new PolygonMarketDataService( logger.child({ service: 'PolygonMarketDataService' }), 'TEST', cacheService ) securityPricingService = new SecurityPricingService( logger.child({ service: 'SecurityPricingService' }), prisma, marketDataService ) // reset db records await prisma.security.deleteMany({ where: { providerName: SecurityProvider.other, }, }) await prisma.security.createMany({ data: [{ symbol: 'AAPL' }, { symbol: 'VOO' }], }) }) afterEach(() => { process.env.NX_POLYGON_TIER = initialPolygonTier }) it('syncs', async () => { // sync 2x to catch any possible caching I/O issues await securityPricingService.syncSecuritiesPricing() await securityPricingService.syncSecuritiesPricing() }) }) describe('us stock ticker sync', () => { const apiKey = process.env.NX_POLYGON_API_KEY let securityPricingService: ISecurityPricingService beforeEach(async () => { if (!apiKey) { process.env.NX_POLYGON_API_KEY = 'TEST_KEY' } const logger = winston.createLogger({ level: 'debug', transports: new winston.transports.Console({ format: winston.format.simple() }), }) const cacheService = new CacheService( logger.child({ service: 'CacheService' }), new RedisCacheBackend(redis) ) const marketDataService: IMarketDataService = new PolygonMarketDataService( logger.child({ service: 'PolygonMarketDataService' }), 'TEST', cacheService ) securityPricingService = new SecurityPricingService( logger.child({ service: 'SecurityPricingService' }), prisma, marketDataService ) // reset db records await prisma.security.deleteMany() }) afterEach(() => { process.env.NX_POLYGON_API_KEY = apiKey // Restore original key }) it('syncs', async () => { // sync 2x to catch any possible caching I/O issues await securityPricingService.syncUSStockTickers() await securityPricingService.syncUSStockTickers() expect(await prisma.security.count()).toEqual(20) }) }) ================================================ FILE: apps/workers/src/app/__tests__/teller.integration.spec.ts ================================================ import type { User } from '@prisma/client' import { TellerGenerator } from '../../../../../tools/generators' import { TellerApi } from '@maybe-finance/teller-api' jest.mock('@maybe-finance/teller-api') import { TellerETL, TellerService, type IAccountConnectionProvider, } from '@maybe-finance/server/features' import { createLogger } from '@maybe-finance/server/shared' import prisma from '../lib/prisma' import { resetUser } from './helpers/user.test-helper' import { transports } from 'winston' import { cryptoService } from '../lib/di' const logger = createLogger({ level: 'debug', transports: [new transports.Console()] }) const teller = jest.mocked(new TellerApi()) const tellerETL = new TellerETL(logger, prisma, teller, cryptoService) const service: IAccountConnectionProvider = new TellerService( logger, prisma, teller, tellerETL, cryptoService, 'TELLER_WEBHOOK_URL', true ) afterAll(async () => { await prisma.$disconnect() }) describe('Teller', () => { let user: User beforeEach(async () => { jest.clearAllMocks() user = await resetUser(prisma) }) it('syncs connection', async () => { const tellerConnection = TellerGenerator.generateConnection() const tellerAccounts = tellerConnection.accountsWithBalances const tellerTransactions = tellerConnection.transactions teller.getAccounts.mockResolvedValue(tellerAccounts) teller.getTransactions.mockImplementation(async ({ accountId }) => { return Promise.resolve(tellerTransactions.filter((t) => t.account_id === accountId)) }) const connection = await prisma.accountConnection.create({ data: { userId: user.id, name: 'TEST_TELLER', type: 'teller', tellerEnrollmentId: tellerConnection.enrollment.enrollment.id, tellerInstitutionId: tellerConnection.enrollment.institutionId, tellerAccessToken: cryptoService.encrypt(tellerConnection.enrollment.accessToken), }, }) await service.sync(connection) const { accounts } = await prisma.accountConnection.findUniqueOrThrow({ where: { id: connection.id, }, include: { accounts: { include: { transactions: true, investmentTransactions: true, holdings: true, valuations: true, }, }, }, }) // all accounts expect(accounts).toHaveLength(tellerConnection.accounts.length) for (const account of accounts) { expect(account.transactions).toHaveLength( tellerTransactions.filter((t) => t.account_id === account.tellerAccountId).length ) } // credit accounts const creditAccounts = tellerAccounts.filter((a) => a.type === 'credit') expect(accounts.filter((a) => a.type === 'CREDIT')).toHaveLength(creditAccounts.length) for (const creditAccount of creditAccounts) { const account = accounts.find((a) => a.tellerAccountId === creditAccount.id)! expect(account.transactions).toHaveLength( tellerTransactions.filter((t) => t.account_id === account.tellerAccountId).length ) expect(account.holdings).toHaveLength(0) expect(account.valuations).toHaveLength(0) expect(account.investmentTransactions).toHaveLength(0) } // depository accounts const depositoryAccounts = tellerAccounts.filter((a) => a.type === 'depository') expect(accounts.filter((a) => a.type === 'DEPOSITORY')).toHaveLength( depositoryAccounts.length ) for (const depositoryAccount of depositoryAccounts) { const account = accounts.find((a) => a.tellerAccountId === depositoryAccount.id)! expect(account.transactions).toHaveLength( tellerTransactions.filter((t) => t.account_id === account.tellerAccountId).length ) expect(account.holdings).toHaveLength(0) expect(account.valuations).toHaveLength(0) expect(account.investmentTransactions).toHaveLength(0) } }) }) ================================================ FILE: apps/workers/src/app/lib/di.ts ================================================ import type { IAccountConnectionProcessor, IAccountProcessor, IAccountQueryService, IAccountService, ISecurityPricingProcessor, IInstitutionService, IUserProcessor, ISecurityPricingService, IUserService, IEmailProcessor, } from '@maybe-finance/server/features' import { AccountConnectionProcessor, AccountConnectionProviderFactory, AccountConnectionService, AccountProcessor, AccountProviderFactory, AccountQueryService, AccountService, BalanceSyncStrategyFactory, InstitutionProviderFactory, InstitutionService, InvestmentTransactionBalanceSyncStrategy, LoanBalanceSyncStrategy, TellerETL, TellerService, SecurityPricingProcessor, SecurityPricingService, TransactionBalanceSyncStrategy, UserProcessor, UserService, ValuationBalanceSyncStrategy, EmailService, EmailProcessor, TransactionService, } from '@maybe-finance/server/features' import type { IMarketDataService } from '@maybe-finance/server/shared' import { BullQueueFactory, CacheService, CryptoService, InMemoryQueueFactory, PgService, PolygonMarketDataService, QueueService, RedisCacheBackend, ServerUtil, } from '@maybe-finance/server/shared' import Redis from 'ioredis' import logger from './logger' import prisma from './prisma' import teller from './teller' import { initializeEmailClient } from './email' import stripe from './stripe' import env from '../../env' import { BullQueueEventHandler, WorkerErrorHandlerService } from '../services' // shared services const redis = new Redis(env.NX_REDIS_URL, { retryStrategy: ServerUtil.redisRetryStrategy({ maxAttempts: 5 }), }) export const cryptoService = new CryptoService(env.NX_DATABASE_SECRET) export const pgService = new PgService(logger.child({ service: 'PgService' }), env.NX_DATABASE_URL) export const queueService = new QueueService( logger.child({ service: 'QueueService' }), process.env.NODE_ENV === 'test' ? new InMemoryQueueFactory() : new BullQueueFactory( logger.child({ service: 'BullQueueFactory' }), env.NX_REDIS_URL, new BullQueueEventHandler(logger.child({ service: 'BullQueueEventHandler' }), prisma) ) ) const cacheService = new CacheService( logger.child({ service: 'CacheService' }), new RedisCacheBackend(redis) ) export const marketDataService: IMarketDataService = new PolygonMarketDataService( logger.child({ service: 'PolygonMarketDataService' }), env.NX_POLYGON_API_KEY, cacheService ) export const securityPricingService: ISecurityPricingService = new SecurityPricingService( logger.child({ service: 'SecurityPricingService' }), prisma, marketDataService ) // providers const tellerService = new TellerService( logger.child({ service: 'TellerService' }), prisma, teller, new TellerETL(logger.child({ service: 'TellerETL' }), prisma, teller, cryptoService), cryptoService, '', env.NX_TELLER_ENV === 'sandbox' ) // account-connection const accountConnectionProviderFactory = new AccountConnectionProviderFactory({ teller: tellerService, }) const transactionStrategy = new TransactionBalanceSyncStrategy( logger.child({ service: 'TransactionBalanceSyncStrategy' }), prisma ) const investmentTransactionStrategy = new InvestmentTransactionBalanceSyncStrategy( logger.child({ service: 'InvestmentTransactionBalanceSyncStrategy' }), prisma ) const valuationStrategy = new ValuationBalanceSyncStrategy( logger.child({ service: 'ValuationBalanceSyncStrategy' }), prisma ) const loanStrategy = new LoanBalanceSyncStrategy( logger.child({ service: 'LoanBalanceSyncStrategy' }), prisma ) const balanceSyncStrategyFactory = new BalanceSyncStrategyFactory({ INVESTMENT: investmentTransactionStrategy, DEPOSITORY: transactionStrategy, CREDIT: transactionStrategy, LOAN: loanStrategy, PROPERTY: valuationStrategy, VEHICLE: valuationStrategy, OTHER_ASSET: valuationStrategy, OTHER_LIABILITY: valuationStrategy, }) export const accountConnectionService = new AccountConnectionService( logger.child({ service: 'AccountConnectionService' }), prisma, accountConnectionProviderFactory, balanceSyncStrategyFactory, securityPricingService, queueService.getQueue('sync-account-connection') ) const transactionService = new TransactionService( logger.child({ service: 'TransactionService' }), prisma ) export const accountConnectionProcessor: IAccountConnectionProcessor = new AccountConnectionProcessor( logger.child({ service: 'AccountConnectionProcessor' }), accountConnectionService, transactionService, accountConnectionProviderFactory ) // account export const accountQueryService: IAccountQueryService = new AccountQueryService( logger.child({ service: 'AccountQueryService' }), pgService ) export const accountService: IAccountService = new AccountService( logger.child({ service: 'AccountService' }), prisma, accountQueryService, queueService.getQueue('sync-account'), queueService.getQueue('sync-account-connection'), balanceSyncStrategyFactory ) const accountProviderFactory = new AccountProviderFactory({ // Since these are not in use yet, just commenting out for now // property: propertyService, // vehicle: vehicleService, }) export const accountProcessor: IAccountProcessor = new AccountProcessor( logger.child({ service: 'AccountProcessor' }), accountService, accountProviderFactory ) // user export const userService: IUserService = new UserService( logger.child({ service: 'UserService' }), prisma, accountQueryService, balanceSyncStrategyFactory, queueService.getQueue('sync-user'), queueService.getQueue('purge-user'), stripe ) export const userProcessor: IUserProcessor = new UserProcessor( logger.child({ service: 'UserProcessor' }), prisma, userService, accountService, accountConnectionService, accountConnectionProviderFactory ) // security-pricing export const securityPricingProcessor: ISecurityPricingProcessor = new SecurityPricingProcessor( logger.child({ service: 'SecurityPricingProcessor' }), securityPricingService ) // institution const institutionProviderFactory = new InstitutionProviderFactory({ TELLER: tellerService, }) export const institutionService: IInstitutionService = new InstitutionService( logger.child({ service: 'InstitutionService' }), prisma, pgService, institutionProviderFactory ) // worker services export const workerErrorHandlerService = new WorkerErrorHandlerService( logger.child({ service: 'WorkerErrorHandlerService' }) ) // send-email export const emailService: EmailService = new EmailService( logger.child({ service: 'EmailService' }), initializeEmailClient(), { from: env.NX_EMAIL_FROM_ADDRESS, replyTo: env.NX_EMAIL_REPLY_TO_ADDRESS, } ) export const emailProcessor: IEmailProcessor = new EmailProcessor( logger.child({ service: 'EmailProcessor' }), prisma, emailService ) ================================================ FILE: apps/workers/src/app/lib/email.ts ================================================ import { ServerClient as PostmarkServerClient } from 'postmark' import nodemailer from 'nodemailer' import type SMTPTransport from 'nodemailer/lib/smtp-transport' import env from '../../env' export function initializeEmailClient() { switch (env.NX_EMAIL_PROVIDER) { case 'postmark': if (env.NX_EMAIL_PROVIDER_API_TOKEN) { return new PostmarkServerClient(env.NX_EMAIL_PROVIDER_API_TOKEN) } else { return undefined } case 'smtp': if ( !process.env.NX_EMAIL_SMTP_HOST || !process.env.NX_EMAIL_SMTP_PORT || !process.env.NX_EMAIL_SMTP_USERNAME || !process.env.NX_EMAIL_SMTP_PASSWORD ) { return undefined } else { const transportOptions: SMTPTransport.Options = { host: process.env.NX_EMAIL_SMTP_HOST, port: Number(process.env.NX_EMAIL_SMTP_PORT), secure: process.env.NX_EMAIL_SMTP_SECURE === 'true', auth: { user: process.env.NX_EMAIL_SMTP_USERNAME, pass: process.env.NX_EMAIL_SMTP_PASSWORD, }, } return nodemailer.createTransport(transportOptions) } default: return undefined } } ================================================ FILE: apps/workers/src/app/lib/logger.ts ================================================ import { createLogger } from '@maybe-finance/server/shared' const logger = createLogger({ level: 'info', }) export default logger ================================================ FILE: apps/workers/src/app/lib/prisma.ts ================================================ import { PrismaClient } from '@prisma/client' import { DbUtil } from '@maybe-finance/server/shared' import globalLogger from './logger' const logger = globalLogger.child({ service: 'PrismaClient' }) // https://stackoverflow.com/a/68328402 declare global { var prisma: PrismaClient | undefined // eslint-disable-line } function createPrismaClient() { const prisma = new PrismaClient({ log: [ { emit: 'event', level: 'query' }, { emit: 'event', level: 'info' }, { emit: 'event', level: 'warn' }, { emit: 'event', level: 'error' }, ], }) prisma.$on('query', ({ query, params, duration, ...data }) => { logger.silly(`Query: ${query}, Params: ${params}, Duration: ${duration}`, { ...data }) }) prisma.$on('info', ({ message, ...data }) => { logger.info(message, { ...data }) }) prisma.$on('warn', ({ message, ...data }) => { logger.warn(message, { ...data }) }) prisma.$on('error', ({ message, ...data }) => { logger.error(message, { ...data }) }) prisma.$use(DbUtil.slowQueryMiddleware(logger)) return prisma } // Prevent multiple instances of Prisma Client in development // https://www.prisma.io/docs/guides/performance-and-optimization/connection-management#prevent-hot-reloading-from-creating-new-instances-of-prismaclient // https://www.prisma.io/docs/concepts/components/prisma-client/working-with-prismaclient/instantiate-prisma-client#the-number-of-prismaclient-instances-matters const prisma = global.prisma || createPrismaClient() if (process.env.NODE_ENV === 'development') global.prisma = prisma export default prisma ================================================ FILE: apps/workers/src/app/lib/stripe.ts ================================================ import Stripe from 'stripe' import env from '../../env' const stripe = new Stripe(env.NX_STRIPE_SECRET_KEY, { apiVersion: '2022-08-01' }) export default stripe ================================================ FILE: apps/workers/src/app/lib/teller.ts ================================================ import { TellerApi } from '@maybe-finance/teller-api' const teller = new TellerApi() export default teller ================================================ FILE: apps/workers/src/app/services/bull-queue-event-handler.ts ================================================ import type { PrismaClient, User } from '@prisma/client' import type { Job } from 'bull' import type { Logger } from 'winston' import type { BullQueue, IBullQueueEventHandler } from '@maybe-finance/server/shared' import * as Sentry from '@sentry/node' import { ErrorUtil } from '@maybe-finance/server/shared' const printJob = (job: Job) => `Job{queue=${job.queue.name} id=${job.id} name=${job.name} ts=${ job.timestamp } data=${JSON.stringify(job.data)}}` export class BullQueueEventHandler implements IBullQueueEventHandler { constructor(private readonly logger: Logger, private readonly prisma: PrismaClient) {} onQueueCreated({ queue }: BullQueue) { // https://github.com/OptimalBits/bull/blob/develop/REFERENCE.md#events queue.on('active', (job, _jobPromise) => { this.logger.info(`[job.active] ${printJob(job)}`) }) queue.on('completed', (job, _result) => { this.logger.info(`[job.completed] ${printJob(job)}`) }) queue.on('stalled', async (job) => { this.logger.warn(`[job.stalled] ${printJob(job)}`) }) queue.on('lock-extension-failed', (job, err) => { this.logger.warn(`[job.lock-extension-failed] ${printJob(job)}`, { err }) }) queue.on('progress', (job, progress) => { this.logger.info(`[job.progress] ${printJob(job)}`, { progress }) }) queue.on('failed', async (job, error) => { this.logger.error(`[job.failed] ${printJob(job)}`, { error }) const user = await this.getUserFromJob(job) Sentry.withScope((scope) => { scope.setUser(user ? {} : null) scope.setTags({ 'queue.name': job.queue.name, 'job.name': job.name, }) scope.setContext('Job Info', { queue: job.queue.name, job: job.name, attempts: job.attemptsMade, data: job.data, }) const err = ErrorUtil.parseError(error) Sentry.captureException(error, { level: 'error', tags: err.sentryTags, contexts: err.sentryContexts, }) }) }) queue.on('error', async (error) => { this.logger.error(`[queue.error]`, { error }) const err = ErrorUtil.parseError(error) Sentry.captureException(error, { level: 'error', tags: err.sentryTags, contexts: { ...err.sentryContexts, queue: { name: queue.name }, }, }) }) } private async getUserFromJob(job: Job) { let user: Pick | undefined try { if (job.queue.name === 'sync-account' && 'accountId' in job.data) { const account = await this.prisma.account.findUniqueOrThrow({ where: { id: job.data.accountId }, include: { accountConnection: { include: { user: true } }, user: true, }, }) user = account.user ?? account.accountConnection?.user } if (job.queue.name === 'sync-account-connection' && 'accountConnectionId' in job.data) { const accountConnection = await this.prisma.accountConnection.findUniqueOrThrow({ where: { id: job.data.accountConnectionId }, include: { user: true, }, }) user = accountConnection.user } return user } catch (err) { // Gracefully return if no user identified successfully return null } } } ================================================ FILE: apps/workers/src/app/services/index.ts ================================================ export * from './worker-error.service' export * from './bull-queue-event-handler' ================================================ FILE: apps/workers/src/app/services/worker-error.service.ts ================================================ import type { Logger } from 'winston' import * as Sentry from '@sentry/node' import { ErrorUtil } from '@maybe-finance/server/shared' type WorkerErrorContext = { variant: 'unhandled'; error: unknown } export class WorkerErrorHandlerService { constructor(private readonly logger: Logger) {} async handleWorkersError(ctx: WorkerErrorContext) { const err = ErrorUtil.parseError(ctx.error) switch (ctx.variant) { case 'unhandled': this.logger.error(`[workers-unhandled] ${err.message}`, { error: err.metadata }) Sentry.captureException(ctx.error, { level: 'error', tags: err.sentryTags, contexts: err.sentryContexts, }) break default: return } } } ================================================ FILE: apps/workers/src/assets/.gitkeep ================================================ ================================================ FILE: apps/workers/src/env.ts ================================================ import { z } from 'zod' const envSchema = z.object({ NX_PORT: z.string().default('3334'), NX_DATABASE_URL: z.string(), NX_DATABASE_SECRET: z.string(), NX_TELLER_SIGNING_SECRET: z.string().default('REPLACE_THIS'), NX_TELLER_APP_ID: z.string().default('REPLACE_THIS'), NX_TELLER_ENV: z.string().default('sandbox'), NX_SENTRY_DSN: z.string().optional(), NX_SENTRY_ENV: z.string().optional(), NX_REDIS_URL: z.string().default('redis://localhost:6379'), NX_POLYGON_API_KEY: z.string().default(''), NX_POLYGON_TIER: z.string().default('basic'), NX_EMAIL_FROM_ADDRESS: z.string().default('account@maybe.co'), NX_EMAIL_REPLY_TO_ADDRESS: z.string().default('support@maybe.co'), NX_EMAIL_PROVIDER: z.string().optional(), NX_EMAIL_PROVIDER_API_TOKEN: z.string().optional(), NX_STRIPE_SECRET_KEY: z.string().default('sk_test_REPLACE_THIS'), NX_CDN_PRIVATE_BUCKET: z.string().default('REPLACE_THIS'), NX_CDN_PUBLIC_BUCKET: z.string().default('REPLACE_THIS'), STRIPE_API_KEY: z.string().optional(), }) const env = envSchema.parse(process.env) export default env ================================================ FILE: apps/workers/src/environments/environment.prod.ts ================================================ export const environment = { production: true, } ================================================ FILE: apps/workers/src/environments/environment.ts ================================================ export const environment = { production: false, } ================================================ FILE: apps/workers/src/main.ts ================================================ import express from 'express' import cors from 'cors' import * as Sentry from '@sentry/node' import * as SentryTracing from '@sentry/tracing' import { BullQueue } from '@maybe-finance/server/shared' import logger from './app/lib/logger' import prisma from './app/lib/prisma' import { accountConnectionProcessor, accountProcessor, institutionService, queueService, securityPricingProcessor, userProcessor, emailProcessor, workerErrorHandlerService, } from './app/lib/di' import env from './env' import { cleanUpOutdatedJobs } from './utils' // Defaults from quickstart - https://docs.sentry.io/platforms/node/ Sentry.init({ dsn: env.NX_SENTRY_DSN, environment: env.NX_SENTRY_ENV, maxValueLength: 8196, integrations: [ new Sentry.Integrations.Http({ tracing: true }), new SentryTracing.Integrations.Postgres(), new SentryTracing.Integrations.Prisma({ client: prisma }), ], tracesSampleRate: 1.0, }) const syncUserQueue = queueService.getQueue('sync-user') const syncConnectionQueue = queueService.getQueue('sync-account-connection') const syncAccountQueue = queueService.getQueue('sync-account') const syncSecurityQueue = queueService.getQueue('sync-security') const purgeUserQueue = queueService.getQueue('purge-user') const syncInstitutionQueue = queueService.getQueue('sync-institution') const sendEmailQueue = queueService.getQueue('send-email') syncUserQueue.process( 'sync-user', async (job) => { await userProcessor.sync(job.data) }, { concurrency: 4 } ) syncAccountQueue.process( 'sync-account', async (job) => { await accountProcessor.sync(job.data) }, { concurrency: 4 } ) /** * sync-account-connection queue */ syncConnectionQueue.process( 'sync-connection', async (job) => { await accountConnectionProcessor.sync(job.data, async (progress) => { try { await job.progress(progress) } catch (e) { logger.warn('Failed to update SYNC_CONNECTION job progress', job.data) } }) }, { concurrency: 4 } ) /** * sync-security queue */ syncSecurityQueue.process( 'sync-all-securities', async () => await securityPricingProcessor.syncAll() ) /** * sync-us-stock-ticker queue */ syncSecurityQueue.process( 'sync-us-stock-tickers', async () => await securityPricingProcessor.syncUSStockTickers() ) /** * purge-user queue */ purgeUserQueue.process( 'purge-user', async (job) => { await userProcessor.delete(job.data) }, { concurrency: 4 } ) /** * sync-all-securities queue */ // If no securities exist, sync them immediately // Otherwise, schedule the job to run every 24 hours // Use same jobID to prevent duplicates and rate limiting syncSecurityQueue.cancelJobs().then(() => { if (!env.NX_POLYGON_API_KEY) { logger.warn('No Polygon API key found, skipping adding jobs to queue') return } prisma.security .count({ where: { providerName: 'polygon', }, }) .then((count) => { // If no securities exist, sync them immediately except in development // In development, sync manually to avoid hot reloads causing rate issues if (count === 0 && process.env.NODE_ENV !== 'development') { syncSecurityQueue.add( 'sync-us-stock-tickers', {}, { delay: 15_000, removeOnFail: true, } ) } else { syncSecurityQueue.add( 'sync-us-stock-tickers', {}, { repeat: { cron: '0 */24 * * *' }, // Run every 24 hours jobId: Date.now().toString(), } ) } // Do not run if on the free tier (rate limits) if (env.NX_POLYGON_TIER !== 'basic') { syncSecurityQueue.add( 'sync-all-securities', {}, { repeat: { cron: '*/5 * * * *' }, // Run every 5 minutes jobId: Date.now().toString(), } ) } else if (env.NX_POLYGON_TIER === 'basic') { syncSecurityQueue.add( 'sync-all-securities', {}, { repeat: { cron: '* 3 * * *' }, // Run at 3am to avoid rate limits jobId: Date.now().toString(), } ) } }) }) /** * sync-institution queue */ syncInstitutionQueue.process( 'sync-teller-institutions', async () => await institutionService.sync('TELLER') ) syncInstitutionQueue.add( 'sync-teller-institutions', {}, { repeat: { cron: '0 */24 * * *' }, // Run every 24 hours jobId: Date.now().toString(), } ) /** * send-email queue */ sendEmailQueue.process('send-email', async (job) => await emailProcessor.send(job.data)) if (env.STRIPE_API_KEY) { sendEmailQueue.add( 'send-email', { type: 'trial-reminders' }, { repeat: { cron: '0 */12 * * *' } } // Run every 12 hours ) } // Fallback - usually triggered by errors not handled (or thrown) within the Bull event handlers (see above) process.on( 'uncaughtException', async (error) => await workerErrorHandlerService.handleWorkersError({ variant: 'unhandled', error }) ) // Fallback - usually triggered by errors not handled (or thrown) within the Bull event handlers (see above) process.on( 'unhandledRejection', async (error) => await workerErrorHandlerService.handleWorkersError({ variant: 'unhandled', error }) ) // Replace any jobs that have changed cron schedules and ensures only // one repeatable jobs for each type is running const queues = [syncSecurityQueue, syncInstitutionQueue] cleanUpOutdatedJobs(queues) const app = express() app.use(cors()) // Make sure that at least 1 of the queues is ready and Redis is connected properly app.get('/health', (_req, res, _next) => { syncConnectionQueue .isHealthy() .then((isHealthy) => { if (isHealthy) { res.status(200).json({ success: true, message: 'Queue is healthy' }) } else { res.status(500).json({ success: false, message: 'Queue is not healthy' }) } }) .catch((err) => { console.log(err) res.status(500).json({ success: false, message: 'Queue health check failed' }) }) }) const server = app.listen(env.NX_PORT, () => { logger.info(`Worker health server started on port ${env.NX_PORT}`) }) async function onShutdown() { logger.info('[shutdown.start]') await new Promise((resolve) => server.close(resolve)) // shutdown queues try { await Promise.allSettled( queueService.allQueues .filter((q): q is BullQueue => q instanceof BullQueue) .map((q) => q.queue.close()) ) } catch (error) { logger.error('[shutdown.error]', error) } finally { logger.info('[shutdown.complete]') process.exitCode = 0 } } process.on('SIGINT', onShutdown) process.on('SIGTERM', onShutdown) process.on('exit', (code) => logger.info(`[exit] code=${code}`)) logger.info(`🚀 worker started`) ================================================ FILE: apps/workers/src/utils.ts ================================================ import type { IQueue } from '@maybe-finance/server/shared' import type { JobInformation } from 'bull' export async function cleanUpOutdatedJobs(queues: IQueue[]) { for (const queue of queues) { const repeatedJobs = await queue.getRepeatableJobs() const outdatedJobs = filterOutdatedJobs(repeatedJobs) for (const job of outdatedJobs) { await queue.removeRepeatableByKey(job.key) } } } function filterOutdatedJobs(jobs: JobInformation[]) { const jobGroups = new Map() jobs.forEach((job) => { if (!jobGroups.has(job.name)) { jobGroups.set(job.name, []) } jobGroups.get(job.name).push(job) }) const mostRecentJobs = new Map() jobGroups.forEach((group, name) => { const mostRecentJob = group.reduce((mostRecent, current) => { if (current.id === null) return mostRecent const currentIdTime = current.id const mostRecentIdTime = mostRecent ? mostRecent.id : 0 return currentIdTime > mostRecentIdTime ? current : mostRecent }, null) if (mostRecentJob) { mostRecentJobs.set(name, mostRecentJob.id) } }) return jobs.filter((job: JobInformation) => { const mostRecentId = mostRecentJobs.get(job.name) return job.id === null || job.id !== mostRecentId }) } ================================================ FILE: apps/workers/tsconfig.app.json ================================================ { "extends": "./tsconfig.json", "compilerOptions": { "outDir": "../../dist/out-tsc", "module": "commonjs", "types": ["node"] }, "exclude": ["**/*.spec.ts", "**/*.test.ts", "**/*.test-helper.ts", "jest.config.ts"], "include": ["**/*.ts", "../../custom-express.d.ts"] } ================================================ FILE: apps/workers/tsconfig.json ================================================ { "extends": "../../tsconfig.base.json", "compilerOptions": { "esModuleInterop": true, "noImplicitAny": false, "strict": true, "strictNullChecks": true }, "files": [], "include": [], "references": [ { "path": "./tsconfig.app.json" }, { "path": "./tsconfig.spec.json" } ] } ================================================ FILE: apps/workers/tsconfig.spec.json ================================================ { "extends": "./tsconfig.json", "compilerOptions": { "outDir": "../../dist/out-tsc", "module": "commonjs", "types": ["jest", "node"] }, "include": [ "**/*.spec.ts", "**/*.test.ts", "**/*.d.ts", "**/*.test-helper.ts", "jest.config.ts" ] } ================================================ FILE: babel.config.json ================================================ { "babelrcRoots": ["*"] } ================================================ FILE: custom-express.d.ts ================================================ import express, { Send, Response, Request } from 'express' import { SharedType } from '@maybe-finance/shared' // Because this is a module, need to escape from module scope and enter global scope so declaration merging works correctly declare global { namespace Express { interface Request { // Add custom properties here (i.e. if props are defined with middleware) user?: User & SharedType.MaybeCustomClaims } interface Response { json(data: any): Send superjson(data: any): Send } } } ================================================ FILE: docker-compose.test.yml ================================================ --- version: '3.9' services: server: env_file: .env container_name: maybe-server profiles: [maybe] image: ghcr.io/maybe/maybe:main ports: - 3333 environment: NEXTAUTH_URL: &canonical https://maybe.example.com NX_NEXTAUTH_URL: *canonical NX_CLIENT_URL: *canonical NX_CLIENT_URL_CUSTOM: *canonical NEXT_PUBLIC_API_URL: &next_public_api_url https://maybe-server.example.com NX_API_URL: &nx_api_url https://maybe-server.example.com NX_REDIS_URL: &nx_redis_url redis://redis:6379 NODE_ENV: production client: env_file: .env container_name: maybe-client profiles: [maybe] image: ghcr.io/maybe/maybe-client:main ports: - 4200 environment: NEXTAUTH_URL: *canonical NX_NEXTAUTH_URL: *canonical NX_CLIENT_URL: *canonical NX_CLIENT_URL_CUSTOM: *canonical NEXT_PUBLIC_API_URL: *next_public_api_url NX_API_URL: *nx_api_url NX_REDIS_URL: *nx_redis_url NODE_ENV: production worker: env_file: .env container_name: maybe-worker profiles: [maybe] image: ghcr.io/maybe/maybe-worker:main ports: - 3334 environment: NEXTAUTH_URL: *canonical NX_NEXTAUTH_URL: *canonical NX_CLIENT_URL: *canonical NX_CLIENT_URL_CUSTOM: *canonical NEXT_PUBLIC_API_URL: *next_public_api_url NX_API_URL: *nx_api_url NX_REDIS_URL: *nx_redis_url NODE_ENV: production ================================================ FILE: docker-compose.yml ================================================ --- version: '3.9' services: postgres: container_name: postgres profiles: [services] image: timescale/timescaledb:latest-pg14 ports: - 5433:5432 environment: POSTGRES_USER: maybe POSTGRES_PASSWORD: maybe POSTGRES_DB: maybe_local volumes: - postgres_data:/var/lib/postgresql/data redis: container_name: redis profiles: [services] image: redis:6.2-alpine ports: - 6379:6379 command: 'redis-server --bind 0.0.0.0' ngrok: env_file: .env image: shkoliar/ngrok:latest profiles: [ngrok] container_name: ngrok ports: - 4551:4551 environment: - DOMAIN=${NGROK_DOMAIN:-host.docker.internal} - PORT=3333 - AUTH_TOKEN=${NGROK_AUTH_TOKEN} - DEBUG=true stripe: container_name: stripe image: stripe/stripe-cli:latest profiles: [stripe] command: listen --forward-to host.docker.internal:3333/v1/stripe/webhook --log-level warn extra_hosts: - 'host.docker.internal:host-gateway' environment: - STRIPE_API_KEY=${STRIPE_SECRET_KEY} tty: true volumes: postgres_data: ================================================ FILE: jest.config.ts ================================================ const { getJestProjects } = require('@nrwl/jest') export default { projects: getJestProjects(), } ================================================ FILE: jest.preset.js ================================================ const nxPreset = require('@nrwl/jest/preset').default module.exports = { ...nxPreset } ================================================ FILE: libs/.gitkeep ================================================ ================================================ FILE: libs/client/features/.babelrc ================================================ { "presets": [ [ "@nrwl/react/babel", { "runtime": "automatic", "useBuiltIns": "usage" } ] ], "plugins": [] } ================================================ FILE: libs/client/features/.eslintrc.json ================================================ { "extends": ["plugin:@nrwl/nx/react", "../../../.eslintrc.json"], "ignorePatterns": ["!**/*"], "overrides": [ { "files": ["*.ts", "*.tsx", "*.js", "*.jsx"], "rules": {} }, { "files": ["*.ts", "*.tsx"], "rules": {} }, { "files": ["*.js", "*.jsx"], "rules": {} } ] } ================================================ FILE: libs/client/features/jest.config.ts ================================================ /* eslint-disable */ export default { displayName: 'client-features', preset: '../../../jest.preset.js', transform: { '^.+\\.[tj]sx?$': ['babel-jest', { presets: ['@nrwl/react/babel'] }], }, moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'], coverageDirectory: '../../../coverage/libs/client/features', } ================================================ FILE: libs/client/features/src/account/AccountMenu.tsx ================================================ import type { SharedType } from '@maybe-finance/shared' import { useAccountContext } from '@maybe-finance/client/shared' import { Menu } from '@maybe-finance/design-system' import { RiDeleteBin5Line, RiPencilLine } from 'react-icons/ri' import { useRouter } from 'next/router' type Props = { account?: SharedType.AccountDetail } export function AccountMenu({ account }: Props) { const { editAccount, deleteAccount } = useAccountContext() const router = useRouter() if (!account) return null return ( } onClick={() => editAccount(account)}> Edit {!account.accountConnectionId && ( } destructive onClick={() => deleteAccount(account, () => router.push('/'))} > Delete )} ) } ================================================ FILE: libs/client/features/src/account/AccountsSidebar.tsx ================================================ import type { AccordionRowProps } from '@maybe-finance/design-system' import type { SharedType } from '@maybe-finance/shared' import { useCallback, useMemo } from 'react' import { RiAlertLine, RiCloseFill, RiInformationLine as InfoIcon, RiInformationLine, } from 'react-icons/ri' import { AnimatePresence, motion } from 'framer-motion' import { AccordionRow, LoadingPlaceholder, TrendLine } from '@maybe-finance/design-system' import classNames from 'classnames' import type DecimalJS from 'decimal.js' import { AiOutlineExclamationCircle } from 'react-icons/ai' import { useAccountApi, useQueryParam, useUserAccountContext, useProviderStatus, useAccountContext, useLocalStorage, } from '@maybe-finance/client/shared' import { NumberUtil } from '@maybe-finance/shared' function SidebarAccountsLoader() { return (
{Array(6) .fill(0) .map((_, idx) => { return (
) })}
) } export default function AccountsSidebar() { const { useAccountRollup } = useAccountApi() const activeAccountId = useQueryParam('accountId', 'number') const providerStatus = useProviderStatus() const { someConnectionsSyncing, someAccountsSyncing, connectionsSyncing, syncProgress } = useUserAccountContext() const { dateRange } = useAccountContext() const connectionsStatus = useMemo( () => ({ syncing: someAccountsSyncing || someConnectionsSyncing, pending: connectionsSyncing.filter((connection) => connection.syncStatus === 'PENDING') .length > 0, }), [someAccountsSyncing, someConnectionsSyncing, connectionsSyncing] ) const { error, data } = useAccountRollup(dateRange) const isLoading = useMemo(() => { if (error) { return false } if (!connectionsStatus.syncing && data) { return false } // If any connection is syncing and there are > 1 accounts, show the accounts if (connectionsStatus.syncing && data && data.length > 0) { return false } return true }, [data, error, connectionsStatus]) const [toggleState, setToggleState] = useLocalStorage<{ [key: string]: boolean }>( 'ACCOUNTS_LIST_TOGGLE_STATE', {} ) const updateToggleState = useCallback( (key: string, isExpanded: boolean) => { setToggleState({ ...toggleState, [key]: isExpanded, }) }, [toggleState, setToggleState] ) if (error) { return (

Unable to load accounts

) } if (!isLoading && (!data || !data.length)) { return (

No accounts found

) } return (
{syncProgress && ( {syncProgress.description}...
{syncProgress.progress ? ( ) : ( )}
)}
{providerStatus.statusMessage && (
{providerStatus.isCollapsed ? ( <>

Data provider service disruption

providerStatus.expand()}> ) : ( <>

{providerStatus.statusMessage}

providerStatus.dismiss()}> )}
)} {isLoading || !data ? ( ) : ( data.map(({ key: classification, title, balances, items }) => ( updateToggleState(title, isExpanded)} expanded={toggleState[title] !== false} syncing={items.some(({ items }) => items.some((a) => a.syncing))} > {items.map(({ key: category, title, balances, items }) => ( updateToggleState(`${title}-${classification}`, isExpanded) } expanded={toggleState[title] !== false} level={1} syncing={items.some((a) => a.syncing)} > {items.map(({ id, name, mask, connection, balances, syncing }) => ( ))} ))} )) )}
) } function AccountsSidebarRow({ label, level = 0, balances, institutionName, accountMask, inverted = false, syncing = false, active = false, url, ...rest }: AccordionRowProps & { label: string balances: { date: string; balance: SharedType.Decimal }[] institutionName?: string | null accountMask?: string | null inverted?: boolean syncing?: boolean active?: boolean url?: string }) { const startBalance = balances[0].balance const endBalance = balances[balances.length - 1].balance const percentChange = NumberUtil.calculatePercentChange(startBalance, endBalance) let isPositive = balances.length > 1 && (endBalance as DecimalJS).gt(startBalance as DecimalJS) if (inverted) isPositive = !isPositive const overlayClassName = ['!bg-gray-400', '!bg-gray-600', '!bg-gray-700'][level] // Hide flat lines or inifite const hasValidValue = !percentChange.isZero() && percentChange.isFinite() return (

{label}

{(institutionName || accountMask) && (
{institutionName && ( {institutionName} )} {accountMask && (  ···· {accountMask} )}
)}
{balances.length && (
{syncing ? '$X,XXX,XXX' : NumberUtil.format(endBalance, 'currency', { minimumFractionDigits: 0, maximumFractionDigits: 0, })}
{(balances.length > 1 || syncing) && hasValidValue && (
{!syncing && (
({ key: date, value: balance.toNumber(), }))} />
)} {syncing ? '+XXX%' : NumberUtil.format(percentChange, 'percent')}
)}
)} } /> ) } ================================================ FILE: libs/client/features/src/account/PageTitle.tsx ================================================ import type { SharedType } from '@maybe-finance/shared' import { SmallDecimals, TrendBadge } from '@maybe-finance/client/shared' import { LoadingPlaceholder } from '@maybe-finance/design-system' type Props = { isLoading: boolean title?: string value?: string trend?: SharedType.Trend trendLabel?: string trendNegative?: boolean } export function PageTitle({ isLoading, title, value, trend, trendLabel, trendNegative }: Props) { return (
Placeholder Title} > {title &&

{title}

}
} >

} > {trend && ( )}
) } ================================================ FILE: libs/client/features/src/account/index.ts ================================================ export * from './AccountMenu' export { default as AccountSidebar } from './AccountsSidebar' export * from './PageTitle' ================================================ FILE: libs/client/features/src/accounts-list/Account.tsx ================================================ import type { SharedType } from '@maybe-finance/shared' import cn from 'classnames' import { Button, Menu, Toggle, Tooltip } from '@maybe-finance/design-system' import { useAccountApi, useAccountContext } from '@maybe-finance/client/shared' import { NumberUtil, AccountUtil } from '@maybe-finance/shared' import { DateTime } from 'luxon' import { useCallback, useEffect, useMemo, useState } from 'react' import debounce from 'lodash/debounce' type AccountProps = { account: SharedType.Account readonly?: boolean onEdit?(): void editLabel?: string canDelete?: boolean showAccountDescription?: boolean } export default function Account({ account, readonly = false, onEdit, editLabel = 'Edit', canDelete = false, showAccountDescription = true, }: AccountProps) { const { useSyncAccount, useAccountBalances } = useAccountApi() const { deleteAccount } = useAccountContext() const syncAccount = useSyncAccount() const accountBalancesQuery = useAccountBalances({ id: account.id, start: DateTime.now().toISODate(), end: DateTime.now().toISODate(), }) let accountTypeName = AccountUtil.getAccountTypeName(account.category, account.subcategory) accountTypeName = accountTypeName ? accountTypeName.charAt(0).toUpperCase() + accountTypeName.slice(1) : null const renderAccountDescription = () => { if (!showAccountDescription) return null if (!accountTypeName && !account.mask) return null return (
{accountTypeName ?? 'Account'} {account.mask && <> ending in ···· {account.mask}}
) } return (
  • {account.name}
    {renderAccountDescription()}
    {onEdit && ( )} {canDelete && ( )} {process.env.NODE_ENV === 'development' && ( syncAccount.mutate(account.id)} > Sync )}
    {accountBalancesQuery.data ? ( {NumberUtil.format(accountBalancesQuery.data.today?.balance, 'currency')} ) : ( ... )}
  • ) } function AccountToggle({ account, disabled, }: { account: SharedType.Account disabled: boolean }): JSX.Element { const { useUpdateAccount } = useAccountApi() const { mutateAsync } = useUpdateAccount() const [isActive, setIsActive] = useState(account.isActive) useEffect(() => setIsActive(account.isActive), [account.isActive]) const debouncedMutate = useMemo( () => debounce(async (checked: boolean) => { try { await mutateAsync({ id: account.id, data: { data: { isActive: checked } }, }) } catch (e) { setIsActive(!checked) } }, 500), [mutateAsync, account.id] ) const onChange = useCallback( (checked: boolean) => { setIsActive(checked) debouncedMutate(checked) }, [debouncedMutate] ) return ( ) } ================================================ FILE: libs/client/features/src/accounts-list/AccountDevTools.tsx ================================================ import Link from 'next/link' import { useState } from 'react' import { useAccountConnectionApi, useInstitutionApi, useSecurityApi, useUserApi, } from '@maybe-finance/client/shared' import { Button, Input, Dialog } from '@maybe-finance/design-system' import { type SubmitHandler, useForm } from 'react-hook-form' import { toast } from 'react-hot-toast' export function AccountDevTools() { const [open, setOpen] = useState(false) const { useDeleteAllConnections } = useAccountConnectionApi() const { useSyncInstitutions, useDeduplicateInstitutions } = useInstitutionApi() const { useSyncUSStockTickers, useSyncSecurityPricing } = useSecurityApi() const deleteAllConnections = useDeleteAllConnections() const syncInstitutions = useSyncInstitutions() const deduplicateInstitutions = useDeduplicateInstitutions() const syncUSStockTickers = useSyncUSStockTickers() const syncSecurityPricing = useSyncSecurityPricing() return process.env.NODE_ENV === 'development' ? (
    Dev Tools

    This section along with anything in red text will NOT show in production and are solely for making testing easier.

    Actions:

    BullMQ Dashboard
    setOpen(false)}> Send test email
    ) : null } export default AccountDevTools type TestEmailFormProps = { setOpen: (open: boolean) => void } type EmailFormFields = { recipient: string subject: string body: string } function TestEmailForm({ setOpen }: TestEmailFormProps) { const { register, handleSubmit } = useForm() const { useSendTestEmail, useAuthProfile } = useUserApi() const sendTestEmail = useSendTestEmail() const authUser = useAuthProfile() const onSubmit: SubmitHandler = (data) => { if (authUser.data?.email !== data.recipient) { toast.error('You can only send test emails to yourself.') return } sendTestEmail.mutate(data) setOpen(false) } return (