import: gitroomhq/postiz-app snapshot (AGPL-3.0)
Squashed import of upstream postiz-app at gitroomhq/postiz-app@826d07d. Full upstream history: https://github.com/gitroomhq/postiz-app
@@ -0,0 +1,177 @@
|
||||
language: en-US
|
||||
tone_instructions: ''
|
||||
early_access: false
|
||||
enable_free_tier: true
|
||||
reviews:
|
||||
profile: chill
|
||||
request_changes_workflow: false
|
||||
high_level_summary: true
|
||||
high_level_summary_placeholder: '@coderabbitai summary'
|
||||
high_level_summary_in_walkthrough: false
|
||||
auto_title_placeholder: '@coderabbitai'
|
||||
auto_title_instructions: ''
|
||||
review_status: false
|
||||
commit_status: true
|
||||
fail_commit_status: false
|
||||
collapse_walkthrough: false
|
||||
changed_files_summary: true
|
||||
sequence_diagrams: true
|
||||
estimate_code_review_effort: true
|
||||
assess_linked_issues: true
|
||||
related_issues: true
|
||||
related_prs: true
|
||||
suggested_labels: true
|
||||
auto_apply_labels: false
|
||||
suggested_reviewers: true
|
||||
auto_assign_reviewers: false
|
||||
poem: true
|
||||
labeling_instructions: []
|
||||
path_filters: []
|
||||
path_instructions: []
|
||||
abort_on_close: true
|
||||
disable_cache: false
|
||||
auto_review:
|
||||
enabled: false
|
||||
auto_incremental_review: true
|
||||
ignore_title_keywords: []
|
||||
labels: []
|
||||
drafts: false
|
||||
base_branches: []
|
||||
finishing_touches:
|
||||
docstrings:
|
||||
enabled: true
|
||||
unit_tests:
|
||||
enabled: true
|
||||
pre_merge_checks:
|
||||
docstrings:
|
||||
mode: warning
|
||||
threshold: 80
|
||||
title:
|
||||
mode: warning
|
||||
requirements: ''
|
||||
description:
|
||||
mode: warning
|
||||
issue_assessment:
|
||||
mode: warning
|
||||
tools:
|
||||
ast-grep:
|
||||
rule_dirs: []
|
||||
util_dirs: []
|
||||
essential_rules: true
|
||||
packages: []
|
||||
shellcheck:
|
||||
enabled: true
|
||||
ruff:
|
||||
enabled: true
|
||||
markdownlint:
|
||||
enabled: true
|
||||
github-checks:
|
||||
enabled: true
|
||||
timeout_ms: 90000
|
||||
languagetool:
|
||||
enabled: true
|
||||
enabled_rules: []
|
||||
disabled_rules: []
|
||||
enabled_categories: []
|
||||
disabled_categories: []
|
||||
enabled_only: false
|
||||
level: default
|
||||
biome:
|
||||
enabled: true
|
||||
hadolint:
|
||||
enabled: true
|
||||
swiftlint:
|
||||
enabled: true
|
||||
phpstan:
|
||||
enabled: true
|
||||
level: default
|
||||
phpmd:
|
||||
enabled: true
|
||||
phpcs:
|
||||
enabled: true
|
||||
golangci-lint:
|
||||
enabled: true
|
||||
yamllint:
|
||||
enabled: true
|
||||
gitleaks:
|
||||
enabled: true
|
||||
checkov:
|
||||
enabled: true
|
||||
detekt:
|
||||
enabled: true
|
||||
eslint:
|
||||
enabled: true
|
||||
flake8:
|
||||
enabled: true
|
||||
rubocop:
|
||||
enabled: true
|
||||
buf:
|
||||
enabled: true
|
||||
regal:
|
||||
enabled: true
|
||||
actionlint:
|
||||
enabled: true
|
||||
pmd:
|
||||
enabled: true
|
||||
cppcheck:
|
||||
enabled: true
|
||||
semgrep:
|
||||
enabled: true
|
||||
circleci:
|
||||
enabled: true
|
||||
clippy:
|
||||
enabled: true
|
||||
sqlfluff:
|
||||
enabled: true
|
||||
prismaLint:
|
||||
enabled: true
|
||||
pylint:
|
||||
enabled: true
|
||||
oxc:
|
||||
enabled: true
|
||||
shopifyThemeCheck:
|
||||
enabled: true
|
||||
luacheck:
|
||||
enabled: true
|
||||
brakeman:
|
||||
enabled: true
|
||||
dotenvLint:
|
||||
enabled: true
|
||||
htmlhint:
|
||||
enabled: true
|
||||
checkmake:
|
||||
enabled: true
|
||||
chat:
|
||||
auto_reply: true
|
||||
integrations:
|
||||
jira:
|
||||
usage: auto
|
||||
linear:
|
||||
usage: auto
|
||||
knowledge_base:
|
||||
opt_out: false
|
||||
web_search:
|
||||
enabled: true
|
||||
code_guidelines:
|
||||
enabled: true
|
||||
filePatterns: []
|
||||
learnings:
|
||||
scope: auto
|
||||
issues:
|
||||
scope: auto
|
||||
jira:
|
||||
usage: auto
|
||||
project_keys: []
|
||||
linear:
|
||||
usage: auto
|
||||
team_keys: []
|
||||
pull_requests:
|
||||
scope: auto
|
||||
code_generation:
|
||||
docstrings:
|
||||
language: en-US
|
||||
path_instructions: []
|
||||
unit_tests:
|
||||
path_instructions: []
|
||||
autopilot:
|
||||
enabled: false
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "Postiz Dev Container",
|
||||
"image": "localhost/postiz-devcontainer",
|
||||
"features": {},
|
||||
"customizations": {
|
||||
"vscode": {
|
||||
"settings": {},
|
||||
"extensions": []
|
||||
}
|
||||
},
|
||||
"forwardPorts": ["4200:4200", "3000:3000"],
|
||||
"mounts": ["source=/apps,destination=/apps/dist/,type=bind,consistency=cached"]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
# We want the docker builds to be clean, and as fast as possible. Don't send
|
||||
# any half-built stuff in the build context as a pre-caution (also saves copying
|
||||
# 180k files in node_modules that isn't used!).
|
||||
**/node_modules
|
||||
node_modules/*
|
||||
node_modules
|
||||
docker-data/*
|
||||
dist
|
||||
.nx
|
||||
/apps/frontend/.next
|
||||
/apps/backend/dist
|
||||
/apps/workers/dist
|
||||
/apps/cron/dist
|
||||
/apps/commands/dist
|
||||
.devcontainer
|
||||
**/.git
|
||||
**/*.md
|
||||
**/LICENSE
|
||||
**/npm-debug.log
|
||||
**/*.vscode
|
||||
.git
|
||||
.github
|
||||
reports
|
||||
@@ -0,0 +1,124 @@
|
||||
# Configuration reference: http://docs.postiz.com/configuration/reference
|
||||
|
||||
# === Required Settings
|
||||
DATABASE_URL="postgresql://postiz-user:postiz-password@localhost:5432/postiz-db-local"
|
||||
REDIS_URL="redis://localhost:6379"
|
||||
JWT_SECRET="random string for your JWT secret, make it long"
|
||||
|
||||
# === This needs to be exactly the URL you're accessing Postiz on
|
||||
FRONTEND_URL="http://localhost:4200"
|
||||
NEXT_PUBLIC_BACKEND_URL="http://localhost:3000"
|
||||
BACKEND_INTERNAL_URL="http://localhost:3000"
|
||||
|
||||
## Remember to set your public internet IP address in the allow-list for the API token.
|
||||
##
|
||||
## Cloudflare is currently required to save things like social media avatars for accounts.
|
||||
CLOUDFLARE_ACCOUNT_ID="your-account-id"
|
||||
CLOUDFLARE_ACCESS_KEY="your-access-key"
|
||||
CLOUDFLARE_SECRET_ACCESS_KEY="your-secret-access-key"
|
||||
CLOUDFLARE_BUCKETNAME="your-bucket-name"
|
||||
CLOUDFLARE_BUCKET_URL="https://your-bucket-url.r2.cloudflarestorage.com/"
|
||||
CLOUDFLARE_REGION="auto"
|
||||
|
||||
# === Common optional Settings
|
||||
|
||||
## This is a dummy key, you must create your own from Resend.
|
||||
## If this variable exists, user activation is required.
|
||||
## If it is commented out, users are activated automatically.
|
||||
#RESEND_API_KEY="RzeTwHijvxvPUerScFcenUZUALuQJzSaGSMJ"
|
||||
#EMAIL_FROM_ADDRESS=""
|
||||
#EMAIL_FROM_NAME=""
|
||||
#DISABLE_REGISTRATION=false
|
||||
|
||||
# Where will social media icons be saved - local or cloudflare.
|
||||
STORAGE_PROVIDER="local"
|
||||
|
||||
# Your upload directory path if you host your files locally, otherwise Cloudflare will be used.
|
||||
#UPLOAD_DIRECTORY=""
|
||||
|
||||
# Your upload directory path if you host your files locally, otherwise Cloudflare will be used.
|
||||
#NEXT_PUBLIC_UPLOAD_STATIC_DIRECTORY=""
|
||||
|
||||
# Social Media API Settings
|
||||
X_URL=""
|
||||
X_API_KEY=""
|
||||
X_API_SECRET=""
|
||||
LINKEDIN_CLIENT_ID=""
|
||||
LINKEDIN_CLIENT_SECRET=""
|
||||
REDDIT_CLIENT_ID=""
|
||||
REDDIT_CLIENT_SECRET=""
|
||||
GITHUB_CLIENT_ID=""
|
||||
GITHUB_CLIENT_SECRET=""
|
||||
BEEHIIVE_API_KEY=""
|
||||
BEEHIIVE_PUBLICATION_ID=""
|
||||
LISTMONK_DOMAIN=""
|
||||
LISTMONK_USER=""
|
||||
LISTMONK_API_KEY=""
|
||||
LISTMONK_LIST_ID=""
|
||||
THREADS_APP_ID=""
|
||||
THREADS_APP_SECRET=""
|
||||
FACEBOOK_APP_ID=""
|
||||
FACEBOOK_APP_SECRET=""
|
||||
YOUTUBE_CLIENT_ID=""
|
||||
YOUTUBE_CLIENT_SECRET=""
|
||||
TIKTOK_CLIENT_ID=""
|
||||
TIKTOK_CLIENT_SECRET=""
|
||||
PINTEREST_CLIENT_ID=""
|
||||
PINTEREST_CLIENT_SECRET=""
|
||||
DRIBBBLE_CLIENT_ID=""
|
||||
DRIBBBLE_CLIENT_SECRET=""
|
||||
DISCORD_CLIENT_ID=""
|
||||
DISCORD_CLIENT_SECRET=""
|
||||
DISCORD_BOT_TOKEN_ID=""
|
||||
SLACK_ID=""
|
||||
SLACK_SECRET=""
|
||||
SLACK_SIGNING_SECRET=""
|
||||
MASTODON_URL="https://mastodon.social"
|
||||
MASTODON_CLIENT_ID=""
|
||||
MASTODON_CLIENT_SECRET=""
|
||||
|
||||
# Chrome Extension Settings (for cookie-based platform integrations like Skool)
|
||||
EXTENSION_ID=""
|
||||
|
||||
# Misc Settings
|
||||
OPENAI_API_KEY=""
|
||||
NEXT_PUBLIC_DISCORD_SUPPORT=""
|
||||
NEXT_PUBLIC_POLOTNO=""
|
||||
# NOT_SECURED=false
|
||||
API_LIMIT=30 # The limit of the public API hour limit
|
||||
|
||||
# Payment settings
|
||||
FEE_AMOUNT=0.05
|
||||
STRIPE_PUBLISHABLE_KEY=""
|
||||
STRIPE_SECRET_KEY=""
|
||||
STRIPE_SIGNING_KEY=""
|
||||
STRIPE_SIGNING_KEY_CONNECT=""
|
||||
|
||||
# Developer Settings
|
||||
NX_ADD_PLUGINS=false
|
||||
IS_GENERAL="true" # required for now
|
||||
NEXT_PUBLIC_POSTIZ_OAUTH_DISPLAY_NAME="Authentik"
|
||||
NEXT_PUBLIC_POSTIZ_OAUTH_LOGO_URL="https://raw.githubusercontent.com/walkxcode/dashboard-icons/master/png/authentik.png"
|
||||
POSTIZ_GENERIC_OAUTH="false"
|
||||
POSTIZ_OAUTH_URL="https://auth.example.com"
|
||||
POSTIZ_OAUTH_AUTH_URL="https://auth.example.com/application/o/authorize"
|
||||
POSTIZ_OAUTH_TOKEN_URL="https://auth.example.com/application/o/token"
|
||||
POSTIZ_OAUTH_USERINFO_URL="https://authentik.example.com/application/o/userinfo"
|
||||
POSTIZ_OAUTH_CLIENT_ID=""
|
||||
POSTIZ_OAUTH_CLIENT_SECRET=""
|
||||
# POSTIZ_OAUTH_SCOPE="openid profile email" # default values
|
||||
|
||||
# Short Link Service Settings
|
||||
# DUB_TOKEN="" # Your self-hosted Dub API token
|
||||
# DUB_API_ENDPOINT="https://api.dub.co" # Your self-hosted Dub API endpoint
|
||||
# DUB_SHORT_LINK_DOMAIN="dub.sh" # Your self-hosted Dub domain
|
||||
|
||||
# SHORT_IO_SECRET_KEY="" # Your Short.io API secret key
|
||||
|
||||
# KUTT_API_KEY="" # Your Kutt.it API key
|
||||
# KUTT_API_ENDPOINT="https://kutt.it/api/v2" # Your self-hosted Kutt API endpoint
|
||||
# KUTT_SHORT_LINK_DOMAIN="kutt.it" # Your self-hosted Kutt domain
|
||||
|
||||
# LINK_DRIP_API_KEY="" # Your LinkDrip API key
|
||||
# LINK_DRIP_API_ENDPOINT="https://api.linkdrip.com/v1/" # Your self-hosted LinkDrip API endpoint
|
||||
# LINK_DRIP_SHORT_LINK_DOMAIN="dripl.ink" # Your self-hosted LinkDrip domain
|
||||
@@ -0,0 +1 @@
|
||||
node_modules
|
||||
@@ -0,0 +1,11 @@
|
||||
# To get started with Dependabot version updates, you'll need to specify which
|
||||
# package ecosystems to update and where the package manifests are located.
|
||||
# Please see the documentation for all configuration options:
|
||||
# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
|
||||
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "npm" # See documentation for possible values
|
||||
directory: "/" # Location of package manifests
|
||||
schedule:
|
||||
interval: "daily"
|
||||
@@ -0,0 +1,3 @@
|
||||
#patreon: Postiz
|
||||
open_collective: postiz
|
||||
# github: gitroomhq
|
||||
@@ -0,0 +1,86 @@
|
||||
name: "🐛 Bug Report"
|
||||
description: "Submit a bug report to help us improve,\nif you have a problem installing the app please join our https://discord.postiz.com instead for help."
|
||||
title: "Give your bug report a good title "
|
||||
labels: ["type: bug"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: We value your time and effort to submit this bug report. 🙏
|
||||
- type: textarea
|
||||
id: description
|
||||
validations:
|
||||
required: true
|
||||
attributes:
|
||||
label: "📜 Description"
|
||||
description: "A clear and concise description of what the bug is."
|
||||
placeholder: "It bugs out when ..."
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: steps-to-reproduce
|
||||
validations:
|
||||
required: true
|
||||
attributes:
|
||||
label: "👟 Reproduction steps"
|
||||
description: "How do you trigger this bug? Please walk us through it step by step."
|
||||
placeholder: "1. Go to '...'
|
||||
2. Click on '....'
|
||||
3. Scroll down to '....'
|
||||
4. See error"
|
||||
- type: textarea
|
||||
id: expected-behavior
|
||||
validations:
|
||||
required: true
|
||||
attributes:
|
||||
label: "👍 Expected behavior"
|
||||
description: "What did you think should happen?"
|
||||
placeholder: "It should ..."
|
||||
- type: textarea
|
||||
id: actual-behavior
|
||||
validations:
|
||||
required: true
|
||||
attributes:
|
||||
label: "👎 Actual Behavior with Screenshots"
|
||||
description: "What did actually happen? Add screenshots, if applicable."
|
||||
placeholder: "It actually ..."
|
||||
- type: dropdown
|
||||
id: operating-system
|
||||
attributes:
|
||||
label: "💻 Operating system"
|
||||
description: "What OS is your app running on?"
|
||||
options:
|
||||
- Linux
|
||||
- MacOS
|
||||
- Windows
|
||||
- Something else
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: node-version
|
||||
validations:
|
||||
required: true
|
||||
attributes:
|
||||
label: "🤖 Node Version"
|
||||
description: >
|
||||
What Node version are you using?
|
||||
- type: textarea
|
||||
id: additional-context
|
||||
validations:
|
||||
required: false
|
||||
attributes:
|
||||
label: "📃 Provide any additional context for the Bug."
|
||||
description: "Add any other context about the problem here."
|
||||
placeholder: "It actually ..."
|
||||
- type: checkboxes
|
||||
id: no-duplicate-issues
|
||||
attributes:
|
||||
label: "👀 Have you spent some time to check if this bug has been raised before?"
|
||||
options:
|
||||
- label: "I checked and didn't find similar issue"
|
||||
required: true
|
||||
- type: dropdown
|
||||
attributes:
|
||||
label: Are you willing to submit PR?
|
||||
description: This is absolutely not required, but we are happy to guide you in the contribution process. Find us in help-needed channel on [Discord](https://discord.gitroom.com)!
|
||||
options:
|
||||
- "Yes I am willing to submit a PR!"
|
||||
@@ -0,0 +1,55 @@
|
||||
name: 🚀 Feature
|
||||
description: "Submit a proposal for a new feature"
|
||||
title: "Give your feature request a title"
|
||||
labels: ["type: feature-request"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
We value your time and efforts to submit this Feature request form. 🙏
|
||||
- type: textarea
|
||||
id: feature-description
|
||||
validations:
|
||||
required: true
|
||||
attributes:
|
||||
label: "🔖 Feature description"
|
||||
description: "A clear and concise description of what the feature is."
|
||||
placeholder: "You should add ..."
|
||||
- type: textarea
|
||||
id: pitch
|
||||
validations:
|
||||
required: true
|
||||
attributes:
|
||||
label: "🎤 Why is this feature needed ?"
|
||||
description: "Please explain why this feature should be implemented and how it would be used. Add examples, if applicable."
|
||||
placeholder: "In my use-case, ..."
|
||||
- type: textarea
|
||||
id: solution
|
||||
validations:
|
||||
required: true
|
||||
attributes:
|
||||
label: "✌️ How do you aim to achieve this?"
|
||||
description: "A clear and concise description of what you want to happen."
|
||||
placeholder: "I want this feature to, ..."
|
||||
- type: textarea
|
||||
id: alternative
|
||||
validations:
|
||||
required: false
|
||||
attributes:
|
||||
label: "🔄️ Additional Information"
|
||||
description: "A clear and concise description of any alternative solutions or additional solutions you've considered."
|
||||
placeholder: "I tried, ..."
|
||||
- type: checkboxes
|
||||
id: no-duplicate-issues
|
||||
attributes:
|
||||
label: "👀 Have you spent some time to check if this feature request has been raised before?"
|
||||
options:
|
||||
- label: "I checked and didn't find similar issue"
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: willing-to-submit-pr
|
||||
attributes:
|
||||
label: Are you willing to submit PR?
|
||||
description: This is absolutely not required, but we are happy to guide you in the contribution process. Find us in help-needed channel on [Discord](https://discord.gitroom.com)!
|
||||
options:
|
||||
- "Yes I am willing to submit a PR!"
|
||||
@@ -0,0 +1,14 @@
|
||||
# Disable the default option to open a blank issue
|
||||
blank_issues_enabled: true
|
||||
|
||||
# Define your custom links
|
||||
contact_links:
|
||||
# The first link definition
|
||||
- name: 🙏 Installation Issue
|
||||
url: https://discord.postiz.com
|
||||
about: If you have an installation / configuration issue.
|
||||
|
||||
# You can add more links if needed
|
||||
- name: Security Issue
|
||||
url: https://github.com/gitroomhq/postiz-app/security/advisories/new
|
||||
about: Please submit security Issues our GitHub Security Advisories.
|
||||
@@ -0,0 +1,23 @@
|
||||
<!-- Remember to first apply via [the contribution form](https://contribute.postiz.com/p/postiz) and sign the [CLA](https://contribute.postiz.com/p/postiz/cla) before submitting a PR. -->
|
||||
|
||||
# What kind of change does this PR introduce?
|
||||
|
||||
eg: Bug fix, feature, docs update, ...
|
||||
|
||||
# Why was this change needed?
|
||||
|
||||
Please link to related issues when possible, and explain WHY you changed things, not WHAT you changed.
|
||||
|
||||
# Other information:
|
||||
|
||||
eg: Did you discuss this change with anybody before working on it (not required, but can be a good idea for bigger changes). Any plans for the future, etc?
|
||||
|
||||
# Checklist:
|
||||
|
||||
Put a "X" in the boxes below to indicate you have followed the checklist;
|
||||
|
||||
- [ ] I have read the [CONTRIBUTING](https://github.com/gitroomhq/postiz-app/blob/main/CONTRIBUTING.md) guide.
|
||||
- [ ] I have signed the [Contributor License Agreement (CLA)](https://contribute.postiz.com/p/postiz/cla) ([ICLA](https://github.com/gitroomhq/postiz-app/blob/main/ICLA.md) for individuals, [CCLA](https://github.com/gitroomhq/postiz-app/blob/main/CCLA.md) for entities).
|
||||
- [ ] I confirm I have not used AI to submit this PR or generate code for it.
|
||||
- [ ] I checked that there were no similar issues or PRs already open for this.
|
||||
- [ ] This PR fixes just ONE issue
|
||||
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 1.4 MiB |
|
After Width: | Height: | Size: 2.3 MiB |
|
After Width: | Height: | Size: 2.1 MiB |
|
After Width: | Height: | Size: 2.1 MiB |
@@ -0,0 +1,116 @@
|
||||
|
||||
# Copilot Coding Agent Instructions for Postiz
|
||||
|
||||
## Project Architecture
|
||||
- Monorepo managed by NX, with apps in `apps/` and shared code in `libraries/`.
|
||||
- Main services: `frontend` (Next.js), `backend` (NestJS), `cron`, `commands`, `extension`, `sdk`, and `workers`.
|
||||
- Data layer uses Prisma ORM (`libraries/nestjs-libraries/src/database/prisma/schema.prisma`) with PostgreSQL as the default database.
|
||||
- Redis (BullMQ) is used for queues and caching.
|
||||
- Email notifications via Resend.
|
||||
- Social login integrations (Instagram, Facebook) and Make.com/N8N integrations.
|
||||
|
||||
## Developer Workflows
|
||||
- Use Node.js 20.17.0 and pnpm 8+.
|
||||
- Install dependencies: `pnpm install`
|
||||
- Build all apps: `pnpm run build`
|
||||
- Run all apps in dev mode: `pnpm run dev`
|
||||
- Test: `pnpm test` (Jest, coverage enabled)
|
||||
- Individual app scripts are in each app's `package.json` (e.g., `pnpm --filter ./apps/backend run dev`).
|
||||
- Prisma DB commands: `pnpm run prisma-generate`, `pnpm run prisma-db-push`, `pnpm run prisma-reset`.
|
||||
- Docker: `docker compose -f ./docker-compose.dev.yaml up -d`
|
||||
|
||||
## Conventions & Patterns
|
||||
- Use conventional commits (`feat:`, `fix:`, `chore:`).
|
||||
- PRs should include clear descriptions, related issue links, and UI screenshots/GIFs if relevant.
|
||||
- Comments are required for complex logic.
|
||||
- Shared code lives in `libraries/` (e.g., helpers, React shared libraries, NestJS modules).
|
||||
- Environment variables are managed via `.env` and referenced in Docker and scripts.
|
||||
- Make sure to keep the `.env.example` file updated with new environment variables.
|
||||
|
||||
## Integration Points
|
||||
- External APIs: Social media (Instagram, Facebook), Make.com, N8N, Resend, Stripe, etc.
|
||||
- SDK (`apps/sdk`) provides programmatic access to Postiz features.
|
||||
- Extension (`apps/extension`) is built with Vite, React, TypeScript, and Tailwind CSS.
|
||||
|
||||
## Key Files & Directories
|
||||
- `apps/` — Main services and applications
|
||||
- `libraries/` — Shared code and modules
|
||||
- `docker-compose.dev.yaml` — Local development Docker setup
|
||||
- `.env` — Environment configuration
|
||||
- `jest.config.ts` — Test configuration
|
||||
- `pnpm-workspace.yaml` — Workspace package management
|
||||
- `README.md` — General project overview
|
||||
- `libraries/nestjs-libraries/src/database/prisma/schema.prisma` — Database schema
|
||||
|
||||
## Documentation
|
||||
- Main docs: https://docs.postiz.com/
|
||||
- Developer guide: https://docs.postiz.com/developer-guide
|
||||
- Public API: https://docs.postiz.com/public-api
|
||||
|
||||
---
|
||||
|
||||
# Logs
|
||||
|
||||
- Where logs are used, ensure Sentry is imported using `import * as Sentry from "@sentry/nextjs"`
|
||||
- Enable logging in Sentry using `Sentry.init({ enableLogs: true })`
|
||||
- Reference the logger using `const { logger } = Sentry`
|
||||
- Sentry offers a `consoleLoggingIntegration` that can be used to log specific console error types automatically without instrumenting the individual logger calls
|
||||
|
||||
## Configuration
|
||||
|
||||
The Sentry initialization needs to be updated to enable the logs feature.
|
||||
|
||||
### Baseline
|
||||
|
||||
```javascript
|
||||
import * as Sentry from "@sentry/nextjs";
|
||||
|
||||
Sentry.init({
|
||||
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
|
||||
|
||||
enableLogs: true,
|
||||
});
|
||||
```
|
||||
|
||||
### Logger Integration
|
||||
|
||||
```javascript
|
||||
Sentry.init({
|
||||
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
|
||||
integrations: [
|
||||
// send console.log, console.error, and console.warn calls as logs to Sentry
|
||||
Sentry.consoleLoggingIntegration({ levels: ["log", "error", "warn"] }),
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Logger Examples
|
||||
|
||||
`logger.fmt` is a template literal function that should be used to bring variables into the structured logs.
|
||||
|
||||
```javascript
|
||||
import * as Sentry from "@sentry/nextjs";
|
||||
|
||||
const { logger } = Sentry;
|
||||
|
||||
logger.trace("Starting database connection", { database: "users" });
|
||||
logger.debug(logger.fmt`Cache miss for user: ${userId}`);
|
||||
logger.info("Updated profile", { profileId: 345 });
|
||||
logger.warn("Rate limit reached for endpoint", {
|
||||
endpoint: "/api/results/",
|
||||
isEnterprise: false,
|
||||
});
|
||||
logger.error("Failed to process payment", {
|
||||
orderId: "order_123",
|
||||
amount: 99.99,
|
||||
});
|
||||
logger.fatal("Database connection pool exhausted", {
|
||||
database: "users",
|
||||
activeConnections: 100,
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
For questions or unclear conventions, check the main README or ask for clarification in your PR description.
|
||||
|
||||
|
After Width: | Height: | Size: 69 KiB |
@@ -0,0 +1,103 @@
|
||||
---
|
||||
name: "Build Containers"
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
tags:
|
||||
- '*'
|
||||
|
||||
jobs:
|
||||
build-containers-common:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
containerver: ${{ steps.getcontainerver.outputs.containerver }}
|
||||
steps:
|
||||
- name: Get Container Version
|
||||
id: getcontainerver
|
||||
run: |
|
||||
echo "containerver=${{ github.ref_name }}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
build-containers:
|
||||
needs: build-containers-common
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- runnertags: ubuntu-latest
|
||||
arch: amd64
|
||||
- runnertags: ubuntu-24.04-arm
|
||||
arch: arm64
|
||||
runs-on: ${{ matrix.runnertags }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to ghcr
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ github.token }}
|
||||
|
||||
- name: Build and Push Image
|
||||
env:
|
||||
CONTAINERVER: ${{ needs.build-containers-common.outputs.containerver }}
|
||||
NEXT_PUBLIC_VERSION: ${{ github.ref_name }}
|
||||
run: |
|
||||
docker buildx build --platform linux/${{ matrix.arch }} \
|
||||
-f Dockerfile.dev \
|
||||
-t ghcr.io/gitroomhq/postiz-app:${{ env.CONTAINERVER }}-${{ matrix.arch }} \
|
||||
--build-arg NEXT_PUBLIC_VERSION=${{ env.NEXT_PUBLIC_VERSION }} \
|
||||
--pull \
|
||||
--no-cache \
|
||||
--provenance=false --sbom=false \
|
||||
--output "type=registry,name=ghcr.io/gitroomhq/postiz-app:${{ env.CONTAINERVER }}-${{ matrix.arch }}" .
|
||||
|
||||
build-container-manifest:
|
||||
needs: [build-containers, build-containers-common]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Login to ghcr
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ github.token }}
|
||||
|
||||
- name: Create Docker Manifest
|
||||
env:
|
||||
CONTAINERVER: ${{ needs.build-containers-common.outputs.containerver }}
|
||||
run: |
|
||||
# Verify the architecture images
|
||||
echo "Verifying AMD64 image:"
|
||||
docker buildx imagetools inspect ghcr.io/gitroomhq/postiz-app:${{ env.CONTAINERVER }}-amd64
|
||||
|
||||
echo "Verifying ARM64 image:"
|
||||
docker buildx imagetools inspect ghcr.io/gitroomhq/postiz-app:${{ env.CONTAINERVER }}-arm64
|
||||
|
||||
# Try to remove any existing manifests first
|
||||
docker manifest rm ghcr.io/gitroomhq/postiz-app:${{ env.CONTAINERVER }} || true
|
||||
docker manifest rm ghcr.io/gitroomhq/postiz-app:latest || true
|
||||
|
||||
# Create and push the version-specific manifest
|
||||
docker manifest create ghcr.io/gitroomhq/postiz-app:${{ env.CONTAINERVER }} \
|
||||
--amend ghcr.io/gitroomhq/postiz-app:${{ env.CONTAINERVER }}-amd64 \
|
||||
--amend ghcr.io/gitroomhq/postiz-app:${{ env.CONTAINERVER }}-arm64
|
||||
|
||||
docker manifest push ghcr.io/gitroomhq/postiz-app:${{ env.CONTAINERVER }}
|
||||
|
||||
# Create and push the latest manifest
|
||||
docker manifest create ghcr.io/gitroomhq/postiz-app:latest \
|
||||
--amend ghcr.io/gitroomhq/postiz-app:${{ env.CONTAINERVER }}-amd64 \
|
||||
--amend ghcr.io/gitroomhq/postiz-app:${{ env.CONTAINERVER }}-arm64
|
||||
|
||||
docker manifest push ghcr.io/gitroomhq/postiz-app:latest
|
||||
|
||||
- name: Verify Manifest
|
||||
run: |
|
||||
docker manifest inspect ghcr.io/gitroomhq/postiz-app:latest
|
||||
@@ -0,0 +1,34 @@
|
||||
name: Build Extension
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
submit:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Zip extensions
|
||||
run: FRONTEND_URL=https://platform.postiz.com pnpm run build:extension
|
||||
|
||||
- name: Upload to Nextcloud
|
||||
env:
|
||||
NEXTCLOUD_URL: ${{ secrets.NEXTCLOUD_URL }}
|
||||
NEXTCLOUD_USERNAME: ${{ secrets.NEXTCLOUD_USERNAME }}
|
||||
NEXTCLOUD_PASSWORD: ${{ secrets.NEXTCLOUD_PASSWORD }}
|
||||
run: |
|
||||
curl -T apps/extension/extension.zip \
|
||||
-u "$NEXTCLOUD_USERNAME:$NEXTCLOUD_PASSWORD" \
|
||||
"$NEXTCLOUD_URL/extension.zip"
|
||||
@@ -0,0 +1,54 @@
|
||||
---
|
||||
name: Build
|
||||
|
||||
on:
|
||||
push:
|
||||
merge_group:
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: ['22.12.0']
|
||||
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Use Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
|
||||
- name: Install pnpm
|
||||
uses: pnpm/action-setup@v2
|
||||
with:
|
||||
version: 10
|
||||
run_install: false
|
||||
|
||||
- name: Get pnpm store directory
|
||||
shell: bash
|
||||
run: |
|
||||
echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV
|
||||
|
||||
# - name: Setup pnpm cache
|
||||
# uses: actions/cache@v4
|
||||
# with:
|
||||
# path: |
|
||||
# ${{ env.STORE_PATH }}
|
||||
# ${{ github.workspace }}/.next/cache
|
||||
# key: ${{ runner.os }}-pnpm-${{ hashFiles('**/pnpm-lock.yaml') }}-${{ hashFiles('**/*.js', '**/*.jsx', '**/*.ts', '**/*.tsx') }}
|
||||
# restore-keys: |
|
||||
# ${{ runner.os }}-pnpm-${{ hashFiles('**/pnpm-lock.yaml') }}-
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Build
|
||||
run: pnpm run build
|
||||
@@ -0,0 +1,43 @@
|
||||
---
|
||||
name: "Code Quality Analysis"
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- apps/**
|
||||
- '!apps/docs/**'
|
||||
- libraries/**
|
||||
merge_group:
|
||||
|
||||
|
||||
jobs:
|
||||
analyze:
|
||||
name: Analyze (${{ matrix.language }})
|
||||
|
||||
runs-on: 'ubuntu-latest'
|
||||
permissions:
|
||||
security-events: write
|
||||
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- language: javascript-typescript
|
||||
build-mode: none
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v3
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
build-mode: ${{ matrix.build-mode }}
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v3
|
||||
with:
|
||||
category: "/language:${{matrix.language}}"
|
||||
@@ -0,0 +1,60 @@
|
||||
---
|
||||
name: ESLint
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- package.json
|
||||
- apps/**
|
||||
- '!apps/docs/**'
|
||||
- libraries/**
|
||||
|
||||
pull_request:
|
||||
paths:
|
||||
- package.json
|
||||
- apps/**
|
||||
- '!apps/docs/**'
|
||||
- libraries/**
|
||||
|
||||
jobs:
|
||||
eslint:
|
||||
name: Run eslint scanning
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
security-events: write
|
||||
actions: read # only required for a private repository by github/codeql-action/upload-sarif to get the Action run status
|
||||
strategy:
|
||||
matrix:
|
||||
service: ["backend", "frontend"]
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: |
|
||||
**/pnpm-lock.yaml
|
||||
|
||||
- name: Install ESLint
|
||||
run: |
|
||||
npm install eslint
|
||||
npm install @microsoft/eslint-formatter-sarif@2.1.7
|
||||
|
||||
- name: Run ESLint
|
||||
run: npx eslint apps/${{ matrix.service }}/
|
||||
--config apps/${{ matrix.service }}/.eslintrc.json
|
||||
--format @microsoft/eslint-formatter-sarif
|
||||
--output-file apps/${{ matrix.service }}/eslint-results.sarif
|
||||
continue-on-error: true
|
||||
|
||||
- name: Upload analysis results to GitHub
|
||||
uses: github/codeql-action/upload-sarif@v3
|
||||
with:
|
||||
sarif_file: apps/${{ matrix.service }}/eslint-results.sarif
|
||||
wait-for-processing: true
|
||||
@@ -0,0 +1,28 @@
|
||||
---
|
||||
name: Issue Label Triggers
|
||||
on:
|
||||
issues:
|
||||
types:
|
||||
- labeled
|
||||
|
||||
jobs:
|
||||
closed-public-website:
|
||||
if: github.event.label.name == 'trigger-public-website'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
issues: write
|
||||
steps:
|
||||
- name: Add comment
|
||||
run: gh issue comment "$NUMBER" --body "$BODY" && gh issue close "$NUMBER"
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
NUMBER: ${{ github.event.issue.number }}
|
||||
BODY: >
|
||||
This issue concerns the public website, which is not open source and is not part of this repository.
|
||||
|
||||
|
||||
If you have a question or concern about the content of the public website, please contact Nevo David.
|
||||
|
||||
|
||||
If you are looking to contribute to the open source Postiz project code, this is the correct repository, and we welcome your contributions in a new GitHub issue.
|
||||
@@ -0,0 +1,32 @@
|
||||
name: Publish Extension
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
submit:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Zip extensions
|
||||
run: FRONTEND_URL=https://platform.postiz.com pnpm run build:extension
|
||||
|
||||
- name: Publish to Chrome Web Store
|
||||
uses: mnao305/chrome-extension-upload@v5.0.0
|
||||
with:
|
||||
extension-id: ${{ secrets.CHROME_EXTENSION_ID }}
|
||||
client-id: ${{ secrets.CHROME_CLIENT_ID }}
|
||||
client-secret: ${{ secrets.CHROME_CLIENT_SECRET }}
|
||||
refresh-token: ${{ secrets.CHROME_REFRESH_TOKEN }}
|
||||
file-path: apps/extension/extension.zip
|
||||
@@ -0,0 +1,33 @@
|
||||
name: Close inactive issues
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
schedule:
|
||||
- cron: "*/30 * * * *"
|
||||
|
||||
jobs:
|
||||
close-issues:
|
||||
if: github.repository == 'gitroomhq/postiz-app'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
issues: write
|
||||
pull-requests: write
|
||||
steps:
|
||||
- uses: actions/stale@v9
|
||||
with:
|
||||
days-before-issue-stale: 90
|
||||
days-before-issue-close: 7
|
||||
stale-issue-label: "stale"
|
||||
stale-issue-message: "This issue is stale because it has been open for 90 days with no activity."
|
||||
close-issue-message: "This issue was closed because it has been inactive for 7 days since being marked as stale."
|
||||
exempt-issue-labels: "no-stale-bot"
|
||||
|
||||
days-before-pr-stale: 90
|
||||
days-before-pr-close: 7
|
||||
stale-pr-label: "stale"
|
||||
stale-pr-message: "This PR is stale because it has been open for 90 days with no activity."
|
||||
close-pr-message: "This PR was closed because it has been inactive for 7 days since being marked as stale."
|
||||
exempt-pr-label: "no-stale-bot"
|
||||
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
operations-per-run: 180
|
||||
@@ -0,0 +1,63 @@
|
||||
# See http://help.github.com/ignore-files/ for more about ignoring files.
|
||||
|
||||
# compiled output
|
||||
dist
|
||||
tmp
|
||||
/out-tsc
|
||||
.env
|
||||
# dependencies
|
||||
node_modules
|
||||
|
||||
# IDEs and editors
|
||||
/.idea
|
||||
.project
|
||||
.classpath
|
||||
.c9/
|
||||
*.launch
|
||||
.settings/
|
||||
*.sublime-workspace
|
||||
.vscode/*
|
||||
|
||||
# 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
|
||||
|
||||
# System Files
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
.nx/cache
|
||||
.nx/workspace-data
|
||||
|
||||
# Next.js
|
||||
.next
|
||||
|
||||
# Vim files
|
||||
**/*.swp
|
||||
**/*.swo
|
||||
|
||||
# Temporary files
|
||||
*.orig
|
||||
*.~*~
|
||||
*.tsbuildinfo
|
||||
|
||||
# ignore Secrets folder
|
||||
.secrets/
|
||||
libraries/plugins/src/plugins.ts
|
||||
i18n.cache
|
||||
|
||||
# Generated by apps/frontend/scripts/fetch-gtm.mjs on install
|
||||
apps/frontend/public/g.js
|
||||
@@ -0,0 +1,3 @@
|
||||
[submodule "libraries/plugins/src/list/public-api"]
|
||||
path = libraries/plugins/src/list/public-api
|
||||
url = git@github.com:gitroomhq/public-api.git
|
||||
@@ -0,0 +1,5 @@
|
||||
ignore-workspace-root-check=true
|
||||
node-linker=hoisted
|
||||
restrict-manifest-changes=true
|
||||
sync-injected-deps-after-scripts[]=build
|
||||
inject-workspace-packages=true
|
||||
@@ -0,0 +1,4 @@
|
||||
# Add files here to ignore them from prettier formatting
|
||||
/dist
|
||||
/coverage
|
||||
/.nx/cache
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"singleQuote": true
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
# Fiduciary License Agreement 2.1
|
||||
|
||||
Based on the
|
||||
|
||||
## Entity Contributor License Agreement (CCLA)
|
||||
|
||||
Thank you for your interest in contributing to GitroomHQ's Postiz ("We" or "Us").
|
||||
|
||||
The purpose of this contributor agreement ("Agreement") is to clarify and document the rights granted by contributors to Us. To make this document effective, please follow the instructions at https://contribute.postiz.com/p/postiz/cla.
|
||||
|
||||
### Preamble
|
||||
|
||||
Software is deeply embedded in all aspects of our lives and it is important that it empower, rather than restrict us. Free Software gives everybody the rights to use, understand, adapt and share software. These rights help support other fundamental freedoms like freedom of speech, press and privacy.
|
||||
|
||||
Development of Free Software can follow many patterns. In some cases whole development is handled by a sole programmer or a small group of people. But usually, the creation and maintenance of software is a complex process that requires the contribution of many individuals. This also affects who owns the rights to the software. In the latter case, rights in software are owned jointly by a great number of individuals.
|
||||
|
||||
To tackle this issue some projects require a full copyright assignment to be signed by all contributors. The problem with such assignments is that they often lack checks and balances that would protect the contributors from potential abuse of power from the new copyright holder.
|
||||
|
||||
FSFE's Fiduciary License Agreement (FLA) was created by the Free Software Foundation Europe e.V. with just that in mind – to concentrate all deciding power within one entity and prevent fragmentation of rights on one hand, while on the other preventing that single entity from abusing its power. The main aim is to ensure that the software covered under the FLA will forever remain Free Software.
|
||||
|
||||
This process only serves for the transfer of economic rights. So-called moral rights (e.g. author's right to be identified as author) remain with the original author(s) and are inalienable.
|
||||
|
||||
### How to use this FLA
|
||||
|
||||
This is the version of the Agreement for Legal Entities. It should be accepted by an individual authorized to enter into this Agreement on behalf of the Legal Entity, such as an officer or other authorized representative. By accepting this Agreement, You confirm that You have the authority to bind the Legal Entity and that Contributions Submitted to Us on behalf of the Legal Entity, including Contributions Submitted by Your Designated Employees, are covered by this Agreement. You provide Your acceptance and the list of Your Designated Employees by following the instructions at https://contribute.postiz.com/p/postiz/cla. If the Legal Entity does not own the Copyright in the entire Contribution, any other author of the Contribution should also sign the applicable Agreement. In any event, please contact Us at nevo@postiz.com.
|
||||
|
||||
### Definitions
|
||||
|
||||
**"You"** means any Legal Entity on behalf of whom a Contribution has been made to Us.
|
||||
|
||||
**"Legal Entity"** means an entity that is not a natural person.
|
||||
|
||||
**"Affiliate"** means any other Legal Entity that controls, is controlled by, or under common control with that Legal Entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such Legal Entity, whether by contract or otherwise, (ii) ownership of fifty percent (50%) or more of the outstanding shares or securities that vote to elect the management or other persons who direct such Legal Entity, or (iii) beneficial ownership of such entity.
|
||||
|
||||
**"Contribution"** means any original work of authorship, including any original modifications or additions to an existing work of authorship, Submitted for inclusion into Material by You to Us, in which You own the Copyright.
|
||||
|
||||
**"Copyright"** means all rights protecting works of authorship, including copyright, moral and neighboring rights, as appropriate, for the full term of their existence.
|
||||
|
||||
**"Material"** means the software and/or documentation of Postiz that We make available to third parties.
|
||||
|
||||
**"Submit"** means any act by which a Contribution is transferred to Us by You by means of tangible or intangible media, including but not limited to electronic mailing lists, source code control systems, and issue tracking systems, but excluding any transfer that is conspicuously marked or otherwise designated in writing by You as "Not a Contribution."
|
||||
|
||||
**"Documentation"** means any non-software portion of a Contribution.
|
||||
|
||||
### License grant
|
||||
|
||||
#### Copyright license to Us
|
||||
|
||||
Subject to the terms and conditions of this Agreement, You hereby grant to Us a worldwide, royalty-free, exclusive, perpetual and irrevocable (except as stated in Section "Term") license, with the right to transfer an unlimited number of non-exclusive licenses or to grant sublicenses to third parties, under the Copyright covering the Contribution to use the Contribution by all means, including, but not limited to:
|
||||
|
||||
* publish the Contribution,
|
||||
* modify the Contribution,
|
||||
* prepare derivative works based upon or containing the Contribution and/or to combine the Contribution with other Materials,
|
||||
* reproduce the Contribution in original or modified form,
|
||||
* distribute, to make the Contribution available to the public, display and publicly perform the Contribution in original or modified form.
|
||||
|
||||
#### Moral rights
|
||||
|
||||
Moral Rights remain unaffected to the extent they are recognized and not waivable by applicable law. Notwithstanding, You may add Your name to the attribution mechanism customarily used in the Materials You Contribute to, such as the header of the source code files of Your Contribution, and We will respect this attribution when using Your Contribution.
|
||||
|
||||
#### Copyright license back to You
|
||||
|
||||
Upon such grant of rights to Us, We immediately grant to You a worldwide, royalty-free, non-exclusive, perpetual and irrevocable license, with the right to transfer an unlimited number of non-exclusive licenses or to grant sublicenses to third parties, under the Copyright covering the Contribution to use the Contribution by all means, including, but not limited to:
|
||||
|
||||
* publish the Contribution,
|
||||
* modify the Contribution,
|
||||
* prepare derivative works based upon or containing the Contribution and/or to combine the Contribution with other Materials,
|
||||
* reproduce the Contribution in original or modified form,
|
||||
* distribute, to make the Contribution available to the public, display and publicly perform the Contribution in original or modified form.
|
||||
|
||||
This license back is limited to the Contribution and does not provide any rights to the Material.
|
||||
|
||||
### Patents
|
||||
|
||||
#### Patent license
|
||||
|
||||
Subject to the terms and conditions of this Agreement You hereby grant to Us and to recipients of Materials distributed by Us a worldwide, royalty-free, non-exclusive, perpetual and irrevocable (except as stated in Subsection "Revocation of patent license") patent license, with the right to transfer an unlimited number of non-exclusive licenses or to grant sublicenses to third parties, to make, have made, use, sell, offer for sale, import and otherwise transfer the Contribution and the Contribution in combination with any Material (and portions of such combination). This license applies to all patents owned or controlled by You, whether already acquired or hereafter acquired, that would be infringed by making, having made, using, selling, offering for sale, importing or otherwise transferring of Your Contribution(s) alone or by combination of Your Contribution(s) with any Material.
|
||||
|
||||
#### Revocation of patent license
|
||||
|
||||
You reserve the right to revoke the patent license stated in Subsection "Patent license" if We make any infringement claim that is targeted at Your Contribution and not asserted for a Defensive Purpose. An assertion of claims of the Patents shall be considered for a "Defensive Purpose" if the claims are asserted against an entity that has filed, maintained, threatened, or voluntarily participated in a patent infringement lawsuit against Us or any of Our licensees.
|
||||
|
||||
### License obligations by Us
|
||||
|
||||
We may, but are under no obligation to, include the Contribution You Submitted to Us into the Material.
|
||||
|
||||
We agree to (sub)license the Contribution or any Materials containing, based on or derived from Your Contribution under the terms of any licenses that qualify as [Free Software](https://www.gnu.org/philosophy/free-sw.html) as defined by the Free Software Foundation and at the same time qualify as [Open Source](https://opensource.org/osd) as defined by the Open Source Initiative. For clarification, should We make available any Material under a non-free or non-open license, We must make a version of such Material available under a free and open license too.
|
||||
|
||||
We agree to license patents owned or controlled by You only to the extent necessary to (sub)license Your Contribution(s) and the combination of Your Contribution(s) with the Material under the terms of any licenses the Free Software Foundation classifies as Free Software licenses and which are approved by the Open Source Initiative as Open Source licenses.
|
||||
|
||||
### Disclaimer
|
||||
|
||||
**We acknowledge that You provide the Contribution "as is".** **More particularly, You disclaim all express or implied warranties including, without limitation, any implied warranty of satisfactory quality, fitness for a particular purpose and non-infringement. To the extent that any such warranties cannot be disclaimed, such warranty is limited in duration and extent to the minimum period and extent permitted by law.**
|
||||
|
||||
### Consequential damage waiver
|
||||
|
||||
**To the maximum extent permitted by applicable law, in no event will You or We be liable for any loss of profits, loss of anticipated savings, loss of data, indirect, special, incidental, consequential and exemplary damages arising out of this Agreement regardless of the legal or equitable theory (contract, tort or otherwise) upon which the claim is based.**
|
||||
|
||||
### Approximation of disclaimer and damage waiver
|
||||
|
||||
**If the disclaimer and damage waiver mentioned in Section "Disclaimer" and Section "Consequential damage waiver" cannot be given legal effect under applicable local law, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil or contractual liability in connection with the Contribution.**
|
||||
|
||||
### Term
|
||||
|
||||
This Agreement shall come into effect upon Your acceptance of the terms and conditions.
|
||||
|
||||
This Agreement shall apply for the term of the copyright and patents licensed here. However, You shall have the right to terminate the Agreement if We do not fulfill the obligations as set forth in Section "License obligations by Us". Such termination must be made in writing.
|
||||
|
||||
In the event of a termination of this Agreement Sections "Disclaimer", "Term" and "Miscellaneous" shall survive such termination and shall remain in full force thereafter. For the avoidance of doubt, Free and Open Source Software (sub)licenses that have already been granted for Contributions at the date of the termination shall remain in full force after the termination of this Agreement.
|
||||
|
||||
### Miscellaneous
|
||||
|
||||
This Agreement and all disputes, claims, actions, suits or other proceedings arising out of this agreement or relating in any way to it shall be governed by the laws of Germany, excluding its private international law provisions.
|
||||
|
||||
This Agreement sets out the entire agreement between You and Us for Your Contributions to Us and overrides all other agreements or understandings.
|
||||
|
||||
If any provision of this Agreement is found void and unenforceable, such provision will be replaced to the extent possible with a provision that comes closest to the meaning of the original provision and that is enforceable. The terms and conditions set forth in this Agreement shall apply notwithstanding any failure of essential purpose of this Agreement or any limited remedy to the maximum extent possible under law.
|
||||
|
||||
You agree to notify Us of any facts or circumstances of which You become aware that would make Your representations under this Agreement inaccurate in any respect.
|
||||
|
||||
### Designated Employees and pre-existing works
|
||||
|
||||
You authorize each individual listed (Your "Designated Employees") to Submit Contributions to Us on Your behalf. Contributions Submitted by a Designated Employee on Your behalf are treated as Your Contributions under this Agreement, and the rights and licenses granted by You in this Agreement apply to them.
|
||||
|
||||
It is Your responsibility to keep the list of Your Designated Employees current and to notify Us of any change to that list or to the individual You have identified as Your point of contact. Until We receive notice of a change, We may rely on the most recent list You have provided. You agree to notify Us promptly when an individual is no longer authorized to Submit Contributions on Your behalf.
|
||||
|
||||
Should You wish to Submit work that is not Your original creation, You may Submit it to Us separately, marking the work clearly and identifying its source and any license or other restriction of which You are aware. Any such work of which You are aware on the date You accept this Agreement should be identified through the contribution form at https://contribute.postiz.com/p/postiz/cla.
|
||||
@@ -0,0 +1,62 @@
|
||||
This project is Postiz, a tool to schedule social media and chat posts to 28+ channels.
|
||||
You can add posts to the calendar, they will be added into a workflow and posted at the right time.
|
||||
You can find things like:
|
||||
- Schedule posts
|
||||
- Calendar view
|
||||
- Analytics
|
||||
- Team management
|
||||
- Media library
|
||||
|
||||
This project is a monorepo with a root only package.json of dependencies.
|
||||
Made with PNPM.
|
||||
We have 3 important folders
|
||||
|
||||
- apps/backend - this is where the API code is (NESTJS)
|
||||
- apps/orchestrator - this is temporal, it's for background jobs (NESTJS) it contains all the workflows and activities
|
||||
- apps/frontend - this is the code of the frontend (Vite ReactJS)
|
||||
- /libraries contains a lot of services shared between backend and orchestrator and frontend components.
|
||||
|
||||
We are using only pnpm, don't use any other dependency manager.
|
||||
Never install frontend components from npmjs, focus on writing native components.
|
||||
|
||||
The project uses tailwind 3, before writing any component look at:
|
||||
- /apps/frontend/src/app/colors.scss
|
||||
- /apps/frontend/src/app/global.scss
|
||||
- /apps/frontend/tailwind.config.js
|
||||
|
||||
All the --color-custom* are deprecated, don't use them.
|
||||
|
||||
And check other components in the system before to get the right design.
|
||||
|
||||
When working on the backend we need to pass the 3 layers:
|
||||
Controller >> Service >> Repository (no shortcuts)
|
||||
In some cases we will have
|
||||
Controller >> Mananger >> Service >> Repository.
|
||||
|
||||
Most of the server logic should be inside of libs/server.
|
||||
The backend repository is mostly used to write controller, and import files from libs.server.
|
||||
|
||||
For the frontend follow this:
|
||||
- Many of the UI components lives in /apps/frontend/src/components/ui
|
||||
- Routing is in /apps/frontend/src/app
|
||||
- Components are in /apps/frontend/src/components
|
||||
- always use SWR to fetch stuff, and use "useFetch" hook from /libraries/helpers/src/utils/custom.fetch.tsx
|
||||
|
||||
When using SWR, each one have to be in a seperate hook and must comply with react-hooks/rules-of-hooks, never put eslint-disable-next-line on it.
|
||||
|
||||
It means that this is valid:
|
||||
const useCommunity = () => {
|
||||
return useSWR....
|
||||
}
|
||||
|
||||
This is not valid:
|
||||
const useCommunity = () => {
|
||||
return {
|
||||
communities: () => useSWR<CommunitiesListResponse>("communities", getCommunities),
|
||||
providers: () => useSWR<ProvidersListResponse>("providers", getProviders),
|
||||
};
|
||||
}
|
||||
|
||||
- Linting of the project can run only from the root.
|
||||
- Use only pnpm.
|
||||
- The system is in production with many users, if you want to change something, you need to be sure that you are not breaking anything for existing users and a migration might be needed
|
||||
@@ -0,0 +1,128 @@
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
We as members, contributors, and leaders pledge to make participation in our
|
||||
community a harassment-free experience for everyone, regardless of age, body
|
||||
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
||||
identity and expression, level of experience, education, socio-economic status,
|
||||
nationality, personal appearance, race, religion, or sexual identity
|
||||
and orientation.
|
||||
|
||||
We pledge to act and interact in ways that contribute to an open, welcoming,
|
||||
diverse, inclusive, and healthy community.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to a positive environment for our
|
||||
community include:
|
||||
|
||||
- Demonstrating empathy and kindness toward other people
|
||||
- Being respectful of differing opinions, viewpoints, and experiences
|
||||
- Giving and gracefully accepting constructive feedback
|
||||
- Accepting responsibility and apologizing to those affected by our mistakes,
|
||||
and learning from the experience
|
||||
- Focusing on what is best not just for us as individuals, but for the
|
||||
overall community
|
||||
|
||||
Examples of unacceptable behavior include:
|
||||
|
||||
- The use of sexualized language or imagery, and sexual attention or
|
||||
advances of any kind
|
||||
- Trolling, insulting or derogatory comments, and personal or political attacks
|
||||
- Public or private harassment
|
||||
- Publishing others' private information, such as a physical or email
|
||||
address, without their explicit permission
|
||||
- Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Enforcement Responsibilities
|
||||
|
||||
Community leaders are responsible for clarifying and enforcing our standards of
|
||||
acceptable behavior and will take appropriate and fair corrective action in
|
||||
response to any behavior that they deem inappropriate, threatening, offensive,
|
||||
or harmful.
|
||||
|
||||
Community leaders have the right and responsibility to remove, edit, or reject
|
||||
comments, commits, code, wiki edits, issues, and other contributions that are
|
||||
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
||||
decisions when appropriate.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies within all community spaces, and also applies when
|
||||
an individual is officially representing the community in public spaces.
|
||||
Examples of representing our community include using an official e-mail address,
|
||||
posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported to the community leaders responsible for enforcement at
|
||||
nevo@gitroom.com.
|
||||
All complaints will be reviewed and investigated promptly and fairly.
|
||||
|
||||
All community leaders are obligated to respect the privacy and security of the
|
||||
reporter of any incident.
|
||||
|
||||
## Enforcement Guidelines
|
||||
|
||||
Community leaders will follow these Community Impact Guidelines in determining
|
||||
the consequences for any action they deem in violation of this Code of Conduct:
|
||||
|
||||
### 1. Correction
|
||||
|
||||
**Community Impact**: Use of inappropriate language or other behavior deemed
|
||||
unprofessional or unwelcome in the community.
|
||||
|
||||
**Consequence**: A private, written warning from community leaders, providing
|
||||
clarity around the nature of the violation and an explanation of why the
|
||||
behavior was inappropriate. A public apology may be requested.
|
||||
|
||||
### 2. Warning
|
||||
|
||||
**Community Impact**: A violation through a single incident or series
|
||||
of actions.
|
||||
|
||||
**Consequence**: A warning with consequences for continued behavior. No
|
||||
interaction with the people involved, including unsolicited interaction with
|
||||
those enforcing the Code of Conduct, for a specified period of time. This
|
||||
includes avoiding interactions in community spaces as well as external channels
|
||||
like social media. Violating these terms may lead to a temporary or
|
||||
permanent ban.
|
||||
|
||||
### 3. Temporary Ban
|
||||
|
||||
**Community Impact**: A serious violation of community standards, including
|
||||
sustained inappropriate behavior.
|
||||
|
||||
**Consequence**: A temporary ban from any sort of interaction or public
|
||||
communication with the community for a specified period of time. No public or
|
||||
private interaction with the people involved, including unsolicited interaction
|
||||
with those enforcing the Code of Conduct, is allowed during this period.
|
||||
Violating these terms may lead to a permanent ban.
|
||||
|
||||
### 4. Permanent Ban
|
||||
|
||||
**Community Impact**: Demonstrating a pattern of violation of community
|
||||
standards, including sustained inappropriate behavior, harassment of an
|
||||
individual, or aggression toward or disparagement of classes of individuals.
|
||||
|
||||
**Consequence**: A permanent ban from any sort of public interaction within
|
||||
the community.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
||||
version 2.0, available at
|
||||
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
||||
|
||||
Community Impact Guidelines were inspired by [Mozilla's code of conduct
|
||||
enforcement ladder](https://github.com/mozilla/diversity).
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
|
||||
For answers to common questions about this code of conduct, see the FAQ at
|
||||
https://www.contributor-covenant.org/faq. Translations are available at
|
||||
https://www.contributor-covenant.org/translations.
|
||||
@@ -0,0 +1,72 @@
|
||||
# Contributing
|
||||
|
||||
Contributions are welcome - code, docs, whatever it might be! If this is your first contribution to an Open Source project or you're a core maintainer of multiple projects, your time and interest in contributing to this project is most welcome.
|
||||
|
||||
## Read the developers guide
|
||||
|
||||
The main documentation site has a [developer guide](https://docs.postiz.com/developer-guide) . That guide provides you a good understanding of the project structure, and how to setup your development environment. Read this document after you have read that guide. This document is intended to provide you a good understanding of how to submit your first contribution.
|
||||
|
||||
## Apply via the contribution form
|
||||
|
||||
To submit your contribution, please fill out the [contribution form](https://contribute.postiz.com/p/postiz). This helps us evaluate whether your contribution is a good fit for the project. We will review your submission and get back to you as soon as possible.
|
||||
|
||||
## Sign the Contributor License Agreement (CLA)
|
||||
|
||||
Before we can merge your contribution, you must agree to our Contributor License Agreement (CLA). This documents the rights you grant us and helps ensure that Postiz can always remain Free and Open Source Software.
|
||||
|
||||
- Contributing as an individual? The [Individual Contributor License Agreement (ICLA)](./ICLA.md) applies.
|
||||
- Contributing on behalf of a company or other legal entity? The [Entity Contributor License Agreement (CCLA)](./CCLA.md) applies.
|
||||
|
||||
You accept the agreement by following the instructions on the [CLA page](https://contribute.postiz.com/p/postiz/cla). You only need to do this once, and it covers your present and future contributions to Postiz.
|
||||
|
||||
## Write code with others
|
||||
|
||||
This is an open source project, with an open and welcoming community that is always keen to welcome new contributors. We recommend the two best ways to interact with the community are:
|
||||
|
||||
- **GitHub issues**: To discuss more slowly, or longer-written messages.
|
||||
- **[Discord chat](https://discord.postiz.com)**: To chat with people [Discord chat](https://discord.postiz.com/) and a quicker feedback.
|
||||
|
||||
As a general rule;
|
||||
|
||||
- **If a change is less than 3 lines**: You're probably safe just to submit the change without a discussion. This includes typos, dependency changes, and quick fixes, etc.
|
||||
- **If a change is more than 3 lines**: It's probably best to discuss the change in an issue or on discord first. This is simply because you might not be aware of the roadmap for the project, or understand the impact this change might have. We're just trying to save you time here, and importantly, avoid you being disappointed if your change isn't accepted.
|
||||
|
||||
## Types of Contributions
|
||||
|
||||
Contributions can include:
|
||||
|
||||
- **Code improvements:** Fixing bugs or adding new features.
|
||||
- **Documentation updates:** Enhancing clarity or adding missing information.
|
||||
- **Feature requests:** Suggesting new capabilities or integrations.
|
||||
- **Bug reports:** Identifying and reporting issues.
|
||||
|
||||
## AI
|
||||
|
||||
To ensure the quality and maintainability of the codebase, **we do not accept Pull Requests generated primarily by AI tools** (e.g., ChatGPT, GitHub Copilot, Claude Code, etc.).
|
||||
All contributions must be the original work of the author. We reserve the right to close any PR that appears to be AI-generated without further review.
|
||||
|
||||
## How to contribute
|
||||
|
||||
This project follows a Fork/Feature Branch/Pull Request model. If you're not familiar with this, here's how it works:
|
||||
|
||||
1. **Fork the project:** Create a personal copy of the repository on your GitHub account.
|
||||
2. **Clone your fork:** Bring a copy of your fork to your local machine.
|
||||
```bash
|
||||
git clone https://github.com/YOUR_USERNAME/postiz.git
|
||||
```
|
||||
3. **Create a new branch**: Start a new branch for your changes
|
||||
```bash
|
||||
git checkout -b feature/your-feature-name
|
||||
```
|
||||
4. **Make your changes**: Implement the changes you wish to contribute.
|
||||
5. **Push your changes**: Upload your changes to your fork.
|
||||
```bash
|
||||
git push -u origin feature/your-feature-name
|
||||
```
|
||||
6. **Create a pull request**: Propose your changes **to the main branch**.
|
||||
|
||||
# Need Help?
|
||||
|
||||
Again, do check the [developer guide](https://docs.postiz.com/developer-guide). Much of what you probably need to know is in there.
|
||||
|
||||
If you encounter any issues, please visit our [support page](https://docs.postiz.com/support) or check the community forums. Your contributions help make Postiz better!
|
||||
@@ -0,0 +1,28 @@
|
||||
FROM node:22.20-bookworm-slim
|
||||
ARG NEXT_PUBLIC_VERSION
|
||||
ENV NEXT_PUBLIC_VERSION=$NEXT_PUBLIC_VERSION
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
g++ \
|
||||
make \
|
||||
python3-pip \
|
||||
bash \
|
||||
nginx \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN addgroup --system www \
|
||||
&& adduser --system --ingroup www --home /www --shell /usr/sbin/nologin www \
|
||||
&& mkdir -p /www \
|
||||
&& chown -R www:www /www /var/lib/nginx
|
||||
|
||||
|
||||
RUN npm --no-update-notifier --no-fund --global install pnpm@10.6.1 pm2
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY . /app
|
||||
COPY var/docker/nginx.conf /etc/nginx/nginx.conf
|
||||
|
||||
RUN pnpm install
|
||||
RUN NODE_OPTIONS="--max-old-space-size=4096" pnpm run build
|
||||
|
||||
CMD ["sh", "-c", "nginx && pnpm run pm2"]
|
||||
@@ -0,0 +1,121 @@
|
||||
# Fiduciary License Agreement 2.1
|
||||
|
||||
Based on the
|
||||
|
||||
## Individual Contributor License Agreement (ICLA)
|
||||
|
||||
Thank you for your interest in contributing to GitroomHQ's Postiz ("We" or "Us").
|
||||
|
||||
The purpose of this contributor agreement ("Agreement") is to clarify and document the rights granted by contributors to Us. To make this document effective, please follow the instructions at https://contribute.postiz.com/p/postiz/cla.
|
||||
|
||||
### Preamble
|
||||
|
||||
Software is deeply embedded in all aspects of our lives and it is important that it empower, rather than restrict us. Free Software gives everybody the rights to use, understand, adapt and share software. These rights help support other fundamental freedoms like freedom of speech, press and privacy.
|
||||
|
||||
Development of Free Software can follow many patterns. In some cases whole development is handled by a sole programmer or a small group of people. But usually, the creation and maintenance of software is a complex process that requires the contribution of many individuals. This also affects who owns the rights to the software. In the latter case, rights in software are owned jointly by a great number of individuals.
|
||||
|
||||
To tackle this issue some projects require a full copyright assignment to be signed by all contributors. The problem with such assignments is that they often lack checks and balances that would protect the contributors from potential abuse of power from the new copyright holder.
|
||||
|
||||
FSFE's Fiduciary License Agreement (FLA) was created by the Free Software Foundation Europe e.V. with just that in mind – to concentrate all deciding power within one entity and prevent fragmentation of rights on one hand, while on the other preventing that single entity from abusing its power. The main aim is to ensure that the software covered under the FLA will forever remain Free Software.
|
||||
|
||||
This process only serves for the transfer of economic rights. So-called moral rights (e.g. author's right to be identified as author) remain with the original author(s) and are inalienable.
|
||||
|
||||
### How to use this FLA
|
||||
|
||||
If You are an employee and have created the Contribution as part of Your employment, You need to have Your employer approve this Agreement or sign the Entity version of this document. If You do not own the Copyright in Your Contribution, any other author of the Contribution should also sign this. In any event, please contact Us at nevo@postiz.com.
|
||||
|
||||
### Definitions
|
||||
|
||||
**"You"** means the individual Copyright owner who Submits a Contribution to Us.
|
||||
|
||||
**"Legal Entity"** means an entity that is not a natural person.
|
||||
|
||||
**"Affiliate"** means any other Legal Entity that controls, is controlled by, or under common control with that Legal Entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such Legal Entity, whether by contract or otherwise, (ii) ownership of fifty percent (50%) or more of the outstanding shares or securities that vote to elect the management or other persons who direct such Legal Entity, or (iii) beneficial ownership of such entity.
|
||||
|
||||
**"Contribution"** means any original work of authorship, including any original modifications or additions to an existing work of authorship, Submitted for inclusion into Material by You to Us, in which You own the Copyright.
|
||||
|
||||
**"Copyright"** means all rights protecting works of authorship, including copyright, moral and neighboring rights, as appropriate, for the full term of their existence.
|
||||
|
||||
**"Material"** means the software and/or documentation of Postiz that We make available to third parties.
|
||||
|
||||
**"Submit"** means any act by which a Contribution is transferred to Us by You by means of tangible or intangible media, including but not limited to electronic mailing lists, source code control systems, and issue tracking systems, but excluding any transfer that is conspicuously marked or otherwise designated in writing by You as "Not a Contribution."
|
||||
|
||||
**"Documentation"** means any non-software portion of a Contribution.
|
||||
|
||||
### License grant
|
||||
|
||||
#### Copyright license to Us
|
||||
|
||||
Subject to the terms and conditions of this Agreement, You hereby grant to Us a worldwide, royalty-free, exclusive, perpetual and irrevocable (except as stated in Section "Term") license, with the right to transfer an unlimited number of non-exclusive licenses or to grant sublicenses to third parties, under the Copyright covering the Contribution to use the Contribution by all means, including, but not limited to:
|
||||
|
||||
* publish the Contribution,
|
||||
* modify the Contribution,
|
||||
* prepare derivative works based upon or containing the Contribution and/or to combine the Contribution with other Materials,
|
||||
* reproduce the Contribution in original or modified form,
|
||||
* distribute, to make the Contribution available to the public, display and publicly perform the Contribution in original or modified form.
|
||||
|
||||
#### Moral rights
|
||||
|
||||
Moral Rights remain unaffected to the extent they are recognized and not waivable by applicable law. Notwithstanding, You may add Your name to the attribution mechanism customarily used in the Materials You Contribute to, such as the header of the source code files of Your Contribution, and We will respect this attribution when using Your Contribution.
|
||||
|
||||
#### Copyright license back to You
|
||||
|
||||
Upon such grant of rights to Us, We immediately grant to You a worldwide, royalty-free, non-exclusive, perpetual and irrevocable license, with the right to transfer an unlimited number of non-exclusive licenses or to grant sublicenses to third parties, under the Copyright covering the Contribution to use the Contribution by all means, including, but not limited to:
|
||||
|
||||
* publish the Contribution,
|
||||
* modify the Contribution,
|
||||
* prepare derivative works based upon or containing the Contribution and/or to combine the Contribution with other Materials,
|
||||
* reproduce the Contribution in original or modified form,
|
||||
* distribute, to make the Contribution available to the public, display and publicly perform the Contribution in original or modified form.
|
||||
|
||||
This license back is limited to the Contribution and does not provide any rights to the Material.
|
||||
|
||||
### Patents
|
||||
|
||||
#### Patent license
|
||||
|
||||
Subject to the terms and conditions of this Agreement You hereby grant to Us and to recipients of Materials distributed by Us a worldwide, royalty-free, non-exclusive, perpetual and irrevocable (except as stated in Subsection "Revocation of patent license") patent license, with the right to transfer an unlimited number of non-exclusive licenses or to grant sublicenses to third parties, to make, have made, use, sell, offer for sale, import and otherwise transfer the Contribution and the Contribution in combination with any Material (and portions of such combination). This license applies to all patents owned or controlled by You, whether already acquired or hereafter acquired, that would be infringed by making, having made, using, selling, offering for sale, importing or otherwise transferring of Your Contribution(s) alone or by combination of Your Contribution(s) with any Material.
|
||||
|
||||
#### Revocation of patent license
|
||||
|
||||
You reserve the right to revoke the patent license stated in Subsection "Patent license" if We make any infringement claim that is targeted at Your Contribution and not asserted for a Defensive Purpose. An assertion of claims of the Patents shall be considered for a "Defensive Purpose" if the claims are asserted against an entity that has filed, maintained, threatened, or voluntarily participated in a patent infringement lawsuit against Us or any of Our licensees.
|
||||
|
||||
### License obligations by Us
|
||||
|
||||
We may, but are under no obligation to, include the Contribution You Submitted to Us into the Material.
|
||||
|
||||
We agree to (sub)license the Contribution or any Materials containing, based on or derived from Your Contribution under the terms of any licenses that qualify as [Free Software](https://www.gnu.org/philosophy/free-sw.html) as defined by the Free Software Foundation and at the same time qualify as [Open Source](https://opensource.org/osd) as defined by the Open Source Initiative. For clarification, should We make available any Material under a non-free or non-open license, We must make a version of such Material available under a free and open license too.
|
||||
|
||||
We agree to license patents owned or controlled by You only to the extent necessary to (sub)license Your Contribution(s) and the combination of Your Contribution(s) with the Material under the terms of any licenses the Free Software Foundation classifies as Free Software licenses and which are approved by the Open Source Initiative as Open Source licenses.
|
||||
|
||||
### Disclaimer
|
||||
|
||||
**We acknowledge that You provide the Contribution "as is".** **More particularly, You disclaim all express or implied warranties including, without limitation, any implied warranty of satisfactory quality, fitness for a particular purpose and non-infringement. To the extent that any such warranties cannot be disclaimed, such warranty is limited in duration and extent to the minimum period and extent permitted by law.**
|
||||
|
||||
### Consequential damage waiver
|
||||
|
||||
**To the maximum extent permitted by applicable law, in no event will You or We be liable for any loss of profits, loss of anticipated savings, loss of data, indirect, special, incidental, consequential and exemplary damages arising out of this Agreement regardless of the legal or equitable theory (contract, tort or otherwise) upon which the claim is based.**
|
||||
|
||||
### Approximation of disclaimer and damage waiver
|
||||
|
||||
**If the disclaimer and damage waiver mentioned in Section "Disclaimer" and Section "Consequential damage waiver" cannot be given legal effect under applicable local law, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil or contractual liability in connection with the Contribution.**
|
||||
|
||||
### Term
|
||||
|
||||
This Agreement shall come into effect upon Your acceptance of the terms and conditions.
|
||||
|
||||
This Agreement shall apply for the term of the copyright and patents licensed here. However, You shall have the right to terminate the Agreement if We do not fulfill the obligations as set forth in Section "License obligations by Us". Such termination must be made in writing.
|
||||
|
||||
In the event of a termination of this Agreement Sections "Disclaimer", "Term" and "Miscellaneous" shall survive such termination and shall remain in full force thereafter. For the avoidance of doubt, Free and Open Source Software (sub)licenses that have already been granted for Contributions at the date of the termination shall remain in full force after the termination of this Agreement.
|
||||
|
||||
### Miscellaneous
|
||||
|
||||
This Agreement and all disputes, claims, actions, suits or other proceedings arising out of this agreement or relating in any way to it shall be governed by the laws of Germany, excluding its private international law provisions.
|
||||
|
||||
This Agreement sets out the entire agreement between You and Us for Your Contributions to Us and overrides all other agreements or understandings.
|
||||
|
||||
In case of Your death, this agreement shall continue with Your heirs. In case of more than one heir, all heirs must exercise their rights through a commonly authorized person.
|
||||
|
||||
If any provision of this Agreement is found void and unenforceable, such provision will be replaced to the extent possible with a provision that comes closest to the meaning of the original provision and that is enforceable. The terms and conditions set forth in this Agreement shall apply notwithstanding any failure of essential purpose of this Agreement or any limited remedy to the maximum extent possible under law.
|
||||
|
||||
You agree to notify Us of any facts or circumstances of which You become aware that would make Your representations under this Agreement inaccurate in any respect.
|
||||
@@ -0,0 +1,96 @@
|
||||
// Declarative Pipeline for building Node.js application and running SonarQube analysis triggered by a push event.
|
||||
pipeline {
|
||||
// Defines the execution environment. Using 'agent any' to ensure an agent is available.
|
||||
agent any
|
||||
|
||||
// Global environment block removed to prevent Groovy scoping issues with manual path calculation.
|
||||
|
||||
stages {
|
||||
// Stage 1: Checkout the code (Relies on the initial SCM checkout done by Jenkins)
|
||||
stage('Source Checkout') {
|
||||
steps {
|
||||
echo "Workspace already populated by the initial SCM checkout. Proceeding."
|
||||
}
|
||||
}
|
||||
|
||||
// Stage 2: Setup Node.js v20 and install pnpm
|
||||
stage('Setup Environment and Tools') {
|
||||
steps {
|
||||
sh '''
|
||||
echo "Ensuring required utilities and Node.js are installed..."
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y curl unzip nodejs
|
||||
|
||||
# 1. Install Node.js v20
|
||||
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
|
||||
sudo apt-get install -y nodejs
|
||||
echo "Node.js version: \$(node -v)"
|
||||
|
||||
# 2. Install pnpm globally (version 8)
|
||||
npm install -g pnpm@8
|
||||
echo "pnpm version: \$(pnpm -v)"
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
||||
// Stage 3: Install dependencies and build the application
|
||||
stage('Install and Build') {
|
||||
steps {
|
||||
sh 'pnpm install'
|
||||
sh 'pnpm run build'
|
||||
}
|
||||
}
|
||||
|
||||
// Stage 4: Run SonarQube analysis: Install scanner, get version, and execute.
|
||||
stage('SonarQube Analysis') {
|
||||
steps {
|
||||
script {
|
||||
// 1. Get the short 8-character commit SHA for project versioning
|
||||
def commitShaShort = sh(returnStdout: true, script: 'git rev-parse --short=8 HEAD').trim()
|
||||
echo "Commit SHA (short) is: ${commitShaShort}"
|
||||
|
||||
// --- 2. MANUALLY INSTALL THE SONAR SCANNER CLI LOCALLY IN THIS STAGE ---
|
||||
sh """
|
||||
echo "Manually downloading and installing Sonar Scanner CLI..."
|
||||
|
||||
# Download the stable scanner CLI package
|
||||
curl -sS -o sonar-scanner.zip \
|
||||
"https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-4.7.0.2747.zip"
|
||||
|
||||
# Added -o flag to force overwrite and prevent interactive prompt failure
|
||||
unzip -o -q sonar-scanner.zip -d .
|
||||
"""
|
||||
|
||||
// 3. Find the extracted directory name and capture the full absolute bin path in Groovy
|
||||
// This is defined locally and used directly, avoiding environment variable issues.
|
||||
def scannerBinPath = sh(
|
||||
returnStdout: true,
|
||||
script: '''
|
||||
SCANNER_DIR=$(find . -maxdepth 1 -type d -name "sonar-scanner*" | head -n 1)
|
||||
# Get the full absolute path to the executable file
|
||||
echo \$(pwd)/\${SCANNER_DIR}/bin/sonar-scanner
|
||||
'''
|
||||
).trim()
|
||||
|
||||
echo "Scanner executable path captured: ${scannerBinPath}"
|
||||
|
||||
// 4. Use withSonarQubeEnv to set up the secure variables (HOST and TOKEN)
|
||||
withSonarQubeEnv(installationName: 'SonarQube-Server') {
|
||||
// 5. Execute the scanner using the Groovy variable directly.
|
||||
sh """
|
||||
echo "Starting SonarQube Analysis for project version: ${commitShaShort}"
|
||||
|
||||
# Execute the full, absolute path captured in the Groovy variable.
|
||||
'${scannerBinPath}' \\
|
||||
-Dsonar.projectVersion=${commitShaShort} \\
|
||||
-Dsonar.sources=.
|
||||
|
||||
# SONAR_HOST_URL and SONAR_TOKEN are automatically passed as environment variables
|
||||
# by the withSonarQubeEnv block.
|
||||
"""
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
// Declarative Pipeline for building Node.js application and running SonarQube analysis for a Pull Request.
|
||||
pipeline {
|
||||
// Defines the execution environment. Using 'agent any' to ensure an agent is available.
|
||||
agent any
|
||||
|
||||
// Environment variables that hold PR details, provided by Jenkins Multibranch setup.
|
||||
environment {
|
||||
// FIX: Environment variables must be quoted or wrapped in a function call.
|
||||
// We quote the 'env.CHANGE_ID' reference to fix the compilation error.
|
||||
PR_KEY = "${env.CHANGE_ID}"
|
||||
PR_BRANCH = "${env.CHANGE_BRANCH}"
|
||||
PR_BASE = "${env.CHANGE_TARGET}"
|
||||
}
|
||||
|
||||
stages {
|
||||
// Stage 1: Checkout the code (Relies on the initial SCM checkout done by Jenkins)
|
||||
stage('Source Checkout') {
|
||||
steps {
|
||||
echo "Workspace already populated by the initial SCM checkout. Proceeding."
|
||||
}
|
||||
}
|
||||
|
||||
// Stage 2: Setup Node.js v20, install pnpm, and install required tools (curl, unzip)
|
||||
stage('Setup Environment and Tools') {
|
||||
steps {
|
||||
sh '''
|
||||
echo "Ensuring required utilities and Node.js are installed..."
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y curl unzip nodejs
|
||||
|
||||
# 1. Install Node.js v20 (closest matching the specified version '20.17.0')
|
||||
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
|
||||
sudo apt-get install -y nodejs
|
||||
echo "Node.js version: \$(node -v)"
|
||||
|
||||
# 2. Install pnpm globally (version 8)
|
||||
npm install -g pnpm@8
|
||||
echo "pnpm version: \$(pnpm -v)"
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
||||
// Stage 3: Install dependencies and build the application
|
||||
stage('Install and Build') {
|
||||
steps {
|
||||
sh 'pnpm install'
|
||||
sh 'pnpm run build'
|
||||
}
|
||||
}
|
||||
|
||||
// Stage 4: Run SonarQube PR analysis: Install scanner locally, get version, and execute.
|
||||
stage('SonarQube Pull Request Analysis') {
|
||||
steps {
|
||||
script {
|
||||
// 1. Get the short 8-character commit SHA for project versioning
|
||||
def commitShaShort = sh(returnStdout: true, script: 'git rev-parse --short=8 HEAD').trim()
|
||||
echo "Commit SHA (short) is: ${commitShaShort}"
|
||||
|
||||
// --- 2. MANUALLY INSTALL THE SONAR SCANNER CLI LOCALLY ---
|
||||
sh """
|
||||
echo "Manually downloading and installing Sonar Scanner CLI..."
|
||||
curl -sS -o sonar-scanner.zip \
|
||||
"https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-4.7.0.2747.zip"
|
||||
unzip -o -q sonar-scanner.zip -d .
|
||||
"""
|
||||
|
||||
// 3. Find the extracted directory name and capture the full absolute executable path.
|
||||
def scannerBinPath = sh(
|
||||
returnStdout: true,
|
||||
script: '''
|
||||
SCANNER_DIR=$(find . -maxdepth 1 -type d -name "sonar-scanner*" | head -n 1)
|
||||
# Get the full absolute path to the executable file
|
||||
echo \$(pwd)/\${SCANNER_DIR}/bin/sonar-scanner
|
||||
'''
|
||||
).trim()
|
||||
|
||||
echo "Scanner executable path captured: ${scannerBinPath}"
|
||||
|
||||
// 4. Use withSonarQubeEnv to set up the secure variables (HOST and TOKEN)
|
||||
withSonarQubeEnv(installationName: 'SonarQube-Server') {
|
||||
// 5. Execute the scanner using the Groovy variable directly with PR parameters.
|
||||
sh """
|
||||
echo "Starting SonarQube Pull Request Analysis for PR #${PR_KEY}"
|
||||
|
||||
'${scannerBinPath}' \\
|
||||
-Dsonar.projectVersion=${commitShaShort} \\
|
||||
-Dsonar.sources=. \\
|
||||
-Dsonar.pullrequest.key=${PR_KEY} \\
|
||||
-Dsonar.pullrequest.branch=${PR_BRANCH} \\
|
||||
-Dsonar.pullrequest.base=${PR_BASE}
|
||||
|
||||
# SONAR_HOST_URL and SONAR_TOKEN are automatically passed as environment variables
|
||||
# by the withSonarQubeEnv block.
|
||||
"""
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,661 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
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.
|
||||
|
||||
Postiz - Social media schedule tool
|
||||
Copyright (C) 2025 Nevo David
|
||||
|
||||
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 <https://www.gnu.org/licenses/>.
|
||||
|
||||
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
|
||||
<https://www.gnu.org/licenses/>.
|
||||
@@ -0,0 +1,148 @@
|
||||
<p align="center">
|
||||
<a href="https://postiz.com/" target="_blank">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://github.com/user-attachments/assets/765e9d72-3ee7-4a56-9d59-a2c9befe2311">
|
||||
<img alt="Postiz Logo" src="https://github.com/user-attachments/assets/f0d30d70-dddb-4142-8876-e9aa6ed1cb99" width="280"/>
|
||||
</picture>
|
||||
</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://opensource.org/license/agpl-v3">
|
||||
<img src="https://img.shields.io/badge/License-AGPL%203.0-blue.svg" alt="License">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
<h3 align="center"><strong><a href="https://github.com/gitroomhq/postiz-agent">NEW: check out Postiz agent CLI! perfect for OpenClaw and other agents</a></strong></h3>
|
||||
<div align="center">
|
||||
<strong>
|
||||
<h2>Your ultimate AI social media scheduling tool</h2><br />
|
||||
<a href="https://postiz.com">Postiz</a>: An alternative to: Buffer.com, Hypefury, Twitter Hunter, etc...<br /><br />
|
||||
</strong>
|
||||
Postiz offers everything you need to manage your social media posts,<br />build an audience, capture leads, and grow your business.
|
||||
</div>
|
||||
|
||||
<div class="flex" align="center">
|
||||
<br />
|
||||
<img alt="Instagram" src="https://postiz.com/svgs/socials/Instagram.svg" width="32">
|
||||
<img alt="Youtube" src="https://postiz.com/svgs/socials/Youtube.svg" width="32">
|
||||
<img alt="Dribbble" src="https://postiz.com/svgs/socials/Dribbble.svg" width="32">
|
||||
<img alt="Linkedin" src="https://postiz.com/svgs/socials/Linkedin.svg" width="32">
|
||||
<img alt="Reddit" src="https://postiz.com/svgs/socials/Reddit.svg" width="32">
|
||||
<img alt="TikTok" src="https://postiz.com/svgs/socials/TikTok.svg" width="32">
|
||||
<img alt="Facebook" src="https://postiz.com/svgs/socials/Facebook.svg" width="32">
|
||||
<img alt="Pinterest" src="https://postiz.com/svgs/socials/Pinterest.svg" width="32">
|
||||
<img alt="Threads" src="https://postiz.com/svgs/socials/Threads.svg" width="32">
|
||||
<img alt="X" src="https://postiz.com/svgs/socials/X.svg" width="32">
|
||||
<img alt="Slack" src="https://postiz.com/svgs/socials/Slack.svg" width="32">
|
||||
<img alt="Discord" src="https://postiz.com/svgs/socials/Discord.svg" width="32">
|
||||
<img alt="Mastodon" src="https://postiz.com/svgs/socials/Mastodon.svg" width="32">
|
||||
<img alt="Bluesky" src="https://postiz.com/svgs/socials/Bluesky.svg" width="32">
|
||||
</div>
|
||||
|
||||
<p align="center">
|
||||
<br />
|
||||
<a href="https://docs.postiz.com" rel="dofollow"><strong>Explore the docs »</strong></a>
|
||||
<br />
|
||||
|
||||
<br />
|
||||
<a href="https://youtube.com/@postizofficial" rel="dofollow"><strong>Watch the YouTube Tutorials»</strong></a>
|
||||
<br />
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://platform.postiz.com">Register</a>
|
||||
·
|
||||
<a href="https://discord.postiz.com">Join Our Discord (devs only)</a>
|
||||
·
|
||||
<a href="https://docs.postiz.com/public-api">Public API</a><br />
|
||||
</p>
|
||||
<p align="center">
|
||||
<a href="https://www.npmjs.com/package/@postiz/node">NodeJS SDK</a>
|
||||
·
|
||||
<a href="https://www.npmjs.com/package/n8n-nodes-postiz">N8N custom node</a>
|
||||
·
|
||||
<a href="https://apps.make.com/postiz">Make.com integration</a>
|
||||
</p>
|
||||
|
||||
<br /><br />
|
||||
|
||||
## 🔌 See the leading Postiz features
|
||||
|
||||
<p align="center">
|
||||
<a href="https://www.youtube.com/watch?v=BdsCVvEYgHU" target="_blank">
|
||||
<img alt="Postiz" src="https://github.com/user-attachments/assets/8b9b7939-da1a-4be5-95be-42c6fce772de" />
|
||||
</a>
|
||||
</p>
|
||||
|
||||
## ✨ Features
|
||||
|
||||
|  |  |
|
||||
| ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
|
||||
|  |  |
|
||||
|
||||
### Our Sponsors
|
||||
|
||||
| Sponsor | Logo | Description |
|
||||
|---------|:-----------------------------------------------------------------------:|-----------------|
|
||||
| [Hostinger](https://www.hostinger.com/vps/docker/postiz?ref=postiz) | <img src=".github/sponsors/hostinger.png" alt="Hostinger" width="500"/> | Hostinger is on a mission to make online success possible for anyone – from developers to aspiring bloggers and business owners |
|
||||
| [Virlo](https://dev.virlo.ai/?ref=postiz) | <img src="https://github.com/user-attachments/assets/25182598-5344-45fc-b9cd-e4cfa16aabfd" alt="Virlo" width="500"/> | Virlo is the #1 social media trend spotting and all-in-one GTM tool for teams leveraging short-form video |
|
||||
|
||||
|
||||
|
||||
# Intro
|
||||
|
||||
- Schedule all your social media posts (many AI features)
|
||||
- Measure your work with analytics.
|
||||
- Collaborate with other team members to exchange or buy posts.
|
||||
- Invite your team members to collaborate, comment, and schedule posts.
|
||||
- At the moment there is no difference between the hosted version to the self-hosted version
|
||||
- Perfect for automation (API) with platforms like N8N, Make.com, Zapier, etc.
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- Pnpm workspaces (Monorepo)
|
||||
- NextJS (React)
|
||||
- NestJS
|
||||
- Prisma (Default to PostgreSQL)
|
||||
- Temporal
|
||||
- Resend (email notifications)
|
||||
|
||||
## Quick Start
|
||||
|
||||
To have the project up and running, please follow the [Quick Start Guide](https://docs.postiz.com/quickstart)
|
||||
|
||||
## Sponsor Postiz
|
||||
|
||||
We now give a few options to Sponsor Postiz:
|
||||
- Just a donation: You like what we are building, and want to buy us some coffees so we can build faster.
|
||||
- Main Repository: Get your logo with a backlink from the main Postiz repository. Postiz has almost 3m downloads and 20k views per month.
|
||||
- Main Repository + Website: Get your logo on the central repository and the main website. Here are some metrics: - Website has 20k hits per month + 65 DR (strong backlink) - Repository has 20k hits per month + Almost 3m docker downloads.
|
||||
|
||||
Link: https://opencollective.com/postiz
|
||||
|
||||
## Postiz Compliance
|
||||
|
||||
- Postiz is an open-source, self-hosted social media scheduling tool that supports platforms like X (formerly Twitter), Bluesky, Mastodon, Discord, and others.
|
||||
- Postiz hosted service uses official, platform-approved OAuth flows.
|
||||
- Postiz does not automate or scrape content from social media platforms.
|
||||
- Postiz does not collect, store, or proxy API keys or access tokens from users.
|
||||
- Postiz never ask users to paste API keys into our hosted product.
|
||||
- Postiz Users always authenticate directly with the social platform (e.g., X, Discord, etc.), ensuring platform compliance and data privacy.
|
||||
|
||||
## Star History
|
||||
|
||||
[](https://www.star-history.com/#gitroomhq/postiz-app&type=date&legend=top-left)
|
||||
|
||||
## License
|
||||
|
||||
This repository's source code is available under the [AGPL-3.0 license](LICENSE).
|
||||
|
||||
<br /><br /><br />
|
||||
|
||||
<p align="center">
|
||||
<a href="https://www.g2.com/products/postiz/take_survey" target="blank"><img alt="g2" src="https://github.com/user-attachments/assets/892cb74c-0b49-4589-b2f5-fbdbf7a98f66" /></a>
|
||||
</p>
|
||||
<p align="center">
|
||||
<img src="https://github.com/snyk-labs/secure-developer-sample-repo/raw/main/badge_full.svg" alt="Secure Developer Badge Full" width="150">
|
||||
</p>
|
||||
@@ -0,0 +1,69 @@
|
||||
# Security Policy
|
||||
|
||||
## Introduction
|
||||
|
||||
The Postiz app is committed to ensuring the security and integrity of our users' data. This security policy outlines our procedures for handling security vulnerabilities and our disclosure policy.
|
||||
|
||||
## Scope
|
||||
|
||||
We, at Postiz (gitroomhq), cover the following scopes for vulnerability disclosures:
|
||||
|
||||
- The core repository for `postiz-app` (github.com/gitroomhq/postiz-app)
|
||||
- All `gitroomhq` repositories that are official components, tooling, or integrations of Postiz
|
||||
- Official Postiz container images published under `gitroomhq` on GHCR
|
||||
- Official Postiz CLI tools and NPM packages (NPM org: @postiz)
|
||||
- Postiz-Cloud related infrastructure & services. (API, Frontend, Configurations etc.)
|
||||
- Plugins for Postiz maintained within the `gitroomhq` organization
|
||||
|
||||
Vulnerabilities in third-party dependencies or user-hosted infrastructure are outside of this scope.
|
||||
|
||||
## Supported Versions
|
||||
|
||||
This project currently only supports the latest release. We recommend that users always use the latest version of the Postiz app to ensure they have the latest security patches.
|
||||
*CVE IDs will only be assigned to vulnerabilities affecting currently supported versions.*
|
||||
|
||||
## Reporting Security Vulnerabilities
|
||||
|
||||
If you discover a security vulnerability in the Postiz app, please report it through the [GitHub Security Advisory system](https://github.com/gitroomhq/postiz-app/security/advisories/new).
|
||||
|
||||
When reporting a security vulnerability, please provide as much detail as possible, including:
|
||||
|
||||
- A clear description of the vulnerability
|
||||
- Proof of concept (PoC), where possible
|
||||
- Steps to reproduce the vulnerability
|
||||
- Any relevant code or configuration files
|
||||
|
||||
If the report has immediate urgency, please contact one (or more) of the maintainers via email:
|
||||
|
||||
- @egelhaus ([E-Mail](mailto:egelhaus@ennogelhaus.de))
|
||||
|
||||
### AI Reports
|
||||
|
||||
Reports that appear to be LLM-generated without meaningful human analysis — typically lacking a working proof of concept, reproducible steps, or accurate impact assessment — will be closed without detailed response.
|
||||
|
||||
Reports that include AI-assisted analysis are welcome provided they have been validated by the reporter and include a proof of concept, reproduction steps, and impact assessment.
|
||||
|
||||
## Disclosure Guidelines
|
||||
|
||||
We follow a private disclosure policy. If you discover a security vulnerability, please report it to us privately via GitHub Security Advisories, and if immediate urgency, via email as listed above. We will respond promptly to reports of vulnerabilities and work to resolve them as quickly as possible.
|
||||
|
||||
We will not publicly disclose security vulnerabilities until a patch or fix is available to prevent malicious actors from exploiting the vulnerability before a fix is released.
|
||||
|
||||
## Security Vulnerability Response Process
|
||||
|
||||
We take security vulnerabilities seriously and will respond promptly to reports of vulnerabilities. Our response process includes:
|
||||
|
||||
- Investigating the report and verifying the vulnerability.
|
||||
- Developing a patch or fix for the vulnerability.
|
||||
- Releasing the patch or fix as soon as possible.
|
||||
- Notifying users of the vulnerability and the patch or fix.
|
||||
|
||||
## Response Timelines
|
||||
|
||||
We aim to follow these timelines:
|
||||
|
||||
- **Initial Acknowledgment:** Within 72 hours of initial report.
|
||||
- **Completed Triage / Verification:** Within 7 days of initial acknowledgment.
|
||||
- **Critical Issue Remediation:** Within 90 days of completed triage.
|
||||
- **Non-Critical Issue Remediation:** Within 180 days of completed triage.
|
||||
- **CVE Publication:** Within 24 hours of remediation release.
|
||||
@@ -0,0 +1,8 @@
|
||||
dist/
|
||||
node_modules/
|
||||
[._]*.s[a-v][a-z]
|
||||
[._]*.sw[a-p]
|
||||
[._]s[a-rt-v][a-z]
|
||||
[._]ss[a-gi-z]
|
||||
[._]sw[a-p]
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/nest-cli",
|
||||
"collection": "@nestjs/schematics",
|
||||
"monorepo": false,
|
||||
"sourceRoot": "src",
|
||||
"entryFile": "../../dist/backend/apps/backend/src/main",
|
||||
"language": "ts",
|
||||
"generateOptions": {
|
||||
"spec": false
|
||||
},
|
||||
"compilerOptions": {
|
||||
"manualRestart": true,
|
||||
"tsConfigPath": "./tsconfig.build.json",
|
||||
"webpack": false,
|
||||
"deleteOutDir": true,
|
||||
"assets": [],
|
||||
"watchAssets": false,
|
||||
"plugins": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "postiz-backend",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"scripts": {
|
||||
"dev": "dotenv -e ../../.env -- nest start --watch --entryFile=./apps/backend/src/main",
|
||||
"build": "cross-env NODE_ENV=production nest build",
|
||||
"start": "dotenv -e ../../.env -- node --experimental-require-module ./dist/apps/backend/src/main.js",
|
||||
"pm2": "pm2 start pnpm --name backend -- start"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC"
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
|
||||
import { AuthController } from '@gitroom/backend/api/routes/auth.controller';
|
||||
import { AuthService } from '@gitroom/backend/services/auth/auth.service';
|
||||
import { UsersController } from '@gitroom/backend/api/routes/users.controller';
|
||||
import { AuthMiddleware } from '@gitroom/backend/services/auth/auth.middleware';
|
||||
import { StripeController } from '@gitroom/backend/api/routes/stripe.controller';
|
||||
import { StripeService } from '@gitroom/nestjs-libraries/services/stripe.service';
|
||||
import { AnalyticsController } from '@gitroom/backend/api/routes/analytics.controller';
|
||||
import { PoliciesGuard } from '@gitroom/backend/services/auth/permissions/permissions.guard';
|
||||
import { PermissionsService } from '@gitroom/backend/services/auth/permissions/permissions.service';
|
||||
import { IntegrationsController } from '@gitroom/backend/api/routes/integrations.controller';
|
||||
import { IntegrationManager } from '@gitroom/nestjs-libraries/integrations/integration.manager';
|
||||
import { SettingsController } from '@gitroom/backend/api/routes/settings.controller';
|
||||
import { PostsController } from '@gitroom/backend/api/routes/posts.controller';
|
||||
import { MediaController } from '@gitroom/backend/api/routes/media.controller';
|
||||
import { UploadModule } from '@gitroom/nestjs-libraries/upload/upload.module';
|
||||
import { BillingController } from '@gitroom/backend/api/routes/billing.controller';
|
||||
import { NotificationsController } from '@gitroom/backend/api/routes/notifications.controller';
|
||||
import { OpenaiService } from '@gitroom/nestjs-libraries/openai/openai.service';
|
||||
import { ExtractContentService } from '@gitroom/nestjs-libraries/openai/extract.content.service';
|
||||
import { CodesService } from '@gitroom/nestjs-libraries/services/codes.service';
|
||||
import { CopilotController } from '@gitroom/backend/api/routes/copilot.controller';
|
||||
import { PublicController } from '@gitroom/backend/api/routes/public.controller';
|
||||
import { RootController } from '@gitroom/backend/api/routes/root.controller';
|
||||
import { TrackService } from '@gitroom/nestjs-libraries/track/track.service';
|
||||
import { ShortLinkService } from '@gitroom/nestjs-libraries/short-linking/short.link.service';
|
||||
import { WebhookController } from '@gitroom/backend/api/routes/webhooks.controller';
|
||||
import { SignatureController } from '@gitroom/backend/api/routes/signature.controller';
|
||||
import { AutopostController } from '@gitroom/backend/api/routes/autopost.controller';
|
||||
import { SetsController } from '@gitroom/backend/api/routes/sets.controller';
|
||||
import { ThirdPartyController } from '@gitroom/backend/api/routes/third-party.controller';
|
||||
import { MonitorController } from '@gitroom/backend/api/routes/monitor.controller';
|
||||
import { NoAuthIntegrationsController } from '@gitroom/backend/api/routes/no.auth.integrations.controller';
|
||||
import { EnterpriseController } from '@gitroom/backend/api/routes/enterprise.controller';
|
||||
import { OAuthAppController } from '@gitroom/backend/api/routes/oauth-app.controller';
|
||||
import { ApprovedAppsController } from '@gitroom/backend/api/routes/approved-apps.controller';
|
||||
import { OAuthController, OAuthAuthorizedController } from '@gitroom/backend/api/routes/oauth.controller';
|
||||
import { AnnouncementsController } from '@gitroom/backend/api/routes/announcements.controller';
|
||||
import { AdminController } from '@gitroom/backend/api/routes/admin.controller';
|
||||
import { AuthProviderManager } from '@gitroom/backend/services/auth/providers/providers.manager';
|
||||
import { GithubProvider } from '@gitroom/backend/services/auth/providers/github.provider';
|
||||
import { GoogleProvider } from '@gitroom/backend/services/auth/providers/google.provider';
|
||||
import { FarcasterProvider } from '@gitroom/backend/services/auth/providers/farcaster.provider';
|
||||
import { WalletProvider } from '@gitroom/backend/services/auth/providers/wallet.provider';
|
||||
import { OauthProvider } from '@gitroom/backend/services/auth/providers/oauth.provider';
|
||||
|
||||
const authenticatedController = [
|
||||
UsersController,
|
||||
AnalyticsController,
|
||||
IntegrationsController,
|
||||
SettingsController,
|
||||
PostsController,
|
||||
MediaController,
|
||||
BillingController,
|
||||
NotificationsController,
|
||||
CopilotController,
|
||||
WebhookController,
|
||||
SignatureController,
|
||||
AutopostController,
|
||||
SetsController,
|
||||
ThirdPartyController,
|
||||
OAuthAppController,
|
||||
ApprovedAppsController,
|
||||
OAuthAuthorizedController,
|
||||
AnnouncementsController,
|
||||
AdminController,
|
||||
];
|
||||
@Module({
|
||||
imports: [UploadModule],
|
||||
controllers: [
|
||||
RootController,
|
||||
StripeController,
|
||||
AuthController,
|
||||
PublicController,
|
||||
MonitorController,
|
||||
EnterpriseController,
|
||||
NoAuthIntegrationsController,
|
||||
OAuthController,
|
||||
...authenticatedController,
|
||||
],
|
||||
providers: [
|
||||
AuthService,
|
||||
StripeService,
|
||||
OpenaiService,
|
||||
ExtractContentService,
|
||||
AuthMiddleware,
|
||||
PoliciesGuard,
|
||||
PermissionsService,
|
||||
CodesService,
|
||||
IntegrationManager,
|
||||
TrackService,
|
||||
ShortLinkService,
|
||||
AuthProviderManager,
|
||||
GithubProvider,
|
||||
GoogleProvider,
|
||||
FarcasterProvider,
|
||||
WalletProvider,
|
||||
OauthProvider,
|
||||
],
|
||||
get exports() {
|
||||
return [...this.imports, ...this.providers];
|
||||
},
|
||||
})
|
||||
export class ApiModule implements NestModule {
|
||||
configure(consumer: MiddlewareConsumer) {
|
||||
consumer.apply(AuthMiddleware).forRoutes(...authenticatedController);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
HttpException,
|
||||
Query,
|
||||
} from '@nestjs/common';
|
||||
import { GetUserFromRequest } from '@gitroom/nestjs-libraries/user/user.from.request';
|
||||
import { User } from '@prisma/client';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { ErrorsService } from '@gitroom/nestjs-libraries/database/prisma/errors/errors.service';
|
||||
import { AdminStatsService } from '@gitroom/nestjs-libraries/database/prisma/admin-stats/admin-stats.service';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
@ApiTags('Admin')
|
||||
@Controller('/admin')
|
||||
export class AdminController {
|
||||
constructor(
|
||||
private _errorsService: ErrorsService,
|
||||
private _adminStatsService: AdminStatsService
|
||||
) {}
|
||||
|
||||
private assertSuperAdmin(user: User) {
|
||||
if (!user?.isSuperAdmin) {
|
||||
throw new HttpException('Unauthorized', 400);
|
||||
}
|
||||
}
|
||||
|
||||
@Get('/errors')
|
||||
async listErrors(
|
||||
@GetUserFromRequest() user: User,
|
||||
@Query('page') page?: string,
|
||||
@Query('limit') limit?: string,
|
||||
@Query('platform') platform?: string,
|
||||
@Query('email') email?: string,
|
||||
@Query('unknownFirst') unknownFirst?: string
|
||||
) {
|
||||
this.assertSuperAdmin(user);
|
||||
return this._errorsService.listErrors({
|
||||
page: page ? parseInt(page, 10) : 0,
|
||||
limit: limit ? parseInt(limit, 10) : 20,
|
||||
platform: platform || undefined,
|
||||
email: email || undefined,
|
||||
unknownFirst: unknownFirst === 'true' || unknownFirst === '1',
|
||||
});
|
||||
}
|
||||
|
||||
@Get('/errors/platforms')
|
||||
async listPlatforms(@GetUserFromRequest() user: User) {
|
||||
this.assertSuperAdmin(user);
|
||||
return this._errorsService.listPlatforms();
|
||||
}
|
||||
|
||||
@Get('/stats')
|
||||
async getStats(
|
||||
@GetUserFromRequest() user: User,
|
||||
@Query('from') from?: string,
|
||||
@Query('to') to?: string,
|
||||
@Query('unknownOnly') unknownOnly?: string
|
||||
) {
|
||||
this.assertSuperAdmin(user);
|
||||
|
||||
const fromDate = from ? dayjs(from) : dayjs().subtract(30, 'day');
|
||||
const toDate = to ? dayjs(to) : dayjs();
|
||||
|
||||
return this._adminStatsService.getStats({
|
||||
from: fromDate.startOf('day').toDate(),
|
||||
to: toDate.endOf('day').toDate(),
|
||||
unknownOnly: unknownOnly === 'true' || unknownOnly === '1',
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { Controller, Get, Param, Query } from '@nestjs/common';
|
||||
import { Organization } from '@prisma/client';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { IntegrationService } from '@gitroom/nestjs-libraries/database/prisma/integrations/integration.service';
|
||||
import { PostsService } from '@gitroom/nestjs-libraries/database/prisma/posts/posts.service';
|
||||
|
||||
@ApiTags('Analytics')
|
||||
@Controller('/analytics')
|
||||
export class AnalyticsController {
|
||||
constructor(
|
||||
private _integrationService: IntegrationService,
|
||||
private _postsService: PostsService
|
||||
) {}
|
||||
|
||||
@Get('/:integration')
|
||||
async getIntegration(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('integration') integration: string,
|
||||
@Query('date') date: string
|
||||
) {
|
||||
return this._integrationService.checkAnalytics(org, integration, date);
|
||||
}
|
||||
|
||||
@Get('/post/:postId')
|
||||
async getPostAnalytics(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('postId') postId: string,
|
||||
@Query('date') date: string
|
||||
) {
|
||||
return this._postsService.checkPostAnalytics(org.id, postId, +date);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
HttpException,
|
||||
Param,
|
||||
Post,
|
||||
} from '@nestjs/common';
|
||||
import { GetUserFromRequest } from '@gitroom/nestjs-libraries/user/user.from.request';
|
||||
import { User } from '@prisma/client';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { AnnouncementsService } from '@gitroom/nestjs-libraries/database/prisma/announcements/announcements.service';
|
||||
import { AnnouncementDto } from '@gitroom/nestjs-libraries/dtos/announcements/announcements.dto';
|
||||
|
||||
@ApiTags('Announcements')
|
||||
@Controller('/announcements')
|
||||
export class AnnouncementsController {
|
||||
constructor(private _announcementsService: AnnouncementsService) {}
|
||||
|
||||
@Get('/')
|
||||
async getAnnouncements() {
|
||||
return this._announcementsService.getAnnouncements();
|
||||
}
|
||||
|
||||
@Post('/')
|
||||
async createAnnouncement(
|
||||
@GetUserFromRequest() user: User,
|
||||
@Body() body: AnnouncementDto
|
||||
) {
|
||||
if (!user.isSuperAdmin) {
|
||||
throw new HttpException('Unauthorized', 400);
|
||||
}
|
||||
return this._announcementsService.createAnnouncement(body);
|
||||
}
|
||||
|
||||
@Delete('/:id')
|
||||
async deleteAnnouncement(
|
||||
@GetUserFromRequest() user: User,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
if (!user.isSuperAdmin) {
|
||||
throw new HttpException('Unauthorized', 400);
|
||||
}
|
||||
return this._announcementsService.deleteAnnouncement(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { Controller, Delete, Get, Param } from '@nestjs/common';
|
||||
import { GetUserFromRequest } from '@gitroom/nestjs-libraries/user/user.from.request';
|
||||
import { User } from '@prisma/client';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { OAuthService } from '@gitroom/nestjs-libraries/database/prisma/oauth/oauth.service';
|
||||
|
||||
@ApiTags('Approved Apps')
|
||||
@Controller('/user/approved-apps')
|
||||
export class ApprovedAppsController {
|
||||
constructor(private _oauthService: OAuthService) {}
|
||||
|
||||
@Get('/')
|
||||
async list(@GetUserFromRequest() user: User) {
|
||||
return this._oauthService.getApprovedApps(user.id);
|
||||
}
|
||||
|
||||
@Delete('/:id')
|
||||
async revoke(
|
||||
@GetUserFromRequest() user: User,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
return this._oauthService.revokeApp(user.id, id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Param,
|
||||
Post,
|
||||
Query,
|
||||
Req,
|
||||
Res,
|
||||
} from '@nestjs/common';
|
||||
import { Response, Request } from 'express';
|
||||
|
||||
import { CreateOrgUserDto } from '@gitroom/nestjs-libraries/dtos/auth/create.org.user.dto';
|
||||
import { LoginUserDto } from '@gitroom/nestjs-libraries/dtos/auth/login.user.dto';
|
||||
import { AuthService } from '@gitroom/backend/services/auth/auth.service';
|
||||
import { ForgotReturnPasswordDto } from '@gitroom/nestjs-libraries/dtos/auth/forgot-return.password.dto';
|
||||
import { ForgotPasswordDto } from '@gitroom/nestjs-libraries/dtos/auth/forgot.password.dto';
|
||||
import { ResendActivationDto } from '@gitroom/nestjs-libraries/dtos/auth/resend-activation.dto';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { getCookieUrlFromDomain } from '@gitroom/helpers/subdomain/subdomain.management';
|
||||
import { EmailService } from '@gitroom/nestjs-libraries/services/email.service';
|
||||
import { RealIP } from 'nestjs-real-ip';
|
||||
import { UserAgent } from '@gitroom/nestjs-libraries/user/user.agent';
|
||||
import { Provider } from '@prisma/client';
|
||||
import * as Sentry from '@sentry/nestjs';
|
||||
|
||||
@ApiTags('Auth')
|
||||
@Controller('/auth')
|
||||
export class AuthController {
|
||||
constructor(
|
||||
private _authService: AuthService,
|
||||
private _emailService: EmailService
|
||||
) {}
|
||||
|
||||
@Get('/can-register')
|
||||
async canRegister() {
|
||||
return {
|
||||
register: await this._authService.canRegister(Provider.LOCAL as string),
|
||||
};
|
||||
}
|
||||
|
||||
@Post('/register')
|
||||
async register(
|
||||
@Req() req: Request,
|
||||
@Body() body: CreateOrgUserDto,
|
||||
@Res({ passthrough: false }) response: Response,
|
||||
@RealIP() ip: string,
|
||||
@UserAgent() userAgent: string
|
||||
) {
|
||||
try {
|
||||
const getOrgFromCookie = this._authService.getOrgFromCookie(
|
||||
req?.cookies?.org
|
||||
);
|
||||
|
||||
const { jwt, addedOrg } = await this._authService.routeAuth(
|
||||
body.provider,
|
||||
body,
|
||||
ip,
|
||||
userAgent,
|
||||
getOrgFromCookie
|
||||
);
|
||||
|
||||
const activationRequired =
|
||||
body.provider === 'LOCAL' && this._emailService.hasProvider();
|
||||
|
||||
if (activationRequired) {
|
||||
response.header('activate', 'true');
|
||||
response.status(200).json({ activate: true });
|
||||
return;
|
||||
}
|
||||
|
||||
response.cookie('auth', jwt, {
|
||||
domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),
|
||||
...(!process.env.NOT_SECURED
|
||||
? {
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
}
|
||||
: {}),
|
||||
expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),
|
||||
});
|
||||
|
||||
if (process.env.NOT_SECURED) {
|
||||
response.header('auth', jwt);
|
||||
}
|
||||
|
||||
if (typeof addedOrg !== 'boolean' && addedOrg?.organizationId) {
|
||||
response.cookie('showorg', addedOrg.organizationId, {
|
||||
domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),
|
||||
...(!process.env.NOT_SECURED
|
||||
? {
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
}
|
||||
: {}),
|
||||
expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),
|
||||
});
|
||||
|
||||
if (process.env.NOT_SECURED) {
|
||||
response.header('showorg', addedOrg.organizationId);
|
||||
}
|
||||
}
|
||||
|
||||
Sentry.metrics.count('new_user', 1);
|
||||
response.header('onboarding', 'true');
|
||||
response.status(200).json({
|
||||
register: true,
|
||||
});
|
||||
} catch (e: any) {
|
||||
response.status(400).send(e.message);
|
||||
}
|
||||
}
|
||||
|
||||
@Post('/login')
|
||||
async login(
|
||||
@Req() req: Request,
|
||||
@Body() body: LoginUserDto,
|
||||
@Res({ passthrough: false }) response: Response,
|
||||
@RealIP() ip: string,
|
||||
@UserAgent() userAgent: string
|
||||
) {
|
||||
try {
|
||||
const getOrgFromCookie = this._authService.getOrgFromCookie(
|
||||
req?.cookies?.org
|
||||
);
|
||||
|
||||
const { jwt, addedOrg } = await this._authService.routeAuth(
|
||||
body.provider,
|
||||
body,
|
||||
ip,
|
||||
userAgent,
|
||||
getOrgFromCookie
|
||||
);
|
||||
|
||||
response.cookie('auth', jwt, {
|
||||
domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),
|
||||
...(!process.env.NOT_SECURED
|
||||
? {
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
}
|
||||
: {}),
|
||||
expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),
|
||||
});
|
||||
|
||||
if (process.env.NOT_SECURED) {
|
||||
response.header('auth', jwt);
|
||||
}
|
||||
|
||||
if (typeof addedOrg !== 'boolean' && addedOrg?.organizationId) {
|
||||
response.cookie('showorg', addedOrg.organizationId, {
|
||||
domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),
|
||||
...(!process.env.NOT_SECURED
|
||||
? {
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
}
|
||||
: {}),
|
||||
expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),
|
||||
});
|
||||
|
||||
if (process.env.NOT_SECURED) {
|
||||
response.header('showorg', addedOrg.organizationId);
|
||||
}
|
||||
}
|
||||
|
||||
response.header('reload', 'true');
|
||||
response.status(200).json({
|
||||
login: true,
|
||||
});
|
||||
} catch (e: any) {
|
||||
response.status(400).send(e.message);
|
||||
}
|
||||
}
|
||||
|
||||
@Post('/forgot')
|
||||
async forgot(@Body() body: ForgotPasswordDto) {
|
||||
try {
|
||||
await this._authService.forgot(body.email);
|
||||
return {
|
||||
forgot: true,
|
||||
};
|
||||
} catch (e) {
|
||||
return {
|
||||
forgot: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@Post('/forgot-return')
|
||||
async forgotReturn(@Body() body: ForgotReturnPasswordDto) {
|
||||
const reset = await this._authService.forgotReturn(body);
|
||||
return {
|
||||
reset: !!reset,
|
||||
};
|
||||
}
|
||||
|
||||
@Get('/oauth-mobile-callback')
|
||||
mobileCallback(
|
||||
@Query('code') code: string,
|
||||
@Query('state') state: string,
|
||||
@Res({ passthrough: false }) response: Response
|
||||
) {
|
||||
const scheme = process.env.MOBILE_APP_SCHEME || 'postiz://auth/callback';
|
||||
const params = new URLSearchParams();
|
||||
if (code) params.set('code', code);
|
||||
if (state) params.set('state', state);
|
||||
return response.redirect(302, `${scheme}?${params.toString()}`);
|
||||
}
|
||||
|
||||
@Get('/oauth/:provider')
|
||||
async oauthLink(@Param('provider') provider: string, @Query() query: any) {
|
||||
return this._authService.oauthLink(provider, query);
|
||||
}
|
||||
|
||||
@Post('/activate')
|
||||
async activate(
|
||||
@Body('code') code: string,
|
||||
@Body('datafast_visitor_id') datafast_visitor_id: string,
|
||||
@Res({ passthrough: false }) response: Response
|
||||
) {
|
||||
const activate = await this._authService.activate(
|
||||
code,
|
||||
datafast_visitor_id
|
||||
);
|
||||
if (!activate) {
|
||||
return response.status(200).json({ can: false });
|
||||
}
|
||||
|
||||
response.cookie('auth', activate, {
|
||||
domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),
|
||||
...(!process.env.NOT_SECURED
|
||||
? {
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
}
|
||||
: {}),
|
||||
expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),
|
||||
});
|
||||
|
||||
if (process.env.NOT_SECURED) {
|
||||
response.header('auth', activate);
|
||||
}
|
||||
|
||||
response.header('onboarding', 'true');
|
||||
|
||||
return response.status(200).json({ can: true });
|
||||
}
|
||||
|
||||
@Post('/resend-activation')
|
||||
async resendActivation(@Body() body: ResendActivationDto) {
|
||||
try {
|
||||
await this._authService.resendActivationEmail(body.email);
|
||||
return {
|
||||
success: true,
|
||||
};
|
||||
} catch (e: any) {
|
||||
return {
|
||||
success: false,
|
||||
message: e.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@Post('/oauth/:provider/exists')
|
||||
async oauthExists(
|
||||
@Body('code') code: string,
|
||||
@Body('redirect_uri') redirect_uri: string,
|
||||
@Param('provider') provider: string,
|
||||
@Res({ passthrough: false }) response: Response
|
||||
) {
|
||||
const { jwt, token } = await this._authService.checkExists(
|
||||
provider,
|
||||
code,
|
||||
redirect_uri
|
||||
);
|
||||
|
||||
if (token) {
|
||||
return response.json({ token });
|
||||
}
|
||||
|
||||
response.cookie('auth', jwt, {
|
||||
domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),
|
||||
...(!process.env.NOT_SECURED
|
||||
? {
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
}
|
||||
: {}),
|
||||
expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),
|
||||
});
|
||||
|
||||
if (process.env.NOT_SECURED) {
|
||||
response.header('auth', jwt);
|
||||
}
|
||||
|
||||
response.header('reload', 'true');
|
||||
|
||||
response.status(200).json({
|
||||
login: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
Post,
|
||||
Put,
|
||||
Query,
|
||||
} from '@nestjs/common';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { Organization } from '@prisma/client';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { CheckPolicies } from '@gitroom/backend/services/auth/permissions/permissions.ability';
|
||||
import { AutopostService } from '@gitroom/nestjs-libraries/database/prisma/autopost/autopost.service';
|
||||
import { AutopostDto } from '@gitroom/nestjs-libraries/dtos/autopost/autopost.dto';
|
||||
import { AuthorizationActions, Sections } from '@gitroom/backend/services/auth/permissions/permission.exception.class';
|
||||
import { OnlyURL } from '@gitroom/nestjs-libraries/dtos/webhooks/webhooks.dto';
|
||||
|
||||
@ApiTags('Autopost')
|
||||
@Controller('/autopost')
|
||||
export class AutopostController {
|
||||
constructor(private _autopostsService: AutopostService) {}
|
||||
|
||||
@Get('/')
|
||||
async getAutoposts(@GetOrgFromRequest() org: Organization) {
|
||||
return this._autopostsService.getAutoposts(org.id);
|
||||
}
|
||||
|
||||
@Post('/')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.WEBHOOKS])
|
||||
async createAutopost(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: AutopostDto
|
||||
) {
|
||||
return this._autopostsService.createAutopost(org.id, body);
|
||||
}
|
||||
|
||||
@Put('/:id')
|
||||
async updateAutopost(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: AutopostDto,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
return this._autopostsService.createAutopost(org.id, body, id);
|
||||
}
|
||||
|
||||
@Delete('/:id')
|
||||
async deleteAutopost(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
return this._autopostsService.deleteAutopost(org.id, id);
|
||||
}
|
||||
|
||||
@Post('/:id/active')
|
||||
async changeActive(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string,
|
||||
@Body('active') active: boolean
|
||||
) {
|
||||
return this._autopostsService.changeActive(org.id, id, active);
|
||||
}
|
||||
|
||||
@Post('/send')
|
||||
async sendWebhook(@Query() query: OnlyURL) {
|
||||
return this._autopostsService.loadXML(query.url);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
import { Body, Controller, Get, HttpException, Param, Post, Req } from '@nestjs/common';
|
||||
import { SubscriptionService } from '@gitroom/nestjs-libraries/database/prisma/subscriptions/subscription.service';
|
||||
import { StripeService } from '@gitroom/nestjs-libraries/services/stripe.service';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { Organization, User } from '@prisma/client';
|
||||
import { BillingSubscribeDto } from '@gitroom/nestjs-libraries/dtos/billing/billing.subscribe.dto';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { GetUserFromRequest } from '@gitroom/nestjs-libraries/user/user.from.request';
|
||||
import { NotificationService } from '@gitroom/nestjs-libraries/database/prisma/notifications/notification.service';
|
||||
import { Request } from 'express';
|
||||
import { AuthService } from '@gitroom/helpers/auth/auth.service';
|
||||
|
||||
@ApiTags('Billing')
|
||||
@Controller('/billing')
|
||||
export class BillingController {
|
||||
constructor(
|
||||
private _subscriptionService: SubscriptionService,
|
||||
private _stripeService: StripeService,
|
||||
private _notificationService: NotificationService
|
||||
) {}
|
||||
|
||||
@Get('/check/:id')
|
||||
async checkId(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') body: string
|
||||
) {
|
||||
return {
|
||||
status: await this._stripeService.checkSubscription(org.id, body),
|
||||
};
|
||||
}
|
||||
|
||||
@Get('/check-discount')
|
||||
async checkDiscount(@GetOrgFromRequest() org: Organization) {
|
||||
return {
|
||||
offerCoupon: !(await this._stripeService.checkDiscount(org.paymentId))
|
||||
? false
|
||||
: AuthService.signJWT({ discount: true }),
|
||||
};
|
||||
}
|
||||
|
||||
@Post('/apply-discount')
|
||||
async applyDiscount(@GetOrgFromRequest() org: Organization) {
|
||||
await this._stripeService.applyDiscount(org.paymentId);
|
||||
}
|
||||
|
||||
@Post('/finish-trial')
|
||||
async finishTrial(@GetOrgFromRequest() org: Organization) {
|
||||
try {
|
||||
await this._stripeService.finishTrial(org.paymentId);
|
||||
} catch (err) {}
|
||||
return {
|
||||
finish: true,
|
||||
};
|
||||
}
|
||||
|
||||
@Get('/is-trial-finished')
|
||||
async isTrialFinished(@GetOrgFromRequest() org: Organization) {
|
||||
return {
|
||||
finished: !org.isTrailing,
|
||||
};
|
||||
}
|
||||
|
||||
@Post('/embedded')
|
||||
embedded(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@GetUserFromRequest() user: User,
|
||||
@Body() body: BillingSubscribeDto,
|
||||
@Req() req: Request
|
||||
) {
|
||||
const uniqueId = req?.cookies?.track;
|
||||
return this._stripeService.embedded(
|
||||
uniqueId,
|
||||
org.id,
|
||||
user.id,
|
||||
body,
|
||||
org.allowTrial
|
||||
);
|
||||
}
|
||||
|
||||
@Post('/subscribe')
|
||||
subscribe(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@GetUserFromRequest() user: User,
|
||||
@Body() body: BillingSubscribeDto,
|
||||
@Req() req: Request
|
||||
) {
|
||||
const uniqueId = req?.cookies?.track;
|
||||
return this._stripeService.subscribe(
|
||||
uniqueId,
|
||||
org.id,
|
||||
user.id,
|
||||
body,
|
||||
org.allowTrial
|
||||
);
|
||||
}
|
||||
|
||||
@Get('/portal')
|
||||
async modifyPayment(@GetOrgFromRequest() org: Organization) {
|
||||
const customer = await this._stripeService.getCustomerByOrganizationId(
|
||||
org.id
|
||||
);
|
||||
const { url } = await this._stripeService.createBillingPortalLink(customer);
|
||||
return {
|
||||
portal: url,
|
||||
};
|
||||
}
|
||||
|
||||
@Get('/')
|
||||
getCurrentBilling(@GetOrgFromRequest() org: Organization) {
|
||||
return this._subscriptionService.getSubscriptionByOrganizationId(org.id);
|
||||
}
|
||||
|
||||
@Post('/cancel')
|
||||
async cancel(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@GetUserFromRequest() user: User,
|
||||
@Body() body: { feedback: string }
|
||||
) {
|
||||
await this._notificationService.sendEmail(
|
||||
process.env.EMAIL_FROM_ADDRESS,
|
||||
'Subscription Cancelled',
|
||||
`Organization ${org.name} has cancelled their subscription because: ${body.feedback}`,
|
||||
user.email
|
||||
);
|
||||
|
||||
return this._stripeService.setToCancel(org.id);
|
||||
}
|
||||
|
||||
@Post('/prorate')
|
||||
prorate(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: BillingSubscribeDto
|
||||
) {
|
||||
return this._stripeService.prorate(org.id, body);
|
||||
}
|
||||
|
||||
@Post('/lifetime')
|
||||
async lifetime(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: { code: string }
|
||||
) {
|
||||
return this._stripeService.lifetimeDeal(org.id, body.code);
|
||||
}
|
||||
|
||||
@Get('/charges')
|
||||
async getCharges(
|
||||
@GetUserFromRequest() user: User,
|
||||
@GetOrgFromRequest() org: Organization
|
||||
) {
|
||||
if (!user.isSuperAdmin) {
|
||||
throw new HttpException('Unauthorized', 400);
|
||||
}
|
||||
|
||||
return this._stripeService.getCharges(org.id);
|
||||
}
|
||||
|
||||
@Post('/refund-charges')
|
||||
async refundCharges(
|
||||
@GetUserFromRequest() user: User,
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: { chargeIds: string[] }
|
||||
) {
|
||||
if (!user.isSuperAdmin) {
|
||||
throw new HttpException('Unauthorized', 400);
|
||||
}
|
||||
|
||||
return this._stripeService.refundCharges(org.id, body.chargeIds);
|
||||
}
|
||||
|
||||
@Post('/cancel-subscription')
|
||||
async cancelSubscription(
|
||||
@GetUserFromRequest() user: User,
|
||||
@GetOrgFromRequest() org: Organization
|
||||
) {
|
||||
if (!user.isSuperAdmin) {
|
||||
throw new HttpException('Unauthorized', 400);
|
||||
}
|
||||
|
||||
return this._stripeService.cancelSubscription(org.id);
|
||||
}
|
||||
|
||||
@Post('/add-subscription')
|
||||
async addSubscription(
|
||||
@Body() body: { subscription: string },
|
||||
@GetUserFromRequest() user: User,
|
||||
@GetOrgFromRequest() org: Organization
|
||||
) {
|
||||
if (!user.isSuperAdmin) {
|
||||
throw new Error('Unauthorized');
|
||||
}
|
||||
|
||||
await this._subscriptionService.addSubscription(
|
||||
org.id,
|
||||
user.id,
|
||||
body.subscription
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import {
|
||||
Logger,
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Req,
|
||||
Res,
|
||||
Query,
|
||||
Param,
|
||||
} from '@nestjs/common';
|
||||
import {
|
||||
CopilotRuntime,
|
||||
OpenAIAdapter,
|
||||
copilotRuntimeNodeHttpEndpoint,
|
||||
copilotRuntimeNextJSAppRouterEndpoint,
|
||||
} from '@copilotkit/runtime';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { Organization } from '@prisma/client';
|
||||
import { SubscriptionService } from '@gitroom/nestjs-libraries/database/prisma/subscriptions/subscription.service';
|
||||
import { MastraAgent } from '@ag-ui/mastra';
|
||||
import { MastraService } from '@gitroom/nestjs-libraries/chat/mastra.service';
|
||||
import { Request, Response } from 'express';
|
||||
import { RequestContext } from '@mastra/core/di';
|
||||
import { CheckPolicies } from '@gitroom/backend/services/auth/permissions/permissions.ability';
|
||||
import { AuthorizationActions, Sections } from '@gitroom/backend/services/auth/permissions/permission.exception.class';
|
||||
|
||||
export type ChannelsContext = {
|
||||
integrations: string;
|
||||
organization: string;
|
||||
ui: string;
|
||||
};
|
||||
|
||||
@Controller('/copilot')
|
||||
export class CopilotController {
|
||||
constructor(
|
||||
private _subscriptionService: SubscriptionService,
|
||||
private _mastraService: MastraService
|
||||
) {}
|
||||
@Post('/chat')
|
||||
chatAgent(@Req() req: Request, @Res() res: Response) {
|
||||
if (
|
||||
process.env.OPENAI_API_KEY === undefined ||
|
||||
process.env.OPENAI_API_KEY === ''
|
||||
) {
|
||||
Logger.warn('OpenAI API key not set, chat functionality will not work');
|
||||
return;
|
||||
}
|
||||
|
||||
const copilotRuntimeHandler = copilotRuntimeNodeHttpEndpoint({
|
||||
endpoint: '/copilot/chat',
|
||||
runtime: new CopilotRuntime(),
|
||||
serviceAdapter: new OpenAIAdapter({
|
||||
model: 'gpt-4.1',
|
||||
}),
|
||||
});
|
||||
|
||||
return copilotRuntimeHandler(req, res);
|
||||
}
|
||||
|
||||
@Post('/agent')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.AI])
|
||||
async agent(
|
||||
@Req() req: Request,
|
||||
@Res() res: Response,
|
||||
@GetOrgFromRequest() organization: Organization
|
||||
) {
|
||||
if (
|
||||
process.env.OPENAI_API_KEY === undefined ||
|
||||
process.env.OPENAI_API_KEY === ''
|
||||
) {
|
||||
Logger.warn('OpenAI API key not set, chat functionality will not work');
|
||||
return;
|
||||
}
|
||||
const mastra = await this._mastraService.mastra();
|
||||
const requestContext = new RequestContext<ChannelsContext>();
|
||||
requestContext.set(
|
||||
'integrations',
|
||||
req?.body?.variables?.properties?.integrations || []
|
||||
);
|
||||
|
||||
requestContext.set('organization', JSON.stringify(organization));
|
||||
requestContext.set('ui', 'true');
|
||||
|
||||
const agents = MastraAgent.getLocalAgents({
|
||||
resourceId: organization.id,
|
||||
mastra,
|
||||
requestContext: requestContext as any,
|
||||
});
|
||||
|
||||
const runtime = new CopilotRuntime({
|
||||
agents,
|
||||
});
|
||||
|
||||
const copilotRuntimeHandler = copilotRuntimeNextJSAppRouterEndpoint({
|
||||
endpoint: '/copilot/agent',
|
||||
runtime,
|
||||
// properties: req.body.variables.properties,
|
||||
serviceAdapter: new OpenAIAdapter({
|
||||
model: 'gpt-4.1',
|
||||
}),
|
||||
});
|
||||
|
||||
return copilotRuntimeHandler.handleRequest(req, res);
|
||||
}
|
||||
|
||||
@Get('/credits')
|
||||
calculateCredits(
|
||||
@GetOrgFromRequest() organization: Organization,
|
||||
@Query('type') type: 'ai_images' | 'ai_videos'
|
||||
) {
|
||||
return this._subscriptionService.checkCredits(
|
||||
organization,
|
||||
type || 'ai_images'
|
||||
);
|
||||
}
|
||||
|
||||
@Get('/:thread/list')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.AI])
|
||||
async getMessagesList(
|
||||
@GetOrgFromRequest() organization: Organization,
|
||||
@Param('thread') threadId: string
|
||||
): Promise<any> {
|
||||
const mastra = await this._mastraService.mastra();
|
||||
const memory = await mastra.getAgent('postiz').getMemory();
|
||||
try {
|
||||
return await memory.recall({
|
||||
resourceId: organization.id,
|
||||
threadId,
|
||||
});
|
||||
} catch (err) {
|
||||
return { messages: [] };
|
||||
}
|
||||
}
|
||||
|
||||
@Get('/list')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.AI])
|
||||
async getList(@GetOrgFromRequest() organization: Organization) {
|
||||
const mastra = await this._mastraService.mastra();
|
||||
const memory = await mastra.getAgent('postiz').getMemory();
|
||||
const list = await memory.listThreads({
|
||||
filter: { resourceId: organization.id },
|
||||
perPage: 100000,
|
||||
page: 0,
|
||||
orderBy: { field: 'createdAt', direction: 'DESC' },
|
||||
});
|
||||
|
||||
return {
|
||||
threads: list.threads.map((p) => ({
|
||||
id: p.id,
|
||||
title: p.title,
|
||||
})),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import { Body, Controller, Param, Post, Res } from '@nestjs/common';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { AuthService } from '@gitroom/helpers/auth/auth.service';
|
||||
import { ioRedis } from '@gitroom/nestjs-libraries/redis/redis.service';
|
||||
import { IntegrationManager } from '@gitroom/nestjs-libraries/integrations/integration.manager';
|
||||
import { OrganizationService } from '@gitroom/nestjs-libraries/database/prisma/organizations/organization.service';
|
||||
import { IntegrationService } from '@gitroom/nestjs-libraries/database/prisma/integrations/integration.service';
|
||||
import { PostsService } from '@gitroom/nestjs-libraries/database/prisma/posts/posts.service';
|
||||
|
||||
@ApiTags('Enterprise')
|
||||
@Controller('/enterprise')
|
||||
export class EnterpriseController {
|
||||
constructor(
|
||||
private _integrationManager: IntegrationManager,
|
||||
private _organizationService: OrganizationService,
|
||||
private _integrationService: IntegrationService,
|
||||
private _postsService: PostsService
|
||||
) {}
|
||||
|
||||
@Post('/create-user')
|
||||
async createUser(@Body('params') params: string) {
|
||||
try {
|
||||
const { id, name, saasName, email } = AuthService.verifyJWT(params) as {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
saasName: string;
|
||||
};
|
||||
|
||||
try {
|
||||
return await this._organizationService.createMaxUser(
|
||||
id,
|
||||
name,
|
||||
saasName,
|
||||
email
|
||||
);
|
||||
} catch (err) {
|
||||
return { create: false };
|
||||
}
|
||||
} catch (err) {
|
||||
return { success: false };
|
||||
}
|
||||
}
|
||||
|
||||
@Post('/url')
|
||||
async redirectParams(@Body('params') params: string) {
|
||||
try {
|
||||
const load = AuthService.verifyJWT(params) as {
|
||||
redirectUrl: string;
|
||||
apiKey: string;
|
||||
refreshId?: string;
|
||||
provider: string;
|
||||
webhookUrl: string;
|
||||
};
|
||||
|
||||
if (!load || !load.redirectUrl || !load.apiKey || !load.provider) {
|
||||
return;
|
||||
}
|
||||
|
||||
const org = await this._organizationService.getOrgByApiKey(load.apiKey);
|
||||
|
||||
if (!org) {
|
||||
throw new Error('Organization not found');
|
||||
}
|
||||
|
||||
if (
|
||||
!this._integrationManager
|
||||
.getAllowedSocialsIntegrations()
|
||||
.includes(load.provider)
|
||||
) {
|
||||
throw new Error('Integration not allowed');
|
||||
}
|
||||
|
||||
const integrationProvider = this._integrationManager.getSocialIntegration(
|
||||
load.provider
|
||||
);
|
||||
|
||||
const { codeVerifier, state, url } =
|
||||
await integrationProvider.generateAuthUrl();
|
||||
|
||||
if (load.refreshId) {
|
||||
await ioRedis.set(`refresh:${state}`, load.refreshId, 'EX', 3600);
|
||||
}
|
||||
|
||||
await ioRedis.set(`webhookUrl:${state}`, load.webhookUrl, 'EX', 3600);
|
||||
await ioRedis.set(`redirect:${state}`, load.redirectUrl, 'EX', 3600);
|
||||
await ioRedis.set(`organization:${state}`, org.id, 'EX', 3600);
|
||||
await ioRedis.set(`login:${state}`, codeVerifier, 'EX', 3600);
|
||||
|
||||
return url;
|
||||
} catch (err) {}
|
||||
}
|
||||
|
||||
@Post('/delete-channel')
|
||||
async deleteChannel(@Body('params') params: string) {
|
||||
try {
|
||||
const load = AuthService.verifyJWT(params) as {
|
||||
apiKey: string;
|
||||
id: string;
|
||||
};
|
||||
|
||||
if (!load || !load.apiKey || !load.id) {
|
||||
return { success: false };
|
||||
}
|
||||
|
||||
const org = await this._organizationService.getOrgByApiKey(load.apiKey);
|
||||
|
||||
if (!org) {
|
||||
return { success: false };
|
||||
}
|
||||
|
||||
const isTherePosts = await this._integrationService.getPostsForChannel(
|
||||
org.id,
|
||||
load.id
|
||||
);
|
||||
if (isTherePosts.length) {
|
||||
for (const post of isTherePosts) {
|
||||
this._postsService.deletePost(org.id, post.group).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
await this._integrationService.deleteChannel(org.id, load.id);
|
||||
return { success: true };
|
||||
} catch (err) {
|
||||
return { success: false };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,481 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
Post,
|
||||
Put,
|
||||
Query,
|
||||
} from '@nestjs/common';
|
||||
import { ioRedis } from '@gitroom/nestjs-libraries/redis/redis.service';
|
||||
import { IntegrationManager } from '@gitroom/nestjs-libraries/integrations/integration.manager';
|
||||
import { IntegrationService } from '@gitroom/nestjs-libraries/database/prisma/integrations/integration.service';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { Organization, User } from '@prisma/client';
|
||||
import { IntegrationFunctionDto } from '@gitroom/nestjs-libraries/dtos/integrations/integration.function.dto';
|
||||
import { CheckPolicies } from '@gitroom/backend/services/auth/permissions/permissions.ability';
|
||||
import { pricing } from '@gitroom/nestjs-libraries/database/prisma/subscriptions/pricing';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { GetUserFromRequest } from '@gitroom/nestjs-libraries/user/user.from.request';
|
||||
import { PostsService } from '@gitroom/nestjs-libraries/database/prisma/posts/posts.service';
|
||||
import { IntegrationTimeDto } from '@gitroom/nestjs-libraries/dtos/integrations/integration.time.dto';
|
||||
import { PlugDto } from '@gitroom/nestjs-libraries/dtos/plugs/plug.dto';
|
||||
import { RefreshToken } from '@gitroom/nestjs-libraries/integrations/social.abstract';
|
||||
|
||||
import { timer } from '@gitroom/helpers/utils/timer';
|
||||
import { TelegramProvider } from '@gitroom/nestjs-libraries/integrations/social/telegram.provider';
|
||||
import { MoltbookProvider } from '@gitroom/nestjs-libraries/integrations/social/moltbook.provider';
|
||||
import {
|
||||
AuthorizationActions,
|
||||
Sections,
|
||||
} from '@gitroom/backend/services/auth/permissions/permission.exception.class';
|
||||
import { uniqBy } from 'lodash';
|
||||
import { RefreshIntegrationService } from '@gitroom/nestjs-libraries/integrations/refresh.integration.service';
|
||||
|
||||
@ApiTags('Integrations')
|
||||
@Controller('/integrations')
|
||||
export class IntegrationsController {
|
||||
constructor(
|
||||
private _integrationManager: IntegrationManager,
|
||||
private _integrationService: IntegrationService,
|
||||
private _postService: PostsService,
|
||||
private _refreshIntegrationService: RefreshIntegrationService
|
||||
) {}
|
||||
|
||||
@Post('/provider/:id/connect')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.CHANNEL])
|
||||
async saveProviderPage(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string,
|
||||
@Body() body: any
|
||||
) {
|
||||
return this._integrationService.saveProviderPage(org.id, id, body);
|
||||
}
|
||||
|
||||
@Get('/:identifier/internal-plugs')
|
||||
getInternalPlugs(@Param('identifier') identifier: string) {
|
||||
return this._integrationManager.getInternalPlugs(identifier);
|
||||
}
|
||||
|
||||
@Get('/customers')
|
||||
getCustomers(@GetOrgFromRequest() org: Organization) {
|
||||
return this._integrationService.customers(org.id);
|
||||
}
|
||||
|
||||
@Put('/:id/group')
|
||||
async updateIntegrationGroup(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string,
|
||||
@Body() body: { group: string }
|
||||
) {
|
||||
return this._integrationService.updateIntegrationGroup(
|
||||
org.id,
|
||||
id,
|
||||
body.group
|
||||
);
|
||||
}
|
||||
|
||||
@Put('/:id/customer-name')
|
||||
async updateOnCustomerName(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string,
|
||||
@Body() body: { name: string }
|
||||
) {
|
||||
return this._integrationService.updateOnCustomerName(org.id, id, body.name);
|
||||
}
|
||||
|
||||
@Get('/list')
|
||||
async getIntegrationList(@GetOrgFromRequest() org: Organization) {
|
||||
return {
|
||||
integrations: await Promise.all(
|
||||
(
|
||||
await this._integrationService.getIntegrationsList(org.id)
|
||||
).map(async (p) => {
|
||||
const findIntegration = this._integrationManager.getSocialIntegration(
|
||||
p.providerIdentifier
|
||||
);
|
||||
return {
|
||||
name: p.name,
|
||||
id: p.id,
|
||||
internalId: p.internalId,
|
||||
disabled: p.disabled,
|
||||
editor: findIntegration.editor,
|
||||
stripLinks: !!findIntegration?.stripLinks?.(),
|
||||
picture: p.picture || '/no-picture.jpg',
|
||||
identifier: p.providerIdentifier,
|
||||
inBetweenSteps: p.inBetweenSteps,
|
||||
refreshNeeded: p.refreshNeeded,
|
||||
isCustomFields: !!findIntegration.customFields,
|
||||
...(findIntegration.customFields
|
||||
? { customFields: await findIntegration.customFields() }
|
||||
: {}),
|
||||
display: p.profile,
|
||||
type: p.type,
|
||||
time: JSON.parse(p.postingTimes),
|
||||
changeProfilePicture: !!findIntegration?.changeProfilePicture,
|
||||
changeNickName: !!findIntegration?.changeNickname,
|
||||
customer: p.customer,
|
||||
additionalSettings: p.additionalSettings || '[]',
|
||||
};
|
||||
})
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
@Post('/:id/settings')
|
||||
async updateProviderSettings(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string,
|
||||
@Body('additionalSettings') body: string
|
||||
) {
|
||||
if (typeof body !== 'string') {
|
||||
throw new Error('Invalid body');
|
||||
}
|
||||
|
||||
await this._integrationService.updateProviderSettings(org.id, id, body);
|
||||
}
|
||||
@Post('/:id/nickname')
|
||||
async setNickname(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string,
|
||||
@Body() body: { name: string; picture: string }
|
||||
) {
|
||||
const integration = await this._integrationService.getIntegrationById(
|
||||
org.id,
|
||||
id
|
||||
);
|
||||
if (!integration) {
|
||||
throw new Error('Invalid integration');
|
||||
}
|
||||
|
||||
const manager = this._integrationManager.getSocialIntegration(
|
||||
integration.providerIdentifier
|
||||
);
|
||||
if (!manager.changeProfilePicture && !manager.changeNickname) {
|
||||
throw new Error('Invalid integration');
|
||||
}
|
||||
|
||||
const { url } = manager.changeProfilePicture
|
||||
? await manager.changeProfilePicture(
|
||||
integration.internalId,
|
||||
integration.token,
|
||||
body.picture
|
||||
)
|
||||
: { url: '' };
|
||||
|
||||
const { name } = manager.changeNickname
|
||||
? await manager.changeNickname(
|
||||
integration.internalId,
|
||||
integration.token,
|
||||
body.name
|
||||
)
|
||||
: { name: '' };
|
||||
|
||||
return this._integrationService.updateNameAndUrl(id, name, url);
|
||||
}
|
||||
|
||||
@Get('/:id')
|
||||
getSingleIntegration(
|
||||
@Param('id') id: string,
|
||||
@Query('order') order: string,
|
||||
@GetUserFromRequest() user: User,
|
||||
@GetOrgFromRequest() org: Organization
|
||||
) {
|
||||
return this._integrationService.getIntegrationForOrder(
|
||||
id,
|
||||
order,
|
||||
user.id,
|
||||
org.id
|
||||
);
|
||||
}
|
||||
|
||||
@Get('/social/:integration')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.CHANNEL])
|
||||
async getIntegrationUrl(
|
||||
@Param('integration') integration: string,
|
||||
@Query('refresh') refresh: string,
|
||||
@Query('externalUrl') externalUrl: string,
|
||||
@Query('redirectUrl') redirectUrl: string,
|
||||
@Query('onboarding') onboarding: string,
|
||||
@GetOrgFromRequest() org: Organization
|
||||
) {
|
||||
if (
|
||||
!this._integrationManager
|
||||
.getAllowedSocialsIntegrations()
|
||||
.includes(integration)
|
||||
) {
|
||||
throw new Error('Integration not allowed');
|
||||
}
|
||||
|
||||
const integrationProvider =
|
||||
this._integrationManager.getSocialIntegration(integration);
|
||||
|
||||
if (integrationProvider.externalUrl && !externalUrl) {
|
||||
throw new Error('Missing external url');
|
||||
}
|
||||
|
||||
try {
|
||||
const getExternalUrl = integrationProvider.externalUrl
|
||||
? {
|
||||
...(await integrationProvider.externalUrl(externalUrl)),
|
||||
instanceUrl: externalUrl,
|
||||
}
|
||||
: undefined;
|
||||
|
||||
const { codeVerifier, state, url } =
|
||||
await integrationProvider.generateAuthUrl(getExternalUrl);
|
||||
|
||||
if (refresh) {
|
||||
await ioRedis.set(`refresh:${state}`, refresh, 'EX', 3600);
|
||||
}
|
||||
|
||||
if (onboarding === 'true') {
|
||||
await ioRedis.set(`onboarding:${state}`, 'true', 'EX', 3600);
|
||||
}
|
||||
|
||||
if (redirectUrl) {
|
||||
await ioRedis.set(`redirect:${state}`, redirectUrl, 'EX', 3600);
|
||||
}
|
||||
|
||||
await ioRedis.set(`organization:${state}`, org.id, 'EX', 3600);
|
||||
await ioRedis.set(`login:${state}`, codeVerifier, 'EX', 3600);
|
||||
await ioRedis.set(
|
||||
`external:${state}`,
|
||||
JSON.stringify(getExternalUrl),
|
||||
'EX',
|
||||
3600
|
||||
);
|
||||
|
||||
return { url };
|
||||
} catch (err) {
|
||||
return { err: true };
|
||||
}
|
||||
}
|
||||
|
||||
@Post('/:id/time')
|
||||
async setTime(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string,
|
||||
@Body() body: IntegrationTimeDto
|
||||
) {
|
||||
return this._integrationService.setTimes(org.id, id, body);
|
||||
}
|
||||
|
||||
@Post('/mentions')
|
||||
async mentions(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: IntegrationFunctionDto
|
||||
) {
|
||||
const getIntegration = await this._integrationService.getIntegrationById(
|
||||
org.id,
|
||||
body.id
|
||||
);
|
||||
if (!getIntegration) {
|
||||
throw new Error('Invalid integration');
|
||||
}
|
||||
|
||||
let newList: any[] | { none: true } = [];
|
||||
try {
|
||||
newList = (await this.functionIntegration(org, body)) || [];
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
}
|
||||
|
||||
if (!Array.isArray(newList) && newList?.none) {
|
||||
return newList;
|
||||
}
|
||||
|
||||
const list = await this._integrationService.getMentions(
|
||||
getIntegration.providerIdentifier,
|
||||
body?.data?.query
|
||||
);
|
||||
|
||||
if (Array.isArray(newList) && newList.length) {
|
||||
await this._integrationService.insertMentions(
|
||||
getIntegration.providerIdentifier,
|
||||
newList
|
||||
.map((p: any) => ({
|
||||
name: p.label || '',
|
||||
username: p.id || '',
|
||||
image: p.image || '',
|
||||
doNotCache: p.doNotCache || false,
|
||||
}))
|
||||
.filter((f: any) => f.name && !f.doNotCache)
|
||||
);
|
||||
}
|
||||
|
||||
return uniqBy(
|
||||
[
|
||||
...list.map((p) => ({
|
||||
id: p.username,
|
||||
image: p.image,
|
||||
label: p.name,
|
||||
})),
|
||||
...(newList as any[]),
|
||||
],
|
||||
(p) => p.id
|
||||
).filter((f) => f.label && f.id);
|
||||
}
|
||||
|
||||
@Post('/function')
|
||||
async functionIntegration(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: IntegrationFunctionDto
|
||||
): Promise<any> {
|
||||
const getIntegration = await this._integrationService.getIntegrationById(
|
||||
org.id,
|
||||
body.id
|
||||
);
|
||||
if (!getIntegration) {
|
||||
throw new Error('Invalid integration');
|
||||
}
|
||||
|
||||
const integrationProvider = this._integrationManager.getSocialIntegration(
|
||||
getIntegration.providerIdentifier
|
||||
);
|
||||
if (!integrationProvider) {
|
||||
throw new Error('Invalid provider');
|
||||
}
|
||||
|
||||
// @ts-ignore
|
||||
if (integrationProvider[body.name]) {
|
||||
try {
|
||||
// @ts-ignore
|
||||
const load = await integrationProvider[body.name](
|
||||
getIntegration.token,
|
||||
body.data,
|
||||
getIntegration.internalId,
|
||||
getIntegration
|
||||
);
|
||||
|
||||
return load;
|
||||
} catch (err) {
|
||||
if (err instanceof RefreshToken) {
|
||||
const data = await this._refreshIntegrationService.refresh(
|
||||
getIntegration
|
||||
);
|
||||
|
||||
if (!data) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { accessToken } = data;
|
||||
|
||||
if (accessToken) {
|
||||
if (integrationProvider.refreshWait) {
|
||||
await timer(10000);
|
||||
}
|
||||
return this.functionIntegration(org, body);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
throw new Error('Function not found');
|
||||
}
|
||||
|
||||
@Post('/disable')
|
||||
disableChannel(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body('id') id: string
|
||||
) {
|
||||
return this._integrationService.disableChannel(org.id, id);
|
||||
}
|
||||
|
||||
@Post('/enable')
|
||||
enableChannel(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body('id') id: string
|
||||
) {
|
||||
return this._integrationService.enableChannel(
|
||||
org.id,
|
||||
// @ts-ignore
|
||||
org?.subscription?.totalChannels || pricing.FREE.channel,
|
||||
id
|
||||
);
|
||||
}
|
||||
|
||||
@Delete('/')
|
||||
async deleteChannel(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body('id') id: string
|
||||
) {
|
||||
const isTherePosts = await this._integrationService.getPostsForChannel(
|
||||
org.id,
|
||||
id
|
||||
);
|
||||
if (isTherePosts.length) {
|
||||
for (const post of isTherePosts) {
|
||||
this._postService.deletePost(org.id, post.group).catch((err) => {});
|
||||
}
|
||||
}
|
||||
|
||||
return this._integrationService.deleteChannel(org.id, id);
|
||||
}
|
||||
|
||||
@Get('/plug/list')
|
||||
async getPlugList() {
|
||||
return { plugs: this._integrationManager.getAllPlugs() };
|
||||
}
|
||||
|
||||
@Get('/:id/plugs')
|
||||
async getPlugsByIntegrationId(
|
||||
@Param('id') id: string,
|
||||
@GetOrgFromRequest() org: Organization
|
||||
) {
|
||||
return this._integrationService.getPlugsByIntegrationId(org.id, id);
|
||||
}
|
||||
|
||||
@Post('/:id/plugs')
|
||||
async postPlugsByIntegrationId(
|
||||
@Param('id') id: string,
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: PlugDto
|
||||
) {
|
||||
return this._integrationService.createOrUpdatePlug(org.id, id, body);
|
||||
}
|
||||
|
||||
@Put('/plugs/:id/activate')
|
||||
async changePlugActivation(
|
||||
@Param('id') id: string,
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body('status') status: boolean
|
||||
) {
|
||||
return this._integrationService.changePlugActivation(org.id, id, status);
|
||||
}
|
||||
|
||||
@Get('/telegram/updates')
|
||||
async getUpdates(@Query() query: { word: string; id?: number }) {
|
||||
return new TelegramProvider().getBotId(query);
|
||||
}
|
||||
|
||||
@Post('/moltbook/register')
|
||||
async moltbookRegister(@Body() body: { name: string; description: string }) {
|
||||
try {
|
||||
const provider = new MoltbookProvider();
|
||||
const result = await provider.registerAgent(body.name, body.description);
|
||||
return {
|
||||
apiKey: result.api_key,
|
||||
claimUrl: result.claim_url,
|
||||
verificationCode: result.verification_code,
|
||||
};
|
||||
} catch (err: any) {
|
||||
return { error: err.message || 'Registration failed' };
|
||||
}
|
||||
}
|
||||
|
||||
@Get('/moltbook/status')
|
||||
async moltbookStatus(@Query('apiKey') apiKey: string) {
|
||||
try {
|
||||
const provider = new MoltbookProvider();
|
||||
const result = await provider.checkAgentStatus(apiKey);
|
||||
return { claimed: result?.status === 'claimed' };
|
||||
} catch (err) {
|
||||
return { claimed: false };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
Post,
|
||||
Query,
|
||||
Req,
|
||||
Res,
|
||||
UploadedFile,
|
||||
UseInterceptors,
|
||||
UsePipes,
|
||||
} from '@nestjs/common';
|
||||
import { Request, Response } from 'express';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { Organization } from '@prisma/client';
|
||||
import { MediaService } from '@gitroom/nestjs-libraries/database/prisma/media/media.service';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import handleR2Upload from '@gitroom/nestjs-libraries/upload/r2.uploader';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import { CustomFileValidationPipe } from '@gitroom/nestjs-libraries/upload/custom.upload.validation';
|
||||
import { SubscriptionService } from '@gitroom/nestjs-libraries/database/prisma/subscriptions/subscription.service';
|
||||
import { UploadFactory } from '@gitroom/nestjs-libraries/upload/upload.factory';
|
||||
import { SaveMediaInformationDto } from '@gitroom/nestjs-libraries/dtos/media/save.media.information.dto';
|
||||
import { VideoDto } from '@gitroom/nestjs-libraries/dtos/videos/video.dto';
|
||||
import { VideoFunctionDto } from '@gitroom/nestjs-libraries/dtos/videos/video.function.dto';
|
||||
|
||||
@ApiTags('Media')
|
||||
@Controller('/media')
|
||||
export class MediaController {
|
||||
private storage = UploadFactory.createStorage();
|
||||
constructor(
|
||||
private _mediaService: MediaService,
|
||||
private _subscriptionService: SubscriptionService
|
||||
) {}
|
||||
|
||||
@Delete('/:id')
|
||||
deleteMedia(@GetOrgFromRequest() org: Organization, @Param('id') id: string) {
|
||||
return this._mediaService.deleteMedia(org.id, id);
|
||||
}
|
||||
|
||||
@Post('/generate-video')
|
||||
generateVideo(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: VideoDto
|
||||
) {
|
||||
console.log('hello');
|
||||
return this._mediaService.generateVideo(org, body);
|
||||
}
|
||||
|
||||
@Post('/generate-image')
|
||||
async generateImage(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Req() req: Request,
|
||||
@Body('prompt') prompt: string,
|
||||
isPicturePrompt = false
|
||||
) {
|
||||
const total = await this._subscriptionService.checkCredits(org);
|
||||
if (process.env.STRIPE_PUBLISHABLE_KEY && total.credits <= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return {
|
||||
output:
|
||||
'data:image/png;base64,' +
|
||||
(await this._mediaService.generateImage(prompt, org, isPicturePrompt)),
|
||||
};
|
||||
}
|
||||
|
||||
@Post('/generate-image-with-prompt')
|
||||
async generateImageFromText(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Req() req: Request,
|
||||
@Body('prompt') prompt: string
|
||||
) {
|
||||
const image = await this.generateImage(org, req, prompt, true);
|
||||
if (!image) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const file = await this.storage.uploadSimple(image.output);
|
||||
|
||||
return this._mediaService.saveFile(org.id, file.split('/').pop(), file);
|
||||
}
|
||||
|
||||
@Post('/upload-server')
|
||||
@UseInterceptors(FileInterceptor('file'))
|
||||
@UsePipes(new CustomFileValidationPipe())
|
||||
async uploadServer(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@UploadedFile() file: Express.Multer.File
|
||||
) {
|
||||
const originalName = file?.originalname || '';
|
||||
const uploadedFile = await this.storage.uploadFile(file);
|
||||
return this._mediaService.saveFile(
|
||||
org.id,
|
||||
uploadedFile.originalname,
|
||||
uploadedFile.path,
|
||||
originalName
|
||||
);
|
||||
}
|
||||
|
||||
@Post('/save-media')
|
||||
async saveMedia(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Req() req: Request,
|
||||
@Body('name') name: string,
|
||||
@Body('originalName') originalName: string
|
||||
) {
|
||||
if (!name) {
|
||||
return false;
|
||||
}
|
||||
return this._mediaService.saveFile(
|
||||
org.id,
|
||||
name,
|
||||
process.env.CLOUDFLARE_BUCKET_URL + '/' + name,
|
||||
originalName || undefined
|
||||
);
|
||||
}
|
||||
|
||||
@Post('/information')
|
||||
saveMediaInformation(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: SaveMediaInformationDto
|
||||
) {
|
||||
return this._mediaService.saveMediaInformation(org.id, body);
|
||||
}
|
||||
|
||||
@Post('/upload-simple')
|
||||
@UseInterceptors(FileInterceptor('file'))
|
||||
@UsePipes(new CustomFileValidationPipe())
|
||||
async uploadSimple(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@UploadedFile('file') file: Express.Multer.File,
|
||||
@Body('preventSave') preventSave: string = 'false'
|
||||
) {
|
||||
const originalName = file.originalname;
|
||||
const getFile = await this.storage.uploadFile(file);
|
||||
|
||||
if (preventSave === 'true') {
|
||||
const { path } = getFile;
|
||||
return { path };
|
||||
}
|
||||
|
||||
return this._mediaService.saveFile(
|
||||
org.id,
|
||||
getFile.originalname,
|
||||
getFile.path,
|
||||
originalName
|
||||
);
|
||||
}
|
||||
|
||||
@Post('/:endpoint')
|
||||
async uploadFile(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Req() req: Request,
|
||||
@Res() res: Response,
|
||||
@Param('endpoint') endpoint: string
|
||||
) {
|
||||
const upload = await handleR2Upload(endpoint, req, res);
|
||||
if (endpoint !== 'complete-multipart-upload') {
|
||||
return upload;
|
||||
}
|
||||
|
||||
// @ts-ignore
|
||||
const name = upload.Location.split('/').pop();
|
||||
const originalName = req.body?.file?.name;
|
||||
|
||||
const saveFile = await this._mediaService.saveFile(
|
||||
org.id,
|
||||
name,
|
||||
// @ts-ignore
|
||||
upload.Location,
|
||||
originalName || undefined
|
||||
);
|
||||
|
||||
res.status(200).json({ ...upload, saved: saveFile });
|
||||
}
|
||||
|
||||
@Get('/')
|
||||
getMedia(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Query('page') page: number,
|
||||
@Query('search') search?: string
|
||||
) {
|
||||
return this._mediaService.getMedia(org.id, page, search);
|
||||
}
|
||||
|
||||
@Get('/video-options')
|
||||
getVideos() {
|
||||
return this._mediaService.getVideoOptions();
|
||||
}
|
||||
|
||||
@Post('/video/function')
|
||||
videoFunction(
|
||||
@Body() body: VideoFunctionDto
|
||||
) {
|
||||
return this._mediaService.videoFunction(body.identifier, body.functionName, body.params);
|
||||
}
|
||||
|
||||
@Get('/generate-video/:type/allowed')
|
||||
generateVideoAllowed(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('type') type: string
|
||||
) {
|
||||
return this._mediaService.generateVideoAllowed(org, type);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Controller, Get, Param } from '@nestjs/common';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
|
||||
@ApiTags('Monitor')
|
||||
@Controller('/monitor')
|
||||
export class MonitorController {
|
||||
@Get('/queue/:name')
|
||||
async getMessagesGroup(@Param('name') name: string) {
|
||||
return {
|
||||
status: 'success',
|
||||
message: `Queue ${name} is healthy.`,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,405 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
HttpException,
|
||||
Param,
|
||||
Post,
|
||||
UseFilters,
|
||||
} from '@nestjs/common';
|
||||
import { ioRedis } from '@gitroom/nestjs-libraries/redis/redis.service';
|
||||
import { ConnectIntegrationDto } from '@gitroom/nestjs-libraries/dtos/integrations/connect.integration.dto';
|
||||
import { IntegrationManager } from '@gitroom/nestjs-libraries/integrations/integration.manager';
|
||||
import { IntegrationService } from '@gitroom/nestjs-libraries/database/prisma/integrations/integration.service';
|
||||
import { CheckPolicies } from '@gitroom/backend/services/auth/permissions/permissions.ability';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { NotEnoughScopesFilter } from '@gitroom/nestjs-libraries/integrations/integration.missing.scopes';
|
||||
import { AuthService } from '@gitroom/helpers/auth/auth.service';
|
||||
import { AuthTokenDetails } from '@gitroom/nestjs-libraries/integrations/social/social.integrations.interface';
|
||||
import { NotEnoughScopes } from '@gitroom/nestjs-libraries/integrations/social.abstract';
|
||||
import {
|
||||
AuthorizationActions,
|
||||
Sections,
|
||||
} from '@gitroom/backend/services/auth/permissions/permission.exception.class';
|
||||
import { RefreshIntegrationService } from '@gitroom/nestjs-libraries/integrations/refresh.integration.service';
|
||||
import { OrganizationService } from '@gitroom/nestjs-libraries/database/prisma/organizations/organization.service';
|
||||
|
||||
@ApiTags('Integrations')
|
||||
@Controller('/integrations')
|
||||
export class NoAuthIntegrationsController {
|
||||
constructor(
|
||||
private _integrationManager: IntegrationManager,
|
||||
private _integrationService: IntegrationService,
|
||||
private _refreshIntegrationService: RefreshIntegrationService,
|
||||
private _organizationService: OrganizationService
|
||||
) {}
|
||||
|
||||
@Get('/')
|
||||
getIntegrations() {
|
||||
return this._integrationManager.getAllIntegrations();
|
||||
}
|
||||
|
||||
@Post('/social-connect/:integration')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.CHANNEL])
|
||||
@UseFilters(new NotEnoughScopesFilter())
|
||||
async connectSocialMedia(
|
||||
@Param('integration') integration: string,
|
||||
@Body() body: ConnectIntegrationDto
|
||||
) {
|
||||
if (
|
||||
!this._integrationManager
|
||||
.getAllowedSocialsIntegrations()
|
||||
.includes(integration)
|
||||
) {
|
||||
throw new Error('Integration not allowed');
|
||||
}
|
||||
|
||||
const integrationProvider =
|
||||
this._integrationManager.getSocialIntegration(integration);
|
||||
|
||||
const getCodeVerifier = integrationProvider.customFields
|
||||
? 'none'
|
||||
: await ioRedis.get(`login:${body.state}`);
|
||||
if (!getCodeVerifier) {
|
||||
throw new Error('Invalid state');
|
||||
}
|
||||
|
||||
const organization = await ioRedis.get(`organization:${body.state}`);
|
||||
if (!organization) {
|
||||
throw new Error('Organization not found');
|
||||
}
|
||||
|
||||
const org = await this._organizationService.getOrgById(organization);
|
||||
|
||||
if (!integrationProvider.customFields) {
|
||||
await ioRedis.del(`login:${body.state}`);
|
||||
}
|
||||
|
||||
const details = integrationProvider.externalUrl
|
||||
? await ioRedis.get(`external:${body.state}`)
|
||||
: undefined;
|
||||
|
||||
if (details) {
|
||||
await ioRedis.del(`external:${body.state}`);
|
||||
}
|
||||
|
||||
const refresh = await ioRedis.get(`refresh:${body.state}`);
|
||||
if (refresh) {
|
||||
await ioRedis.del(`refresh:${body.state}`);
|
||||
}
|
||||
|
||||
const onboarding = await ioRedis.get(`onboarding:${body.state}`);
|
||||
if (onboarding) {
|
||||
await ioRedis.del(`onboarding:${body.state}`);
|
||||
}
|
||||
|
||||
const {
|
||||
error,
|
||||
accessToken,
|
||||
expiresIn,
|
||||
refreshToken,
|
||||
id,
|
||||
name,
|
||||
picture,
|
||||
username,
|
||||
additionalSettings,
|
||||
// eslint-disable-next-line no-async-promise-executor
|
||||
} = await new Promise<AuthTokenDetails>(async (res) => {
|
||||
try {
|
||||
const auth = await integrationProvider.authenticate(
|
||||
{
|
||||
code: body.code,
|
||||
codeVerifier: getCodeVerifier,
|
||||
refresh: body.refresh,
|
||||
},
|
||||
details ? JSON.parse(details) : undefined
|
||||
);
|
||||
|
||||
if (typeof auth === 'string') {
|
||||
return res({
|
||||
error: auth,
|
||||
accessToken: '',
|
||||
id: '',
|
||||
name: '',
|
||||
picture: '',
|
||||
username: '',
|
||||
additionalSettings: [],
|
||||
});
|
||||
}
|
||||
|
||||
if (refresh && integrationProvider.reConnect) {
|
||||
console.log('reconnect');
|
||||
try {
|
||||
const newAuth = await integrationProvider.reConnect(
|
||||
auth.id,
|
||||
refresh,
|
||||
auth.accessToken
|
||||
);
|
||||
return res({ ...newAuth, refreshToken: body.refresh });
|
||||
} catch (err: any) {
|
||||
return res({
|
||||
error: err.message,
|
||||
accessToken: '',
|
||||
id: '',
|
||||
name: '',
|
||||
picture: '',
|
||||
username: '',
|
||||
additionalSettings: [],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return res(auth);
|
||||
} catch (err) {
|
||||
if (err instanceof NotEnoughScopes) {
|
||||
return res({
|
||||
error: err.message,
|
||||
accessToken: '',
|
||||
id: '',
|
||||
name: '',
|
||||
picture: '',
|
||||
username: '',
|
||||
additionalSettings: [],
|
||||
});
|
||||
}
|
||||
|
||||
return res({
|
||||
error: 'Authentication failed',
|
||||
accessToken: '',
|
||||
id: '',
|
||||
name: '',
|
||||
picture: '',
|
||||
username: '',
|
||||
additionalSettings: [],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
if (error) {
|
||||
throw new NotEnoughScopes(error);
|
||||
}
|
||||
|
||||
if (!id) {
|
||||
throw new NotEnoughScopes('Invalid API key');
|
||||
}
|
||||
|
||||
if (refresh && String(id) !== String(refresh)) {
|
||||
throw new NotEnoughScopes(
|
||||
'Please refresh the channel that needs to be refreshed'
|
||||
);
|
||||
}
|
||||
|
||||
let validName = name;
|
||||
if (!validName) {
|
||||
if (username) {
|
||||
validName = username.split('.')[0] ?? username;
|
||||
} else {
|
||||
validName = `Channel_${String(id).slice(0, 8)}`;
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
process.env.STRIPE_PUBLISHABLE_KEY &&
|
||||
org.isTrailing &&
|
||||
(await this._integrationService.checkPreviousConnections(
|
||||
org.id,
|
||||
String(id)
|
||||
))
|
||||
) {
|
||||
throw new HttpException('', 412);
|
||||
}
|
||||
|
||||
const createUpdate =
|
||||
await this._integrationService.createOrUpdateIntegration(
|
||||
additionalSettings,
|
||||
!!integrationProvider.oneTimeToken,
|
||||
org.id,
|
||||
validName.trim(),
|
||||
picture,
|
||||
'social',
|
||||
String(id),
|
||||
integration,
|
||||
accessToken,
|
||||
refreshToken,
|
||||
expiresIn,
|
||||
username,
|
||||
refresh ? false : integrationProvider.isBetweenSteps,
|
||||
body.refresh,
|
||||
+body.timezone,
|
||||
details
|
||||
? AuthService.fixedEncryption(details)
|
||||
: integrationProvider.customFields
|
||||
? AuthService.fixedEncryption(
|
||||
Buffer.from(body.code, 'base64').toString()
|
||||
)
|
||||
: integrationProvider.isChromeExtension
|
||||
? AuthService.fixedEncryption(
|
||||
Buffer.from(body.code, 'base64').toString()
|
||||
)
|
||||
: undefined
|
||||
);
|
||||
|
||||
this._refreshIntegrationService
|
||||
.startRefreshWorkflow(org.id, createUpdate.id, integrationProvider)
|
||||
.catch((err) => {
|
||||
console.log(err);
|
||||
});
|
||||
|
||||
// Fetch pages if this is a two-step provider and not a refresh
|
||||
let pages: any[] = [];
|
||||
if (integrationProvider.isBetweenSteps && !refresh) {
|
||||
try {
|
||||
// Check which method the provider uses (pages or companies)
|
||||
const fetchMethod =
|
||||
'pages' in integrationProvider
|
||||
? 'pages'
|
||||
: 'companies' in integrationProvider
|
||||
? 'companies'
|
||||
: null;
|
||||
|
||||
if (fetchMethod) {
|
||||
// @ts-ignore - dynamic method call
|
||||
pages = await integrationProvider[fetchMethod](accessToken);
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('Failed to fetch pages:', err);
|
||||
}
|
||||
}
|
||||
|
||||
const webhookUrl = await ioRedis.get(`webhookUrl:${body.state}`);
|
||||
if (webhookUrl) {
|
||||
try {
|
||||
await fetch(webhookUrl, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
params: AuthService.signJWT({
|
||||
apiKey: org.apiKey,
|
||||
}),
|
||||
}),
|
||||
});
|
||||
} catch (err) {}
|
||||
|
||||
await ioRedis.del(`webhookUrl:${body.state}`);
|
||||
}
|
||||
|
||||
const returnURL = await ioRedis.get(`redirect:${body.state}`);
|
||||
if (returnURL) {
|
||||
await ioRedis.del(`redirect:${body.state}`);
|
||||
}
|
||||
|
||||
const extensionToken = integrationProvider.isChromeExtension
|
||||
? AuthService.signJWT({
|
||||
integrationId: createUpdate.id,
|
||||
organizationId: org.id,
|
||||
internalId: String(id),
|
||||
provider: integration,
|
||||
})
|
||||
: undefined;
|
||||
|
||||
// Never leak stored credentials (signed/encrypted secrets) back to the
|
||||
// caller. These columns hold the integration access token, refresh token
|
||||
// and encrypted custom instance details and must stay server-side.
|
||||
const {
|
||||
token: _token,
|
||||
refreshToken: _refreshToken,
|
||||
customInstanceDetails: _customInstanceDetails,
|
||||
...safeIntegration
|
||||
} = createUpdate as any;
|
||||
|
||||
return {
|
||||
...safeIntegration,
|
||||
onboarding: onboarding === 'true',
|
||||
pages,
|
||||
...(returnURL ? { returnURL } : {}),
|
||||
...(extensionToken ? { extensionToken } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@Post('/public/provider/:id/connect')
|
||||
async saveProviderPage(@Param('id') id: string, @Body() body: any) {
|
||||
if (!body.state) {
|
||||
throw new Error('Invalid state');
|
||||
}
|
||||
|
||||
const organization = await ioRedis.get(`organization:${body.state}`);
|
||||
if (!organization) {
|
||||
throw new Error('Organization not found');
|
||||
}
|
||||
|
||||
const org = await this._organizationService.getOrgById(organization);
|
||||
|
||||
return this._integrationService.saveProviderPage(org.id, id, body);
|
||||
}
|
||||
|
||||
@Post('/extension-refresh')
|
||||
async extensionRefreshCookies(
|
||||
@Body() body: { jwt: string; cookies: string }
|
||||
) {
|
||||
let payload: any;
|
||||
try {
|
||||
payload = AuthService.verifyJWT(body.jwt);
|
||||
} catch {
|
||||
throw new HttpException('Invalid token', 401);
|
||||
}
|
||||
|
||||
const { integrationId, organizationId, internalId, provider } = payload;
|
||||
if (!integrationId || !organizationId || !internalId || !provider) {
|
||||
throw new HttpException('Invalid token payload', 400);
|
||||
}
|
||||
|
||||
const integration = await this._integrationService.getIntegrationById(
|
||||
organizationId,
|
||||
integrationId
|
||||
);
|
||||
if (!integration || integration.internalId !== internalId) {
|
||||
throw new HttpException('Integration not found', 404);
|
||||
}
|
||||
|
||||
const integrationProvider =
|
||||
this._integrationManager.getSocialIntegration(provider);
|
||||
if (!integrationProvider?.isChromeExtension) {
|
||||
throw new HttpException('Not a Chrome extension integration', 400);
|
||||
}
|
||||
|
||||
const authResult = await integrationProvider.authenticate({
|
||||
code: body.cookies,
|
||||
codeVerifier: '',
|
||||
});
|
||||
|
||||
if (typeof authResult === 'string') {
|
||||
throw new HttpException(authResult, 400);
|
||||
}
|
||||
|
||||
if (String(authResult.id) !== String(integration.internalId)) {
|
||||
await this._integrationService.refreshNeeded(
|
||||
organizationId,
|
||||
integrationId
|
||||
);
|
||||
return { success: false, reason: 'account_mismatch' };
|
||||
}
|
||||
|
||||
await this._integrationService.createOrUpdateIntegration(
|
||||
undefined,
|
||||
false,
|
||||
organizationId,
|
||||
integration.name,
|
||||
undefined,
|
||||
'social',
|
||||
integration.internalId,
|
||||
integration.providerIdentifier,
|
||||
authResult.accessToken,
|
||||
'',
|
||||
authResult.expiresIn,
|
||||
undefined,
|
||||
false,
|
||||
undefined,
|
||||
undefined,
|
||||
AuthService.signJWT(
|
||||
JSON.parse(Buffer.from(body.cookies, 'base64').toString())
|
||||
)
|
||||
);
|
||||
|
||||
return { success: true };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import { GetUserFromRequest } from '@gitroom/nestjs-libraries/user/user.from.request';
|
||||
import { Organization, User } from '@prisma/client';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { NotificationService } from '@gitroom/nestjs-libraries/database/prisma/notifications/notification.service';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
|
||||
@ApiTags('Notifications')
|
||||
@Controller('/notifications')
|
||||
export class NotificationsController {
|
||||
constructor(private _notificationsService: NotificationService) {}
|
||||
@Get('/')
|
||||
async mainPageList(
|
||||
@GetUserFromRequest() user: User,
|
||||
@GetOrgFromRequest() organization: Organization
|
||||
) {
|
||||
return this._notificationsService.getMainPageCount(
|
||||
organization.id,
|
||||
user.id
|
||||
);
|
||||
}
|
||||
|
||||
@Get('/list')
|
||||
async notifications(
|
||||
@GetUserFromRequest() user: User,
|
||||
@GetOrgFromRequest() organization: Organization
|
||||
) {
|
||||
return this._notificationsService.getNotifications(
|
||||
organization.id,
|
||||
user.id
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { Body, Controller, Delete, Get, Post, Put } from '@nestjs/common';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { Organization } from '@prisma/client';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { OAuthService } from '@gitroom/nestjs-libraries/database/prisma/oauth/oauth.service';
|
||||
import { CheckPolicies } from '@gitroom/backend/services/auth/permissions/permissions.ability';
|
||||
import {
|
||||
AuthorizationActions,
|
||||
Sections,
|
||||
} from '@gitroom/backend/services/auth/permissions/permission.exception.class';
|
||||
import { CreateOAuthAppDto } from '@gitroom/nestjs-libraries/dtos/oauth/create-oauth-app.dto';
|
||||
import { UpdateOAuthAppDto } from '@gitroom/nestjs-libraries/dtos/oauth/update-oauth-app.dto';
|
||||
|
||||
@ApiTags('OAuth App')
|
||||
@Controller('/user/oauth-app')
|
||||
export class OAuthAppController {
|
||||
constructor(private _oauthService: OAuthService) {}
|
||||
|
||||
@Get('/')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
|
||||
async getApp(@GetOrgFromRequest() org: Organization) {
|
||||
return this._oauthService.getApp(org.id);
|
||||
}
|
||||
|
||||
@Post('/')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
|
||||
async createApp(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: CreateOAuthAppDto
|
||||
) {
|
||||
return this._oauthService.createApp(org.id, body);
|
||||
}
|
||||
|
||||
@Put('/')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
|
||||
async updateApp(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: UpdateOAuthAppDto
|
||||
) {
|
||||
return this._oauthService.updateApp(org.id, body);
|
||||
}
|
||||
|
||||
@Delete('/')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
|
||||
async deleteApp(@GetOrgFromRequest() org: Organization) {
|
||||
return this._oauthService.deleteApp(org.id);
|
||||
}
|
||||
|
||||
@Post('/rotate-secret')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
|
||||
async rotateSecret(@GetOrgFromRequest() org: Organization) {
|
||||
return this._oauthService.rotateSecret(org.id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Post,
|
||||
Query,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { OAuthService } from '@gitroom/nestjs-libraries/database/prisma/oauth/oauth.service';
|
||||
import { GetUserFromRequest } from '@gitroom/nestjs-libraries/user/user.from.request';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { User, Organization } from '@prisma/client';
|
||||
import { AuthorizeOAuthQueryDto, ApproveOAuthDto } from '@gitroom/nestjs-libraries/dtos/oauth/authorize-oauth.dto';
|
||||
import { TokenExchangeDto } from '@gitroom/nestjs-libraries/dtos/oauth/token-exchange.dto';
|
||||
|
||||
@ApiTags('OAuth')
|
||||
@Controller('/oauth')
|
||||
export class OAuthController {
|
||||
constructor(private _oauthService: OAuthService) {}
|
||||
|
||||
@Get('/authorize')
|
||||
async authorize(@Query() query: AuthorizeOAuthQueryDto) {
|
||||
const app = await this._oauthService.validateAuthorizationRequest(
|
||||
query.client_id
|
||||
);
|
||||
|
||||
return {
|
||||
app: {
|
||||
name: app.name,
|
||||
description: app.description,
|
||||
picture: app.picture,
|
||||
clientId: app.clientId,
|
||||
redirectUrl: app.redirectUrl,
|
||||
},
|
||||
state: query.state,
|
||||
};
|
||||
}
|
||||
|
||||
@Post('/token')
|
||||
async token(@Body() body: TokenExchangeDto) {
|
||||
if (body.grant_type !== 'authorization_code') {
|
||||
throw new HttpException(
|
||||
{ error: 'unsupported_grant_type' },
|
||||
HttpStatus.BAD_REQUEST
|
||||
);
|
||||
}
|
||||
|
||||
return this._oauthService.exchangeCodeForToken(
|
||||
body.code,
|
||||
body.client_id,
|
||||
body.client_secret
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ApiTags('OAuth')
|
||||
@Controller('/oauth')
|
||||
export class OAuthAuthorizedController {
|
||||
constructor(private _oauthService: OAuthService) {}
|
||||
|
||||
@Post('/authorize')
|
||||
async approveOrDeny(
|
||||
@Body() body: ApproveOAuthDto,
|
||||
@GetUserFromRequest() user: User,
|
||||
@GetOrgFromRequest() org: Organization
|
||||
) {
|
||||
const app = await this._oauthService.validateAuthorizationRequest(
|
||||
body.client_id
|
||||
);
|
||||
|
||||
if (body.action === 'deny') {
|
||||
const redirectUrl = new URL(app.redirectUrl);
|
||||
redirectUrl.searchParams.set('error', 'access_denied');
|
||||
if (body.state) {
|
||||
redirectUrl.searchParams.set('state', body.state);
|
||||
}
|
||||
return { redirect: redirectUrl.toString() };
|
||||
}
|
||||
|
||||
const code = await this._oauthService.createAuthorizationCode(
|
||||
app.id,
|
||||
user.id,
|
||||
org.id
|
||||
);
|
||||
|
||||
const redirectUrl = new URL(app.redirectUrl);
|
||||
redirectUrl.searchParams.set('code', code);
|
||||
if (body.state) {
|
||||
redirectUrl.searchParams.set('state', body.state);
|
||||
}
|
||||
return { redirect: redirectUrl.toString() };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
HttpException,
|
||||
Param,
|
||||
Post,
|
||||
Put,
|
||||
Query,
|
||||
Res,
|
||||
} from '@nestjs/common';
|
||||
import { PostsService } from '@gitroom/nestjs-libraries/database/prisma/posts/posts.service';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { Organization, User } from '@prisma/client';
|
||||
import { GetPostsDto } from '@gitroom/nestjs-libraries/dtos/posts/get.posts.dto';
|
||||
import { GetPostsListDto } from '@gitroom/nestjs-libraries/dtos/posts/get.posts.list.dto';
|
||||
import { CheckPolicies } from '@gitroom/backend/services/auth/permissions/permissions.ability';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { GeneratorDto } from '@gitroom/nestjs-libraries/dtos/generator/generator.dto';
|
||||
import { CreateGeneratedPostsDto } from '@gitroom/nestjs-libraries/dtos/generator/create.generated.posts.dto';
|
||||
import { AgentGraphService } from '@gitroom/nestjs-libraries/agent/agent.graph.service';
|
||||
import { Response } from 'express';
|
||||
import { GetUserFromRequest } from '@gitroom/nestjs-libraries/user/user.from.request';
|
||||
import { ShortLinkService } from '@gitroom/nestjs-libraries/short-linking/short.link.service';
|
||||
import { CreateTagDto } from '@gitroom/nestjs-libraries/dtos/posts/create.tag.dto';
|
||||
import {
|
||||
AuthorizationActions,
|
||||
Sections,
|
||||
} from '@gitroom/backend/services/auth/permissions/permission.exception.class';
|
||||
import { PostValidationException } from '@gitroom/backend/api/routes/posts.validation.exception';
|
||||
|
||||
@ApiTags('Posts')
|
||||
@Controller('/posts')
|
||||
export class PostsController {
|
||||
constructor(
|
||||
private _postsService: PostsService,
|
||||
private _agentGraphService: AgentGraphService,
|
||||
private _shortLinkService: ShortLinkService
|
||||
) {}
|
||||
|
||||
@Get('/:id/statistics')
|
||||
async getStatistics(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
return this._postsService.getStatistics(org.id, id);
|
||||
}
|
||||
|
||||
@Get('/:id/missing')
|
||||
async getMissingContent(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
return this._postsService.getMissingContent(org.id, id);
|
||||
}
|
||||
|
||||
@Put('/:id/release-id')
|
||||
async updateReleaseId(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string,
|
||||
@Body('releaseId') releaseId: string
|
||||
) {
|
||||
return this._postsService.updateReleaseId(org.id, id, releaseId);
|
||||
}
|
||||
|
||||
@Post('/should-shortlink')
|
||||
async shouldShortlink(@Body() body: { messages: string[] }) {
|
||||
return { ask: this._shortLinkService.askShortLinkedin(body.messages) };
|
||||
}
|
||||
|
||||
@Post('/:id/comments')
|
||||
async createComment(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@GetUserFromRequest() user: User,
|
||||
@Param('id') id: string,
|
||||
@Body() body: { comment: string }
|
||||
) {
|
||||
return this._postsService.createComment(org.id, user.id, id, body.comment);
|
||||
}
|
||||
|
||||
@Get('/tags')
|
||||
async getTags(@GetOrgFromRequest() org: Organization) {
|
||||
return { tags: await this._postsService.getTags(org.id) };
|
||||
}
|
||||
|
||||
@Post('/tags')
|
||||
async createTag(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: CreateTagDto
|
||||
) {
|
||||
return this._postsService.createTag(org.id, body);
|
||||
}
|
||||
|
||||
@Put('/tags/:id')
|
||||
async editTag(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: CreateTagDto,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
return this._postsService.editTag(id, org.id, body);
|
||||
}
|
||||
|
||||
@Delete('/tags/:id')
|
||||
async deleteTag(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
return this._postsService.deleteTag(id, org.id);
|
||||
}
|
||||
|
||||
@Get('/')
|
||||
async getPosts(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Query() query: GetPostsDto
|
||||
) {
|
||||
return this._postsService.getPostsMinified(org.id, query);
|
||||
}
|
||||
|
||||
@Get('/find-slot')
|
||||
async findSlot(@GetOrgFromRequest() org: Organization) {
|
||||
return { date: await this._postsService.findFreeDateTime(org.id) };
|
||||
}
|
||||
|
||||
@Get('/find-slot/:id')
|
||||
async findSlotIntegration(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id?: string
|
||||
) {
|
||||
return { date: await this._postsService.findFreeDateTime(org.id, id) };
|
||||
}
|
||||
|
||||
@Get('/list')
|
||||
async getPostsList(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Query() query: GetPostsListDto
|
||||
) {
|
||||
return this._postsService.getPostsList(org.id, query);
|
||||
}
|
||||
|
||||
@Get('/old')
|
||||
oldPosts(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Query('date') date: string
|
||||
) {
|
||||
return this._postsService.getOldPosts(org.id, date);
|
||||
}
|
||||
|
||||
@Get('/group/:group/debug-export')
|
||||
async getPostGroupDebugExport(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@GetUserFromRequest() user: User,
|
||||
@Param('group') group: string
|
||||
) {
|
||||
if (!user.isSuperAdmin) {
|
||||
throw new HttpException('Forbidden', 403);
|
||||
}
|
||||
return this._postsService.getPostGroupDebugExport(org.id, group);
|
||||
}
|
||||
|
||||
@Get('/group/:group')
|
||||
getPostsByGroup(@GetOrgFromRequest() org: Organization, @Param('group') group: string) {
|
||||
return this._postsService.getPostsByGroup(org.id, group);
|
||||
}
|
||||
|
||||
@Get('/:id')
|
||||
getPost(@GetOrgFromRequest() org: Organization, @Param('id') id: string) {
|
||||
return this._postsService.getPost(org.id, id);
|
||||
}
|
||||
|
||||
@Post('/valid')
|
||||
async validatePosts(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() rawBody: any
|
||||
) {
|
||||
return this._postsService.validatePosts(org.id, rawBody?.posts || []);
|
||||
}
|
||||
|
||||
@Post('/')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.POSTS_PER_MONTH])
|
||||
async createPost(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() rawBody: any
|
||||
) {
|
||||
// Server-side validation — never trust the client to have validated.
|
||||
const validation = await this._postsService.validatePosts(
|
||||
org.id,
|
||||
rawBody?.posts || []
|
||||
);
|
||||
|
||||
const fail = (item: (typeof validation)[number], error: string) => {
|
||||
throw new PostValidationException({
|
||||
provider: item.identifier,
|
||||
name: item.name,
|
||||
error,
|
||||
});
|
||||
};
|
||||
|
||||
for (const item of validation) {
|
||||
if (item.emptyContent) {
|
||||
fail(
|
||||
item,
|
||||
'Your post should have at least one character or one image.'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (rawBody?.type !== 'draft') {
|
||||
for (const item of validation) {
|
||||
if (!item.valid) {
|
||||
fail(item, item.settingsError || 'Please fix your settings');
|
||||
}
|
||||
if (item.errors !== true) {
|
||||
fail(item, item.errors as string);
|
||||
}
|
||||
if (item.tooLong) {
|
||||
fail(item, 'post is too long, please fix it');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const body = await this._postsService.mapTypeToPost(rawBody, org.id);
|
||||
return this._postsService.createPost(org.id, body, 'WEB');
|
||||
}
|
||||
|
||||
@Post('/generator/draft')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.POSTS_PER_MONTH])
|
||||
generatePostsDraft(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: CreateGeneratedPostsDto
|
||||
) {
|
||||
return this._postsService.generatePostsDraft(org.id, body);
|
||||
}
|
||||
|
||||
@Post('/generator')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.POSTS_PER_MONTH])
|
||||
async generatePosts(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: GeneratorDto,
|
||||
@Res({ passthrough: false }) res: Response
|
||||
) {
|
||||
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
||||
for await (const event of this._agentGraphService.start(org.id, body)) {
|
||||
res.write(JSON.stringify(event) + '\n');
|
||||
}
|
||||
|
||||
res.end();
|
||||
}
|
||||
|
||||
@Delete('/:group')
|
||||
deletePost(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('group') group: string
|
||||
) {
|
||||
return this._postsService.deletePost(org.id, group);
|
||||
}
|
||||
|
||||
@Put('/:id/date')
|
||||
changeDate(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string,
|
||||
@Body('date') date: string,
|
||||
@Body('action') action: 'schedule' | 'update' = 'schedule'
|
||||
) {
|
||||
return this._postsService.changeDate(org.id, id, date, action);
|
||||
}
|
||||
|
||||
@Post('/separate-posts')
|
||||
async separatePosts(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: { content: string; len: number }
|
||||
) {
|
||||
return this._postsService.separatePosts(body.content, body.len);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import {
|
||||
ArgumentsHost,
|
||||
Catch,
|
||||
ExceptionFilter,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
|
||||
export type PostValidationError = {
|
||||
/** Provider identifier, e.g. "x", "linkedin-page". */
|
||||
provider: string;
|
||||
/** Human readable provider name, e.g. "X", "LinkedIn Page". */
|
||||
name: string;
|
||||
/** The readable validation error. */
|
||||
error: string;
|
||||
};
|
||||
|
||||
export class PostValidationException extends HttpException {
|
||||
constructor(message: PostValidationError) {
|
||||
super(message, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
@Catch(PostValidationException)
|
||||
export class PostValidationExceptionFilter implements ExceptionFilter {
|
||||
catch(exception: PostValidationException, host: ArgumentsHost) {
|
||||
const ctx = host.switchToHttp();
|
||||
const response = ctx.getResponse();
|
||||
const status = exception.getStatus();
|
||||
const { provider, name, error } =
|
||||
exception.getResponse() as PostValidationError;
|
||||
|
||||
response.status(status).json({
|
||||
statusCode: status,
|
||||
provider,
|
||||
name,
|
||||
message: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Param,
|
||||
Post,
|
||||
Query,
|
||||
Req,
|
||||
Res,
|
||||
StreamableFile,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { PostsService } from '@gitroom/nestjs-libraries/database/prisma/posts/posts.service';
|
||||
import { TrackService } from '@gitroom/nestjs-libraries/track/track.service';
|
||||
import { RealIP } from 'nestjs-real-ip';
|
||||
import { UserAgent } from '@gitroom/nestjs-libraries/user/user.agent';
|
||||
import { TrackEnum } from '@gitroom/nestjs-libraries/user/track.enum';
|
||||
import { Request, Response } from 'express';
|
||||
import { makeId } from '@gitroom/nestjs-libraries/services/make.is';
|
||||
import { getCookieUrlFromDomain } from '@gitroom/helpers/subdomain/subdomain.management';
|
||||
import { AgentGraphInsertService } from '@gitroom/nestjs-libraries/agent/agent.graph.insert.service';
|
||||
import { SubscriptionService } from '@gitroom/nestjs-libraries/database/prisma/subscriptions/subscription.service';
|
||||
import { AuthService } from '@gitroom/helpers/auth/auth.service';
|
||||
import { pricing } from '@gitroom/nestjs-libraries/database/prisma/subscriptions/pricing';
|
||||
import { Readable, pipeline } from 'stream';
|
||||
import { promisify } from 'util';
|
||||
import { OnlyURL } from '@gitroom/nestjs-libraries/dtos/webhooks/webhooks.dto';
|
||||
import { isSafePublicHttpsUrl } from '@gitroom/nestjs-libraries/dtos/webhooks/webhook.url.validator';
|
||||
import { ssrfSafeDispatcher } from '@gitroom/nestjs-libraries/dtos/webhooks/ssrf.safe.dispatcher';
|
||||
|
||||
const pump = promisify(pipeline);
|
||||
|
||||
@ApiTags('Public')
|
||||
@Controller('/public')
|
||||
export class PublicController {
|
||||
constructor(
|
||||
private _trackService: TrackService,
|
||||
private _agentGraphInsertService: AgentGraphInsertService,
|
||||
private _postsService: PostsService,
|
||||
private _subscriptionService: SubscriptionService
|
||||
) {}
|
||||
@Post('/agent')
|
||||
async createAgent(@Body() body: { text: string; apiKey: string }) {
|
||||
if (
|
||||
!body.apiKey ||
|
||||
!process.env.AGENT_API_KEY ||
|
||||
body.apiKey !== process.env.AGENT_API_KEY
|
||||
) {
|
||||
return;
|
||||
}
|
||||
return this._agentGraphInsertService.newPost(body.text);
|
||||
}
|
||||
|
||||
@Get(`/posts/:id`)
|
||||
async getPreview(@Param('id') id: string) {
|
||||
return (await this._postsService.getPostsRecursively(id, true)).map(
|
||||
({ childrenPost, ...p }) => ({
|
||||
...p,
|
||||
...(p.integration
|
||||
? {
|
||||
integration: {
|
||||
id: p.integration.id,
|
||||
name: p.integration.name,
|
||||
picture: p.integration.picture,
|
||||
providerIdentifier: p.integration.providerIdentifier,
|
||||
profile: p.integration.profile,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@Get(`/posts/:id/comments`)
|
||||
async getComments(@Param('id') postId: string) {
|
||||
return { comments: await this._postsService.getComments(postId) };
|
||||
}
|
||||
|
||||
@Post('/t')
|
||||
async trackEvent(
|
||||
@Res() res: Response,
|
||||
@Req() req: Request,
|
||||
@RealIP() ip: string,
|
||||
@UserAgent() userAgent: string,
|
||||
@Body()
|
||||
body: { fbclid?: string; tt: TrackEnum; additional: Record<string, any> }
|
||||
) {
|
||||
const uniqueId = req?.cookies?.track || makeId(10);
|
||||
const fbclid = req?.cookies?.fbclid || body.fbclid;
|
||||
await this._trackService.track(
|
||||
uniqueId,
|
||||
ip,
|
||||
userAgent,
|
||||
body.tt,
|
||||
body.additional,
|
||||
fbclid
|
||||
);
|
||||
if (!req.cookies.track) {
|
||||
res.cookie('track', uniqueId, {
|
||||
domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),
|
||||
...(!process.env.NOT_SECURED
|
||||
? {
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
}
|
||||
: {}),
|
||||
sameSite: 'none',
|
||||
expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),
|
||||
});
|
||||
}
|
||||
|
||||
if (body.fbclid && !req.cookies.fbclid) {
|
||||
res.cookie('fbclid', body.fbclid, {
|
||||
domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),
|
||||
...(!process.env.NOT_SECURED
|
||||
? {
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
}
|
||||
: {}),
|
||||
sameSite: 'none',
|
||||
expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),
|
||||
});
|
||||
}
|
||||
|
||||
res.status(200).json({
|
||||
track: uniqueId,
|
||||
});
|
||||
}
|
||||
|
||||
@Post('/modify-subscription')
|
||||
async modifySubscription(@Body('params') params: string) {
|
||||
try {
|
||||
const load = AuthService.verifyJWT(params) as {
|
||||
orgId: string;
|
||||
billing: 'FREE' | 'STANDARD' | 'TEAM' | 'PRO' | 'ULTIMATE';
|
||||
};
|
||||
|
||||
if (!load || !load.orgId || !load.billing || !pricing[load.billing]) {
|
||||
return { success: false };
|
||||
}
|
||||
|
||||
const totalChannels = pricing[load.billing].channel || 0;
|
||||
|
||||
await this._subscriptionService.modifySubscriptionByOrg(
|
||||
load.orgId,
|
||||
totalChannels,
|
||||
load.billing
|
||||
);
|
||||
|
||||
return { success: true };
|
||||
} catch (err) {
|
||||
return { success: false };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Get('/stream')
|
||||
async streamFile(
|
||||
@Query() query: OnlyURL,
|
||||
@Res() res: Response,
|
||||
@Req() req: Request
|
||||
) {
|
||||
const { url } = query;
|
||||
if (!url.endsWith('mp4')) {
|
||||
return res.status(400).send('Invalid video URL');
|
||||
}
|
||||
|
||||
const ac = new AbortController();
|
||||
const onClose = () => ac.abort();
|
||||
req.on('aborted', onClose);
|
||||
res.on('close', onClose);
|
||||
|
||||
// Manually follow redirects so every hop is re-validated against
|
||||
// the SSRF blocklist (see GHSA-34w8-5j2v-h6ww). `fetch` defaults to
|
||||
// `redirect: 'follow'`, which bypasses the DTO-level URL check.
|
||||
const MAX_REDIRECTS = 5;
|
||||
let currentUrl = url;
|
||||
let r: globalThis.Response | undefined;
|
||||
for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
|
||||
if (!(await isSafePublicHttpsUrl(currentUrl))) {
|
||||
return res.status(400).send('Blocked URL');
|
||||
}
|
||||
|
||||
r = await fetch(currentUrl, {
|
||||
signal: ac.signal,
|
||||
redirect: 'manual',
|
||||
// @ts-ignore — undici option, not in lib.dom fetch types
|
||||
dispatcher: ssrfSafeDispatcher,
|
||||
});
|
||||
|
||||
if (r.status >= 300 && r.status < 400) {
|
||||
const location = r.headers.get('location');
|
||||
if (!location) {
|
||||
return res.status(502).send('Redirect without Location');
|
||||
}
|
||||
try {
|
||||
currentUrl = new URL(location, currentUrl).toString();
|
||||
} catch {
|
||||
return res.status(400).send('Invalid redirect target');
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
if (!r) {
|
||||
return res.status(502).send('No upstream response');
|
||||
}
|
||||
|
||||
if (r.status >= 300 && r.status < 400) {
|
||||
return res.status(508).send('Too many redirects');
|
||||
}
|
||||
|
||||
if (!r.ok && r.status !== 206) {
|
||||
res.status(r.status);
|
||||
throw new Error(`Upstream error: ${r.statusText}`);
|
||||
}
|
||||
|
||||
const type = r.headers.get('content-type') ?? 'application/octet-stream';
|
||||
res.setHeader('Content-Type', type);
|
||||
|
||||
const contentRange = r.headers.get('content-range');
|
||||
if (contentRange) res.setHeader('Content-Range', contentRange);
|
||||
|
||||
const len = r.headers.get('content-length');
|
||||
if (len) res.setHeader('Content-Length', len);
|
||||
|
||||
const acceptRanges = r.headers.get('accept-ranges') ?? 'bytes';
|
||||
res.setHeader('Accept-Ranges', acceptRanges);
|
||||
|
||||
if (r.status === 206) res.status(206); // Partial Content for range responses
|
||||
|
||||
try {
|
||||
await pump(Readable.fromWeb(r.body as any), res);
|
||||
} catch (err) {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
@Controller('/')
|
||||
export class RootController {
|
||||
@Get('/')
|
||||
getRoot(): string {
|
||||
return 'App is running!';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
Post,
|
||||
Put,
|
||||
} from '@nestjs/common';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { Organization } from '@prisma/client';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { SetsService } from '@gitroom/nestjs-libraries/database/prisma/sets/sets.service';
|
||||
import {
|
||||
UpdateSetsDto,
|
||||
SetsDto,
|
||||
} from '@gitroom/nestjs-libraries/dtos/sets/sets.dto';
|
||||
|
||||
@ApiTags('Sets')
|
||||
@Controller('/sets')
|
||||
export class SetsController {
|
||||
constructor(private _setsService: SetsService) {}
|
||||
|
||||
@Get('/')
|
||||
async getSets(@GetOrgFromRequest() org: Organization) {
|
||||
return this._setsService.getSets(org.id);
|
||||
}
|
||||
|
||||
@Post('/')
|
||||
async createASet(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: SetsDto
|
||||
) {
|
||||
return this._setsService.createSet(org.id, body);
|
||||
}
|
||||
|
||||
@Put('/')
|
||||
async updateSet(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: UpdateSetsDto
|
||||
) {
|
||||
return this._setsService.createSet(org.id, body);
|
||||
}
|
||||
|
||||
@Delete('/:id')
|
||||
async deleteSet(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
return this._setsService.deleteSet(org.id, id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { Body, Controller, Delete, Get, Param, Post } from '@nestjs/common';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { Organization } from '@prisma/client';
|
||||
import { CheckPolicies } from '@gitroom/backend/services/auth/permissions/permissions.ability';
|
||||
import { OrganizationService } from '@gitroom/nestjs-libraries/database/prisma/organizations/organization.service';
|
||||
import { AddTeamMemberDto } from '@gitroom/nestjs-libraries/dtos/settings/add.team.member.dto';
|
||||
import { ShortlinkPreferenceDto } from '@gitroom/nestjs-libraries/dtos/settings/shortlink-preference.dto';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { AuthorizationActions, Sections } from '@gitroom/backend/services/auth/permissions/permission.exception.class';
|
||||
|
||||
@ApiTags('Settings')
|
||||
@Controller('/settings')
|
||||
export class SettingsController {
|
||||
constructor(
|
||||
private _organizationService: OrganizationService
|
||||
) {}
|
||||
|
||||
@Get('/team')
|
||||
@CheckPolicies(
|
||||
[AuthorizationActions.Create, Sections.TEAM_MEMBERS],
|
||||
[AuthorizationActions.Create, Sections.ADMIN]
|
||||
)
|
||||
async getTeam(@GetOrgFromRequest() org: Organization) {
|
||||
return this._organizationService.getTeam(org.id);
|
||||
}
|
||||
|
||||
@Post('/team')
|
||||
@CheckPolicies(
|
||||
[AuthorizationActions.Create, Sections.TEAM_MEMBERS],
|
||||
[AuthorizationActions.Create, Sections.ADMIN]
|
||||
)
|
||||
async inviteTeamMember(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: AddTeamMemberDto
|
||||
) {
|
||||
return this._organizationService.inviteTeamMember(org.id, body);
|
||||
}
|
||||
|
||||
@Delete('/team/:id')
|
||||
@CheckPolicies(
|
||||
[AuthorizationActions.Create, Sections.TEAM_MEMBERS],
|
||||
[AuthorizationActions.Create, Sections.ADMIN]
|
||||
)
|
||||
deleteTeamMember(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
return this._organizationService.deleteTeamMember(org, id);
|
||||
}
|
||||
|
||||
@Get('/shortlink')
|
||||
async getShortlinkPreference(@GetOrgFromRequest() org: Organization) {
|
||||
return this._organizationService.getShortlinkPreference(org.id);
|
||||
}
|
||||
|
||||
@Post('/shortlink')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
|
||||
async updateShortlinkPreference(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: ShortlinkPreferenceDto
|
||||
) {
|
||||
return this._organizationService.updateShortlinkPreference(
|
||||
org.id,
|
||||
body.shortlink
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { Body, Controller, Delete, Get, Param, Post, Put } from '@nestjs/common';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { Organization } from '@prisma/client';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { SignatureService } from '@gitroom/nestjs-libraries/database/prisma/signatures/signature.service';
|
||||
import { SignatureDto } from '@gitroom/nestjs-libraries/dtos/signature/signature.dto';
|
||||
|
||||
@ApiTags('Signatures')
|
||||
@Controller('/signatures')
|
||||
export class SignatureController {
|
||||
constructor(private _signatureService: SignatureService) {}
|
||||
|
||||
@Get('/')
|
||||
async getSignatures(@GetOrgFromRequest() org: Organization) {
|
||||
return this._signatureService.getSignaturesByOrgId(org.id);
|
||||
}
|
||||
|
||||
@Get('/default')
|
||||
async getDefaultSignature(@GetOrgFromRequest() org: Organization) {
|
||||
return (await this._signatureService.getDefaultSignature(org.id)) || {};
|
||||
}
|
||||
|
||||
@Post('/')
|
||||
async createSignature(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: SignatureDto
|
||||
) {
|
||||
return this._signatureService.createOrUpdateSignature(org.id, body);
|
||||
}
|
||||
|
||||
@Delete('/:id')
|
||||
async deleteSignature(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
return this._signatureService.deleteSignature(org.id, id);
|
||||
}
|
||||
|
||||
@Put('/:id')
|
||||
async updateSignature(
|
||||
@Param('id') id: string,
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: SignatureDto
|
||||
) {
|
||||
return this._signatureService.createOrUpdateSignature(org.id, body, id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import {
|
||||
Controller,
|
||||
HttpException,
|
||||
Post,
|
||||
RawBodyRequest,
|
||||
Req,
|
||||
} from '@nestjs/common';
|
||||
import { StripeService } from '@gitroom/nestjs-libraries/services/stripe.service';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
|
||||
@ApiTags('Stripe')
|
||||
@Controller('/stripe')
|
||||
export class StripeController {
|
||||
constructor(
|
||||
private readonly _stripeService: StripeService,
|
||||
) {}
|
||||
|
||||
@Post('/')
|
||||
stripe(@Req() req: RawBodyRequest<Request>) {
|
||||
const event = this._stripeService.validateRequest(
|
||||
req.rawBody,
|
||||
// @ts-ignore
|
||||
req.headers['stripe-signature'],
|
||||
process.env.STRIPE_SIGNING_KEY
|
||||
);
|
||||
|
||||
// Maybe it comes from another stripe webhook
|
||||
if (
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
event?.data?.object?.metadata?.service !== 'gitroom' &&
|
||||
event.type !== 'invoice.payment_succeeded'
|
||||
) {
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
try {
|
||||
switch (event.type) {
|
||||
case 'invoice.payment_succeeded':
|
||||
return this._stripeService.paymentSucceeded(event);
|
||||
case 'customer.subscription.created':
|
||||
return this._stripeService.createSubscription(event);
|
||||
case 'customer.subscription.updated':
|
||||
return this._stripeService.updateSubscription(event);
|
||||
case 'customer.subscription.deleted':
|
||||
return this._stripeService.deleteSubscription(event);
|
||||
default:
|
||||
return { ok: true };
|
||||
}
|
||||
} catch (e) {
|
||||
throw new HttpException(e, 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
HttpException,
|
||||
Param,
|
||||
Post,
|
||||
Delete,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { ThirdPartyManager } from '@gitroom/nestjs-libraries/3rdparties/thirdparty.manager';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { Organization } from '@prisma/client';
|
||||
import { AuthService } from '@gitroom/helpers/auth/auth.service';
|
||||
import { UploadFactory } from '@gitroom/nestjs-libraries/upload/upload.factory';
|
||||
import { MediaService } from '@gitroom/nestjs-libraries/database/prisma/media/media.service';
|
||||
import { ImportMediaDto } from '@gitroom/nestjs-libraries/dtos/third-party/import-media.dto';
|
||||
|
||||
@ApiTags('Third Party')
|
||||
@Controller('/third-party')
|
||||
export class ThirdPartyController {
|
||||
private storage = UploadFactory.createStorage();
|
||||
|
||||
constructor(
|
||||
private _thirdPartyManager: ThirdPartyManager,
|
||||
private _mediaService: MediaService,
|
||||
) {}
|
||||
|
||||
@Get('/list')
|
||||
async getThirdPartyList() {
|
||||
return this._thirdPartyManager.getAllThirdParties();
|
||||
}
|
||||
|
||||
@Get('/')
|
||||
async getSavedThirdParty(@GetOrgFromRequest() organization: Organization) {
|
||||
return Promise.all(
|
||||
(
|
||||
await this._thirdPartyManager.getAllThirdPartiesByOrganization(
|
||||
organization.id
|
||||
)
|
||||
).map((thirdParty) => {
|
||||
const { description, fields, position, title, identifier } =
|
||||
this._thirdPartyManager.getThirdPartyByName(thirdParty.identifier);
|
||||
return {
|
||||
...thirdParty,
|
||||
title,
|
||||
position,
|
||||
fields,
|
||||
description,
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@Delete('/:id')
|
||||
deleteById(
|
||||
@GetOrgFromRequest() organization: Organization,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
return this._thirdPartyManager.deleteIntegration(organization.id, id);
|
||||
}
|
||||
|
||||
@Post('/:id/submit')
|
||||
async generate(
|
||||
@GetOrgFromRequest() organization: Organization,
|
||||
@Param('id') id: string,
|
||||
@Body() data: any
|
||||
) {
|
||||
const thirdParty = await this._thirdPartyManager.getIntegrationById(
|
||||
organization.id,
|
||||
id
|
||||
);
|
||||
|
||||
if (!thirdParty) {
|
||||
throw new HttpException('Integration not found', 404);
|
||||
}
|
||||
|
||||
const thirdPartyInstance = this._thirdPartyManager.getThirdPartyByName(
|
||||
thirdParty.identifier
|
||||
);
|
||||
|
||||
if (!thirdPartyInstance) {
|
||||
throw new HttpException('Invalid identifier', 400);
|
||||
}
|
||||
|
||||
const loadedData = await thirdPartyInstance?.instance?.sendData(
|
||||
AuthService.fixedDecryption(thirdParty.apiKey),
|
||||
data
|
||||
);
|
||||
|
||||
const file = await this.storage.uploadSimple(loadedData);
|
||||
return this._mediaService.saveFile(organization.id, file.split('/').pop(), file);
|
||||
}
|
||||
|
||||
@Post('/function/:id/:functionName')
|
||||
async callFunction(
|
||||
@GetOrgFromRequest() organization: Organization,
|
||||
@Param('id') id: string,
|
||||
@Param('functionName') functionName: string,
|
||||
@Body() data: any
|
||||
) {
|
||||
const thirdParty = await this._thirdPartyManager.getIntegrationById(
|
||||
organization.id,
|
||||
id
|
||||
);
|
||||
|
||||
if (!thirdParty) {
|
||||
throw new HttpException('Integration not found', 404);
|
||||
}
|
||||
|
||||
const thirdPartyInstance = this._thirdPartyManager.getThirdPartyByName(
|
||||
thirdParty.identifier
|
||||
);
|
||||
|
||||
if (!thirdPartyInstance) {
|
||||
throw new HttpException('Invalid identifier', 400);
|
||||
}
|
||||
|
||||
return thirdPartyInstance?.instance?.[functionName](
|
||||
AuthService.fixedDecryption(thirdParty.apiKey),
|
||||
data
|
||||
);
|
||||
}
|
||||
|
||||
@Post('/:id/import')
|
||||
async importMedia(
|
||||
@GetOrgFromRequest() organization: Organization,
|
||||
@Param('id') id: string,
|
||||
@Body() body: ImportMediaDto
|
||||
) {
|
||||
const thirdParty = await this._thirdPartyManager.getIntegrationById(
|
||||
organization.id,
|
||||
id
|
||||
);
|
||||
|
||||
if (!thirdParty) {
|
||||
throw new HttpException('Integration not found', 404);
|
||||
}
|
||||
|
||||
const thirdPartyInstance = this._thirdPartyManager.getThirdPartyByName(
|
||||
thirdParty.identifier
|
||||
);
|
||||
|
||||
if (!thirdPartyInstance) {
|
||||
throw new HttpException('Invalid identifier', 400);
|
||||
}
|
||||
|
||||
const downloadUrls = await thirdPartyInstance?.instance?.['importMedia']?.(
|
||||
AuthService.fixedDecryption(thirdParty.apiKey),
|
||||
body.items
|
||||
);
|
||||
|
||||
if (!downloadUrls || !Array.isArray(downloadUrls)) {
|
||||
throw new HttpException('Import not supported', 400);
|
||||
}
|
||||
|
||||
const results = [];
|
||||
for (const item of downloadUrls) {
|
||||
const file = await this.storage.uploadSimple(item.url);
|
||||
const saved = await this._mediaService.saveFile(
|
||||
organization.id,
|
||||
item.name || file.split('/').pop(),
|
||||
file
|
||||
);
|
||||
results.push(saved);
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
@Post('/:identifier')
|
||||
async addApiKey(
|
||||
@GetOrgFromRequest() organization: Organization,
|
||||
@Param('identifier') identifier: string,
|
||||
@Body('api') api: string
|
||||
) {
|
||||
const thirdParty = this._thirdPartyManager.getThirdPartyByName(identifier);
|
||||
if (!thirdParty) {
|
||||
throw new HttpException('Invalid identifier', 400);
|
||||
}
|
||||
|
||||
const connect = await thirdParty.instance.checkConnection(api);
|
||||
if (!connect) {
|
||||
throw new HttpException('Invalid API key', 400);
|
||||
}
|
||||
|
||||
try {
|
||||
const save = await this._thirdPartyManager.saveIntegration(
|
||||
organization.id,
|
||||
identifier,
|
||||
api,
|
||||
{
|
||||
name: connect.name,
|
||||
username: connect.username,
|
||||
id: connect.id,
|
||||
}
|
||||
);
|
||||
|
||||
return {
|
||||
id: save.id,
|
||||
};
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
throw new HttpException('Integration Already Exists', 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
HttpException,
|
||||
Post,
|
||||
Query,
|
||||
Req,
|
||||
Res,
|
||||
} from '@nestjs/common';
|
||||
import { GetUserFromRequest } from '@gitroom/nestjs-libraries/user/user.from.request';
|
||||
import { sign } from 'jsonwebtoken';
|
||||
import { Organization, User } from '@prisma/client';
|
||||
import { SubscriptionService } from '@gitroom/nestjs-libraries/database/prisma/subscriptions/subscription.service';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { StripeService } from '@gitroom/nestjs-libraries/services/stripe.service';
|
||||
import { Response, Request } from 'express';
|
||||
import { AuthService } from '@gitroom/backend/services/auth/auth.service';
|
||||
import { OrganizationService } from '@gitroom/nestjs-libraries/database/prisma/organizations/organization.service';
|
||||
import { CheckPolicies } from '@gitroom/backend/services/auth/permissions/permissions.ability';
|
||||
import { getCookieUrlFromDomain } from '@gitroom/helpers/subdomain/subdomain.management';
|
||||
import { pricing } from '@gitroom/nestjs-libraries/database/prisma/subscriptions/pricing';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { UsersService } from '@gitroom/nestjs-libraries/database/prisma/users/users.service';
|
||||
import { UserDetailDto } from '@gitroom/nestjs-libraries/dtos/users/user.details.dto';
|
||||
import { EmailNotificationsDto } from '@gitroom/nestjs-libraries/dtos/users/email-notifications.dto';
|
||||
import { HttpForbiddenException } from '@gitroom/nestjs-libraries/services/exception.filter';
|
||||
import { RealIP } from 'nestjs-real-ip';
|
||||
import { UserAgent } from '@gitroom/nestjs-libraries/user/user.agent';
|
||||
import { TrackEnum } from '@gitroom/nestjs-libraries/user/track.enum';
|
||||
import { TrackService } from '@gitroom/nestjs-libraries/track/track.service';
|
||||
import { makeId } from '@gitroom/nestjs-libraries/services/make.is';
|
||||
import { AuthorizationActions, Sections } from '@gitroom/backend/services/auth/permissions/permission.exception.class';
|
||||
|
||||
@ApiTags('User')
|
||||
@Controller('/user')
|
||||
export class UsersController {
|
||||
constructor(
|
||||
private _subscriptionService: SubscriptionService,
|
||||
private _stripeService: StripeService,
|
||||
private _authService: AuthService,
|
||||
private _orgService: OrganizationService,
|
||||
private _userService: UsersService,
|
||||
private _trackService: TrackService
|
||||
) {}
|
||||
@Get('/agent-media-sso')
|
||||
async getAgentMediaSsoUrl(
|
||||
@GetUserFromRequest() user: User,
|
||||
@GetOrgFromRequest() organization: Organization
|
||||
) {
|
||||
if (!process.env.AGENT_MEDIA_SSO_KEY) {
|
||||
throw new HttpException('Agent Media SSO is not configured', 400);
|
||||
}
|
||||
|
||||
const token = sign(
|
||||
{ id: organization.id, displayName: organization.name },
|
||||
process.env.AGENT_MEDIA_SSO_KEY
|
||||
);
|
||||
|
||||
return { url: `https://agent-media.ai/sso/${token}` };
|
||||
}
|
||||
|
||||
@Get('/self')
|
||||
async getSelf(
|
||||
@GetUserFromRequest() user: User,
|
||||
@GetOrgFromRequest() organization: Organization,
|
||||
@Req() req: Request
|
||||
) {
|
||||
if (!organization) {
|
||||
throw new HttpForbiddenException();
|
||||
}
|
||||
|
||||
const impersonate = req.cookies.impersonate || req.headers.impersonate;
|
||||
// @ts-ignore
|
||||
return {
|
||||
...user,
|
||||
orgId: organization.id,
|
||||
// @ts-ignore
|
||||
totalChannels: !process.env.STRIPE_PUBLISHABLE_KEY ? 10000 : organization?.subscription?.totalChannels || pricing.FREE.channel,
|
||||
// @ts-ignore
|
||||
tier: organization?.subscription?.subscriptionTier || (!process.env.STRIPE_PUBLISHABLE_KEY ? 'ULTIMATE' : 'FREE'),
|
||||
// @ts-ignore
|
||||
role: organization?.users[0]?.role,
|
||||
// @ts-ignore
|
||||
isLifetime: !!organization?.subscription?.isLifetime,
|
||||
admin: !!user.isSuperAdmin,
|
||||
impersonate: !!impersonate,
|
||||
isTrailing: !process.env.STRIPE_PUBLISHABLE_KEY ? false : organization?.isTrailing,
|
||||
allowTrial: organization?.allowTrial,
|
||||
streakSince: organization?.streakSince || null,
|
||||
// @ts-ignore
|
||||
publicApi: organization?.users[0]?.role === 'SUPERADMIN' || organization?.users[0]?.role === 'ADMIN' ? organization?.apiKey : '',
|
||||
};
|
||||
}
|
||||
|
||||
@Get('/personal')
|
||||
async getPersonalInformation(@GetUserFromRequest() user: User) {
|
||||
return this._userService.getPersonal(user.id);
|
||||
}
|
||||
|
||||
@Get('/impersonate')
|
||||
async getImpersonate(
|
||||
@GetUserFromRequest() user: User,
|
||||
@Query('name') name: string
|
||||
) {
|
||||
if (!user.isSuperAdmin) {
|
||||
throw new HttpException('Unauthorized', 400);
|
||||
}
|
||||
|
||||
return this._userService.getImpersonateUser(name);
|
||||
}
|
||||
|
||||
@Post('/impersonate')
|
||||
async setImpersonate(
|
||||
@GetUserFromRequest() user: User,
|
||||
@Body('id') id: string,
|
||||
@Res({ passthrough: true }) response: Response
|
||||
) {
|
||||
if (!user.isSuperAdmin) {
|
||||
throw new HttpException('Unauthorized', 400);
|
||||
}
|
||||
|
||||
response.cookie('impersonate', id, {
|
||||
domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),
|
||||
...(!process.env.NOT_SECURED
|
||||
? {
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
}
|
||||
: {}),
|
||||
expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),
|
||||
});
|
||||
|
||||
if (process.env.NOT_SECURED) {
|
||||
response.header('impersonate', id);
|
||||
}
|
||||
}
|
||||
|
||||
@Post('/personal')
|
||||
async changePersonal(
|
||||
@GetUserFromRequest() user: User,
|
||||
@Body() body: UserDetailDto
|
||||
) {
|
||||
return this._userService.changePersonal(user.id, body);
|
||||
}
|
||||
|
||||
@Get('/email-notifications')
|
||||
async getEmailNotifications(@GetUserFromRequest() user: User) {
|
||||
return this._userService.getEmailNotifications(user.id);
|
||||
}
|
||||
|
||||
@Post('/email-notifications')
|
||||
async updateEmailNotifications(
|
||||
@GetUserFromRequest() user: User,
|
||||
@Body() body: EmailNotificationsDto
|
||||
) {
|
||||
return this._userService.updateEmailNotifications(user.id, body);
|
||||
}
|
||||
|
||||
@Post('/api-key/rotate')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
|
||||
async rotateApiKey(@GetOrgFromRequest() organization: Organization) {
|
||||
return this._orgService.updateApiKey(organization.id);
|
||||
}
|
||||
|
||||
@Get('/subscription')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
|
||||
async getSubscription(@GetOrgFromRequest() organization: Organization) {
|
||||
const subscription =
|
||||
await this._subscriptionService.getSubscriptionByOrganizationId(
|
||||
organization.id
|
||||
);
|
||||
|
||||
return subscription ? { subscription } : { subscription: undefined };
|
||||
}
|
||||
|
||||
@Get('/subscription/tiers')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
|
||||
async tiers() {
|
||||
return this._stripeService.getPackages();
|
||||
}
|
||||
|
||||
@Post('/join-org')
|
||||
async joinOrg(
|
||||
@GetUserFromRequest() user: User,
|
||||
@Body('org') org: string,
|
||||
@Res({ passthrough: true }) response: Response
|
||||
) {
|
||||
const getOrgFromCookie = this._authService.getOrgFromCookie(org);
|
||||
|
||||
if (!getOrgFromCookie) {
|
||||
return response.status(200).json({ id: null });
|
||||
}
|
||||
|
||||
const addedOrg = await this._orgService.addUserToOrg(
|
||||
user.id,
|
||||
getOrgFromCookie.id,
|
||||
getOrgFromCookie.orgId,
|
||||
getOrgFromCookie.role
|
||||
);
|
||||
|
||||
response.status(200).json({
|
||||
id: typeof addedOrg !== 'boolean' ? addedOrg.organizationId : null,
|
||||
});
|
||||
}
|
||||
|
||||
@Get('/organizations')
|
||||
async getOrgs(@GetUserFromRequest() user: User) {
|
||||
return (await this._orgService.getOrgsByUserId(user.id)).filter(
|
||||
(f) => !f.users[0].disabled
|
||||
);
|
||||
}
|
||||
|
||||
@Post('/change-org')
|
||||
changeOrg(
|
||||
@Body('id') id: string,
|
||||
@Res({ passthrough: true }) response: Response
|
||||
) {
|
||||
response.cookie('showorg', id, {
|
||||
domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),
|
||||
...(!process.env.NOT_SECURED
|
||||
? {
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
}
|
||||
: {}),
|
||||
expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),
|
||||
});
|
||||
|
||||
if (process.env.NOT_SECURED) {
|
||||
response.header('showorg', id);
|
||||
}
|
||||
|
||||
response.status(200).send();
|
||||
}
|
||||
|
||||
@Post('/logout')
|
||||
logout(@Res({ passthrough: true }) response: Response) {
|
||||
response.header('logout', 'true');
|
||||
response.cookie('auth', '', {
|
||||
domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),
|
||||
...(!process.env.NOT_SECURED
|
||||
? {
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
}
|
||||
: {}),
|
||||
maxAge: -1,
|
||||
expires: new Date(0),
|
||||
});
|
||||
|
||||
response.cookie('showorg', '', {
|
||||
domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),
|
||||
...(!process.env.NOT_SECURED
|
||||
? {
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
}
|
||||
: {}),
|
||||
maxAge: -1,
|
||||
expires: new Date(0),
|
||||
});
|
||||
|
||||
response.cookie('impersonate', '', {
|
||||
domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),
|
||||
...(!process.env.NOT_SECURED
|
||||
? {
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
}
|
||||
: {}),
|
||||
maxAge: -1,
|
||||
expires: new Date(0),
|
||||
});
|
||||
|
||||
response.status(200).send();
|
||||
}
|
||||
|
||||
@Post('/t')
|
||||
async trackEvent(
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
@Req() req: Request,
|
||||
@GetUserFromRequest() user: User,
|
||||
@RealIP() ip: string,
|
||||
@UserAgent() userAgent: string,
|
||||
@Body()
|
||||
body: { tt: TrackEnum; fbclid: string; additional: Record<string, any> }
|
||||
) {
|
||||
const uniqueId = req?.cookies?.track || makeId(10);
|
||||
const fbclid = req?.cookies?.fbclid || body.fbclid;
|
||||
await this._trackService.track(
|
||||
uniqueId,
|
||||
ip,
|
||||
userAgent,
|
||||
body.tt,
|
||||
body.additional,
|
||||
fbclid,
|
||||
user
|
||||
);
|
||||
if (!req.cookies.track) {
|
||||
res.cookie('track', uniqueId, {
|
||||
domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),
|
||||
...(!process.env.NOT_SECURED
|
||||
? {
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
}
|
||||
: {}),
|
||||
expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),
|
||||
});
|
||||
}
|
||||
|
||||
res.status(200).json({
|
||||
track: uniqueId,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
Post,
|
||||
Put,
|
||||
Query,
|
||||
} from '@nestjs/common';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { Organization } from '@prisma/client';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { WebhooksService } from '@gitroom/nestjs-libraries/database/prisma/webhooks/webhooks.service';
|
||||
import { CheckPolicies } from '@gitroom/backend/services/auth/permissions/permissions.ability';
|
||||
import {
|
||||
OnlyURL, UpdateDto, WebhooksDto
|
||||
} from '@gitroom/nestjs-libraries/dtos/webhooks/webhooks.dto';
|
||||
import { AuthorizationActions, Sections } from '@gitroom/backend/services/auth/permissions/permission.exception.class';
|
||||
|
||||
@ApiTags('Webhooks')
|
||||
@Controller('/webhooks')
|
||||
export class WebhookController {
|
||||
constructor(private _webhooksService: WebhooksService) {}
|
||||
|
||||
@Get('/')
|
||||
async getStatistics(@GetOrgFromRequest() org: Organization) {
|
||||
return this._webhooksService.getWebhooks(org.id);
|
||||
}
|
||||
|
||||
@Post('/')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.WEBHOOKS])
|
||||
async createAWebhook(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: WebhooksDto
|
||||
) {
|
||||
return this._webhooksService.createWebhook(org.id, body);
|
||||
}
|
||||
|
||||
@Put('/')
|
||||
async updateWebhook(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: UpdateDto
|
||||
) {
|
||||
return this._webhooksService.createWebhook(org.id, body);
|
||||
}
|
||||
|
||||
@Delete('/:id')
|
||||
async deleteWebhook(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
return this._webhooksService.deleteWebhook(org.id, id);
|
||||
}
|
||||
|
||||
@Post('/send')
|
||||
async sendWebhook(@Body() body: any, @Query() query: OnlyURL) {
|
||||
try {
|
||||
await fetch(query.url, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
} catch (err) {
|
||||
/** sent **/
|
||||
}
|
||||
|
||||
return { send: true };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { DatabaseModule } from '@gitroom/nestjs-libraries/database/prisma/database.module';
|
||||
import { ApiModule } from '@gitroom/backend/api/api.module';
|
||||
import { APP_GUARD } from '@nestjs/core';
|
||||
import { PoliciesGuard } from '@gitroom/backend/services/auth/permissions/permissions.guard';
|
||||
import { PublicApiModule } from '@gitroom/backend/public-api/public.api.module';
|
||||
import { ThrottlerBehindProxyGuard } from '@gitroom/nestjs-libraries/throttler/throttler.provider';
|
||||
import { ThrottlerModule } from '@nestjs/throttler';
|
||||
import { AgentModule } from '@gitroom/nestjs-libraries/agent/agent.module';
|
||||
import { ThirdPartyModule } from '@gitroom/nestjs-libraries/3rdparties/thirdparty.module';
|
||||
import { VideoModule } from '@gitroom/nestjs-libraries/videos/video.module';
|
||||
import { SentryModule } from '@sentry/nestjs/setup';
|
||||
import { FILTER } from '@gitroom/nestjs-libraries/sentry/sentry.exception';
|
||||
import { ChatModule } from '@gitroom/nestjs-libraries/chat/chat.module';
|
||||
import { getTemporalModule } from '@gitroom/nestjs-libraries/temporal/temporal.module';
|
||||
import { TemporalRegisterMissingSearchAttributesModule } from '@gitroom/nestjs-libraries/temporal/temporal.register';
|
||||
import { InfiniteWorkflowRegisterModule } from '@gitroom/nestjs-libraries/temporal/infinite.workflow.register';
|
||||
import { ThrottlerStorageRedisService } from '@nest-lab/throttler-storage-redis';
|
||||
import { ioRedis } from '@gitroom/nestjs-libraries/redis/redis.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
imports: [
|
||||
SentryModule.forRoot(),
|
||||
DatabaseModule,
|
||||
ApiModule,
|
||||
PublicApiModule,
|
||||
AgentModule,
|
||||
ThirdPartyModule,
|
||||
VideoModule,
|
||||
ChatModule,
|
||||
getTemporalModule(false),
|
||||
TemporalRegisterMissingSearchAttributesModule,
|
||||
InfiniteWorkflowRegisterModule,
|
||||
ThrottlerModule.forRoot({
|
||||
throttlers: [
|
||||
{
|
||||
ttl: 3600000,
|
||||
limit: process.env.API_LIMIT ? Number(process.env.API_LIMIT) : 90,
|
||||
},
|
||||
],
|
||||
storage: new ThrottlerStorageRedisService(ioRedis),
|
||||
}),
|
||||
],
|
||||
controllers: [],
|
||||
providers: [
|
||||
FILTER,
|
||||
{
|
||||
provide: APP_GUARD,
|
||||
useClass: ThrottlerBehindProxyGuard,
|
||||
},
|
||||
{
|
||||
provide: APP_GUARD,
|
||||
useClass: PoliciesGuard,
|
||||
},
|
||||
],
|
||||
exports: [
|
||||
DatabaseModule,
|
||||
ApiModule,
|
||||
PublicApiModule,
|
||||
AgentModule,
|
||||
ThrottlerModule,
|
||||
ChatModule,
|
||||
],
|
||||
})
|
||||
export class AppModule {}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { initializeSentry } from '@gitroom/nestjs-libraries/sentry/initialize.sentry';
|
||||
initializeSentry('backend', true);
|
||||
import compression from 'compression';
|
||||
|
||||
import { loadSwagger } from '@gitroom/helpers/swagger/load.swagger';
|
||||
import { json } from 'express';
|
||||
import { Runtime } from '@temporalio/worker';
|
||||
Runtime.install({ shutdownSignals: [] });
|
||||
|
||||
process.env.TZ = 'UTC';
|
||||
|
||||
import cookieParser from 'cookie-parser';
|
||||
import { Logger, ValidationPipe } from '@nestjs/common';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { AppModule } from './app.module';
|
||||
|
||||
import { SubscriptionExceptionFilter } from '@gitroom/backend/services/auth/permissions/subscription.exception';
|
||||
import { PostValidationExceptionFilter } from '@gitroom/backend/api/routes/posts.validation.exception';
|
||||
import { HttpExceptionFilter } from '@gitroom/nestjs-libraries/services/exception.filter';
|
||||
import { ConfigurationChecker } from '@gitroom/helpers/configuration/configuration.checker';
|
||||
import { startMcp } from '@gitroom/nestjs-libraries/chat/start.mcp';
|
||||
|
||||
async function start() {
|
||||
const app = await NestFactory.create(AppModule, {
|
||||
rawBody: true,
|
||||
cors: {
|
||||
...(!process.env.NOT_SECURED ? { credentials: true } : {}),
|
||||
allowedHeaders: [
|
||||
'Content-Type',
|
||||
'Authorization',
|
||||
'auth',
|
||||
'showorg',
|
||||
'impersonate',
|
||||
'x-copilotkit-runtime-client-gql-version',
|
||||
],
|
||||
exposedHeaders: [
|
||||
'reload',
|
||||
'onboarding',
|
||||
'activate',
|
||||
'x-copilotkit-runtime-client-gql-version',
|
||||
...(process.env.NOT_SECURED ? ['auth', 'showorg', 'impersonate'] : []),
|
||||
],
|
||||
origin: [
|
||||
process.env.FRONTEND_URL,
|
||||
'http://localhost:6274',
|
||||
...(process.env.MAIN_URL ? [process.env.MAIN_URL] : []),
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
await startMcp(app);
|
||||
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
transform: true,
|
||||
})
|
||||
);
|
||||
|
||||
app.use(['/copilot/{*splat}', '/posts'], (req: any, res: any, next: any) => {
|
||||
json({ limit: '50mb' })(req, res, next);
|
||||
});
|
||||
|
||||
app.use(cookieParser());
|
||||
app.use(compression());
|
||||
app.useGlobalFilters(new SubscriptionExceptionFilter());
|
||||
app.useGlobalFilters(new PostValidationExceptionFilter());
|
||||
app.useGlobalFilters(new HttpExceptionFilter());
|
||||
|
||||
loadSwagger(app);
|
||||
|
||||
const port = process.env.PORT || 3000;
|
||||
|
||||
try {
|
||||
await app.listen(port);
|
||||
console.log('Backend started successfully on port ' + port);
|
||||
|
||||
checkConfiguration(); // Do this last, so that users will see obvious issues at the end of the startup log without having to scroll up.
|
||||
|
||||
Logger.log(`🚀 Backend is running on: http://localhost:${port}`);
|
||||
} catch (e) {
|
||||
Logger.error(`Backend failed to start on port ${port}`, e);
|
||||
}
|
||||
}
|
||||
|
||||
function checkConfiguration() {
|
||||
const checker = new ConfigurationChecker();
|
||||
checker.readEnvFromProcess();
|
||||
checker.check();
|
||||
|
||||
if (checker.hasIssues()) {
|
||||
for (const issue of checker.getIssues()) {
|
||||
Logger.warn(issue, 'Configuration issue');
|
||||
}
|
||||
|
||||
Logger.warn('Configuration issues found: ' + checker.getIssuesCount());
|
||||
} else {
|
||||
Logger.log('Configuration check completed without any issues');
|
||||
}
|
||||
}
|
||||
|
||||
start();
|
||||
@@ -0,0 +1,37 @@
|
||||
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
|
||||
import { AuthService } from '@gitroom/backend/services/auth/auth.service';
|
||||
import { StripeService } from '@gitroom/nestjs-libraries/services/stripe.service';
|
||||
import { PoliciesGuard } from '@gitroom/backend/services/auth/permissions/permissions.guard';
|
||||
import { PermissionsService } from '@gitroom/backend/services/auth/permissions/permissions.service';
|
||||
import { IntegrationManager } from '@gitroom/nestjs-libraries/integrations/integration.manager';
|
||||
import { UploadModule } from '@gitroom/nestjs-libraries/upload/upload.module';
|
||||
import { OpenaiService } from '@gitroom/nestjs-libraries/openai/openai.service';
|
||||
import { ExtractContentService } from '@gitroom/nestjs-libraries/openai/extract.content.service';
|
||||
import { CodesService } from '@gitroom/nestjs-libraries/services/codes.service';
|
||||
import { PublicIntegrationsController } from '@gitroom/backend/public-api/routes/v1/public.integrations.controller';
|
||||
import { PublicAuthMiddleware } from '@gitroom/backend/services/auth/public.auth.middleware';
|
||||
|
||||
const authenticatedController = [PublicIntegrationsController];
|
||||
@Module({
|
||||
imports: [UploadModule],
|
||||
controllers: [...authenticatedController],
|
||||
providers: [
|
||||
AuthService,
|
||||
StripeService,
|
||||
OpenaiService,
|
||||
ExtractContentService,
|
||||
PoliciesGuard,
|
||||
PermissionsService,
|
||||
CodesService,
|
||||
IntegrationManager,
|
||||
],
|
||||
get exports() {
|
||||
return [...this.imports, ...this.providers];
|
||||
},
|
||||
})
|
||||
export class PublicApiModule implements NestModule {
|
||||
configure(consumer: MiddlewareConsumer) {
|
||||
consumer.apply(PublicAuthMiddleware).forRoutes(...authenticatedController);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,571 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
HttpException,
|
||||
Param,
|
||||
Post,
|
||||
Put,
|
||||
Query,
|
||||
UploadedFile,
|
||||
UseInterceptors,
|
||||
UsePipes,
|
||||
} from '@nestjs/common';
|
||||
import { CustomFileValidationPipe } from '@gitroom/nestjs-libraries/upload/custom.upload.validation';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { Organization } from '@prisma/client';
|
||||
import { IntegrationService } from '@gitroom/nestjs-libraries/database/prisma/integrations/integration.service';
|
||||
import { CheckPolicies } from '@gitroom/backend/services/auth/permissions/permissions.ability';
|
||||
import { PostsService } from '@gitroom/nestjs-libraries/database/prisma/posts/posts.service';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import { UploadFactory } from '@gitroom/nestjs-libraries/upload/upload.factory';
|
||||
import { MediaService } from '@gitroom/nestjs-libraries/database/prisma/media/media.service';
|
||||
import { GetPostsDto } from '@gitroom/nestjs-libraries/dtos/posts/get.posts.dto';
|
||||
import { ChangePostStatusDto } from '@gitroom/nestjs-libraries/dtos/posts/change.post.status.dto';
|
||||
import {
|
||||
AuthorizationActions,
|
||||
Sections,
|
||||
} from '@gitroom/backend/services/auth/permissions/permission.exception.class';
|
||||
import { VideoDto } from '@gitroom/nestjs-libraries/dtos/videos/video.dto';
|
||||
import { VideoFunctionDto } from '@gitroom/nestjs-libraries/dtos/videos/video.function.dto';
|
||||
import { UploadDto } from '@gitroom/nestjs-libraries/dtos/media/upload.dto';
|
||||
import { NotificationService } from '@gitroom/nestjs-libraries/database/prisma/notifications/notification.service';
|
||||
import { GetNotificationsDto } from '@gitroom/nestjs-libraries/dtos/notifications/get.notifications.dto';
|
||||
import { Readable } from 'stream';
|
||||
import { ssrfSafeDispatcher } from '@gitroom/nestjs-libraries/dtos/webhooks/ssrf.safe.dispatcher';
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
const { fromBuffer } = require('file-type');
|
||||
|
||||
const PUBLIC_API_ALLOWED_MIME = new Set<string>([
|
||||
'image/jpeg',
|
||||
'image/png',
|
||||
'image/gif',
|
||||
'image/webp',
|
||||
'image/avif',
|
||||
'image/bmp',
|
||||
'image/tiff',
|
||||
'video/mp4',
|
||||
]);
|
||||
import * as Sentry from '@sentry/nestjs';
|
||||
import {
|
||||
socialIntegrationList,
|
||||
IntegrationManager,
|
||||
} from '@gitroom/nestjs-libraries/integrations/integration.manager';
|
||||
import { getValidationSchemas } from '@gitroom/nestjs-libraries/chat/validation.schemas.helper';
|
||||
import { RefreshIntegrationService } from '@gitroom/nestjs-libraries/integrations/refresh.integration.service';
|
||||
import { RefreshToken } from '@gitroom/nestjs-libraries/integrations/social.abstract';
|
||||
import { PostValidationException } from '@gitroom/backend/api/routes/posts.validation.exception';
|
||||
import { timer } from '@gitroom/helpers/utils/timer';
|
||||
import { ioRedis } from '@gitroom/nestjs-libraries/redis/redis.service';
|
||||
|
||||
@ApiTags('Public API')
|
||||
@Controller('/public/v1')
|
||||
export class PublicIntegrationsController {
|
||||
private storage = UploadFactory.createStorage();
|
||||
|
||||
constructor(
|
||||
private _integrationService: IntegrationService,
|
||||
private _postsService: PostsService,
|
||||
private _mediaService: MediaService,
|
||||
private _notificationService: NotificationService,
|
||||
private _integrationManager: IntegrationManager,
|
||||
private _refreshIntegrationService: RefreshIntegrationService
|
||||
) {}
|
||||
|
||||
@Post('/upload')
|
||||
@UseInterceptors(FileInterceptor('file'))
|
||||
@UsePipes(new CustomFileValidationPipe())
|
||||
async uploadSimple(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@UploadedFile('file') file: Express.Multer.File
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
if (!file) {
|
||||
throw new HttpException({ msg: 'No file provided' }, 400);
|
||||
}
|
||||
|
||||
const getFile = await this.storage.uploadFile(file);
|
||||
return this._mediaService.saveFile(
|
||||
org.id,
|
||||
getFile.originalname,
|
||||
getFile.path
|
||||
);
|
||||
}
|
||||
|
||||
@Post('/upload-from-url')
|
||||
async uploadsFromUrl(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: UploadDto
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
const response = await fetch(body.url, {
|
||||
// @ts-ignore — undici option, not in lib.dom fetch types
|
||||
dispatcher: ssrfSafeDispatcher,
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new HttpException({ msg: 'Failed to fetch URL' }, 400);
|
||||
}
|
||||
const buffer = Buffer.from(await response.arrayBuffer());
|
||||
const detected = await fromBuffer(buffer);
|
||||
if (!detected || !PUBLIC_API_ALLOWED_MIME.has(detected.mime)) {
|
||||
throw new HttpException({ msg: 'Unsupported file type.' }, 400);
|
||||
}
|
||||
const mimetype = detected.mime;
|
||||
const ext = detected.ext;
|
||||
|
||||
const getFile = await this.storage.uploadFile({
|
||||
buffer,
|
||||
mimetype,
|
||||
size: buffer.length,
|
||||
path: '',
|
||||
fieldname: '',
|
||||
destination: '',
|
||||
stream: new Readable(),
|
||||
filename: '',
|
||||
originalname: `upload.${ext}`,
|
||||
encoding: '',
|
||||
});
|
||||
|
||||
return this._mediaService.saveFile(
|
||||
org.id,
|
||||
getFile.originalname,
|
||||
getFile.path
|
||||
);
|
||||
}
|
||||
|
||||
@Get('/find-slot/:id')
|
||||
async findSlotIntegration(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id?: string
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
return { date: await this._postsService.findFreeDateTime(org.id, id) };
|
||||
}
|
||||
|
||||
@Get('/posts')
|
||||
async getPosts(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Query() query: GetPostsDto
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
const posts = await this._postsService.getPosts(org.id, query);
|
||||
return {
|
||||
posts,
|
||||
// comments,
|
||||
};
|
||||
}
|
||||
|
||||
@Post('/posts')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.POSTS_PER_MONTH])
|
||||
async createPost(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() rawBody: any
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
const body = await this._postsService.mapTypeToPost(
|
||||
rawBody,
|
||||
org.id,
|
||||
rawBody?.type === 'draft' || true
|
||||
);
|
||||
body.type = rawBody.type;
|
||||
|
||||
if (
|
||||
process.env.RESTRICT_UPLOAD_DOMAINS &&
|
||||
body.posts.some((p) =>
|
||||
p.value.some((a) =>
|
||||
a.image.some(
|
||||
(i) => i.path.indexOf(process.env.RESTRICT_UPLOAD_DOMAINS) === -1
|
||||
)
|
||||
)
|
||||
)
|
||||
) {
|
||||
throw new HttpException(
|
||||
{
|
||||
msg: `All media must be uploaded through our upload API route and contain the domain: ${process.env.RESTRICT_UPLOAD_DOMAINS}`,
|
||||
},
|
||||
400
|
||||
);
|
||||
}
|
||||
|
||||
// Server-side validation — same rules as the dashboard, surfaced as a
|
||||
// readable 400 (see PostValidationExceptionFilter).
|
||||
const validation = await this._postsService.validatePosts(
|
||||
org.id,
|
||||
body.posts
|
||||
);
|
||||
|
||||
const fail = (item: (typeof validation)[number], error: string) => {
|
||||
throw new PostValidationException({
|
||||
provider: item.identifier,
|
||||
name: item.name,
|
||||
error,
|
||||
});
|
||||
};
|
||||
|
||||
for (const item of validation) {
|
||||
if (item.emptyContent) {
|
||||
fail(
|
||||
item,
|
||||
'Your post should have at least one character or one image.'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (body.type !== 'draft') {
|
||||
for (const item of validation) {
|
||||
if (!item.valid) {
|
||||
fail(item, item.settingsError || 'Please fix your settings');
|
||||
}
|
||||
if (item.errors !== true) {
|
||||
fail(item, item.errors as string);
|
||||
}
|
||||
if (item.tooLong) {
|
||||
fail(item, 'post is too long, please fix it');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const allowedCreationMethods = ['CLI', 'API'] as const;
|
||||
const creationMethod = allowedCreationMethods.includes(
|
||||
rawBody.creationMethod
|
||||
)
|
||||
? (rawBody.creationMethod as 'CLI' | 'API')
|
||||
: 'API';
|
||||
|
||||
return this._postsService.createPost(org.id, body, creationMethod);
|
||||
}
|
||||
|
||||
@Delete('/posts/:id')
|
||||
async deletePost(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
const getPostById = await this._postsService.getPost(org.id, id);
|
||||
return this._postsService.deletePost(org.id, getPostById.group);
|
||||
}
|
||||
|
||||
@Delete('/posts/group/:group')
|
||||
deletePostByGroup(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('group') group: string
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
return this._postsService.deletePost(org.id, group);
|
||||
}
|
||||
|
||||
@Get('/is-connected')
|
||||
async getActiveIntegrations(@GetOrgFromRequest() org: Organization) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
return { connected: true };
|
||||
}
|
||||
|
||||
@Get('/groups')
|
||||
async listGroups(@GetOrgFromRequest() org: Organization) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
return (await this._integrationService.customers(org.id)).map(
|
||||
(customer) => ({
|
||||
id: customer.id,
|
||||
name: customer.name,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@Get('/integrations')
|
||||
async listIntegration(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Query('group') group?: string
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
return (await this._integrationService.getIntegrationsList(org.id))
|
||||
.filter((integration) => !group || integration.customer?.id === group)
|
||||
.map((integration) => ({
|
||||
id: integration.id,
|
||||
name: integration.name,
|
||||
identifier: integration.providerIdentifier,
|
||||
picture: integration.picture,
|
||||
disabled: integration.disabled,
|
||||
profile: integration.profile,
|
||||
customer: integration.customer
|
||||
? {
|
||||
id: integration.customer.id,
|
||||
name: integration.customer.name,
|
||||
}
|
||||
: undefined,
|
||||
}));
|
||||
}
|
||||
|
||||
@Get('/social/:integration')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.CHANNEL])
|
||||
async getIntegrationUrl(
|
||||
@Param('integration') integration: string,
|
||||
@Query('refresh') refresh: string,
|
||||
@GetOrgFromRequest() org: Organization
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
if (
|
||||
!this._integrationManager
|
||||
.getAllowedSocialsIntegrations()
|
||||
.includes(integration)
|
||||
) {
|
||||
throw new HttpException({ msg: 'Integration not allowed' }, 400);
|
||||
}
|
||||
|
||||
const integrationProvider =
|
||||
this._integrationManager.getSocialIntegration(integration);
|
||||
|
||||
if (integrationProvider.externalUrl) {
|
||||
throw new HttpException(
|
||||
{
|
||||
msg: 'This integration requires an external URL and is not supported via the public API',
|
||||
},
|
||||
400
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const { codeVerifier, state, url } =
|
||||
await integrationProvider.generateAuthUrl();
|
||||
|
||||
if (refresh) {
|
||||
await ioRedis.set(`refresh:${state}`, refresh, 'EX', 3600);
|
||||
}
|
||||
|
||||
await ioRedis.set(`organization:${state}`, org.id, 'EX', 3600);
|
||||
await ioRedis.set(`login:${state}`, codeVerifier, 'EX', 3600);
|
||||
|
||||
return { url };
|
||||
} catch (err) {
|
||||
throw new HttpException({ msg: 'Failed to generate auth URL' }, 500);
|
||||
}
|
||||
}
|
||||
|
||||
@Get('/notifications')
|
||||
async getNotifications(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Query() query: GetNotificationsDto
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
return this._notificationService.getNotificationsPaginated(
|
||||
org.id,
|
||||
query.page ?? 0
|
||||
);
|
||||
}
|
||||
|
||||
@Post('/generate-video')
|
||||
generateVideo(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: VideoDto
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
return this._mediaService.generateVideo(org, body);
|
||||
}
|
||||
|
||||
@Post('/video/function')
|
||||
videoFunction(@Body() body: VideoFunctionDto) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
return this._mediaService.videoFunction(
|
||||
body.identifier,
|
||||
body.functionName,
|
||||
body.params
|
||||
);
|
||||
}
|
||||
|
||||
@Delete('/integrations/:id')
|
||||
async deleteChannel(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
const isTherePosts = await this._integrationService.getPostsForChannel(
|
||||
org.id,
|
||||
id
|
||||
);
|
||||
if (isTherePosts.length) {
|
||||
for (const post of isTherePosts) {
|
||||
this._postsService.deletePost(org.id, post.group).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
return this._integrationService.deleteChannel(org.id, id);
|
||||
}
|
||||
|
||||
@Get('/integration-settings/:id')
|
||||
async getIntegrationSettings(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
const loadIntegration = await this._integrationService.getIntegrationById(
|
||||
org.id,
|
||||
id
|
||||
);
|
||||
|
||||
if (!loadIntegration) {
|
||||
throw new HttpException({ msg: 'Integration not found' }, 404);
|
||||
}
|
||||
|
||||
const verified =
|
||||
JSON.parse(loadIntegration.additionalSettings || '[]')?.find(
|
||||
(p: any) => p?.title === 'Verified'
|
||||
)?.value || false;
|
||||
|
||||
const integration = socialIntegrationList.find(
|
||||
(p) => p.identifier === loadIntegration.providerIdentifier
|
||||
)!;
|
||||
|
||||
if (!integration) {
|
||||
return {
|
||||
output: { rules: '', maxLength: 0, settings: {}, tools: [] as any[] },
|
||||
};
|
||||
}
|
||||
|
||||
const maxLength = integration.maxLength(verified);
|
||||
const schemas = !integration.dto
|
||||
? false
|
||||
: getValidationSchemas()[integration.dto.name];
|
||||
const tools = this._integrationManager.getAllTools();
|
||||
const rules = this._integrationManager.getAllRulesDescription();
|
||||
|
||||
return {
|
||||
output: {
|
||||
rules: rules[integration.identifier],
|
||||
maxLength,
|
||||
settings: !schemas ? 'No additional settings required' : schemas,
|
||||
tools: tools[integration.identifier],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@Get('/posts/:id/missing')
|
||||
async getMissingContent(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
return this._postsService.getMissingContent(org.id, id);
|
||||
}
|
||||
|
||||
@Put('/posts/:id/status')
|
||||
async changePostStatus(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string,
|
||||
@Body() body: ChangePostStatusDto
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
return this._postsService.changePostStatus(org.id, id, body.status);
|
||||
}
|
||||
|
||||
@Put('/posts/:id/release-id')
|
||||
async updateReleaseId(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string,
|
||||
@Body('releaseId') releaseId: string
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
return this._postsService.updateReleaseId(org.id, id, releaseId);
|
||||
}
|
||||
|
||||
@Get('/analytics/:integration')
|
||||
async getAnalytics(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('integration') integration: string,
|
||||
@Query('date') date: string
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
return this._integrationService.checkAnalytics(org, integration, date);
|
||||
}
|
||||
|
||||
@Get('/analytics/post/:postId')
|
||||
async getPostAnalytics(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('postId') postId: string,
|
||||
@Query('date') date: string
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
return this._postsService.checkPostAnalytics(org.id, postId, +date);
|
||||
}
|
||||
|
||||
@Post('/integration-trigger/:id')
|
||||
async triggerIntegrationTool(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string,
|
||||
@Body() body: { methodName: string; data: Record<string, string> }
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
const getIntegration = await this._integrationService.getIntegrationById(
|
||||
org.id,
|
||||
id
|
||||
);
|
||||
|
||||
if (!getIntegration) {
|
||||
throw new HttpException({ msg: 'Integration not found' }, 404);
|
||||
}
|
||||
|
||||
const integrationProvider = socialIntegrationList.find(
|
||||
(p) => p.identifier === getIntegration.providerIdentifier
|
||||
)!;
|
||||
|
||||
if (!integrationProvider) {
|
||||
throw new HttpException({ msg: 'Integration provider not found' }, 404);
|
||||
}
|
||||
|
||||
const tools = this._integrationManager.getAllTools();
|
||||
if (
|
||||
// @ts-ignore
|
||||
!tools[integrationProvider.identifier]?.some(
|
||||
(p: any) => p.methodName === body.methodName
|
||||
) ||
|
||||
// @ts-ignore
|
||||
!integrationProvider[body.methodName]
|
||||
) {
|
||||
throw new HttpException({ msg: 'Tool not found' }, 404);
|
||||
}
|
||||
|
||||
while (true) {
|
||||
try {
|
||||
// @ts-ignore
|
||||
const result = await integrationProvider[body.methodName](
|
||||
getIntegration.token,
|
||||
body.data || {},
|
||||
getIntegration.internalId,
|
||||
getIntegration
|
||||
);
|
||||
|
||||
return { output: result };
|
||||
} catch (err) {
|
||||
if (err instanceof RefreshToken) {
|
||||
const data = await this._refreshIntegrationService.refresh(
|
||||
getIntegration
|
||||
);
|
||||
|
||||
if (!data) {
|
||||
await this._integrationService.disconnectChannel(
|
||||
org.id,
|
||||
getIntegration
|
||||
);
|
||||
throw new HttpException(
|
||||
{ msg: 'Channel disconnected due to expired token' },
|
||||
401
|
||||
);
|
||||
}
|
||||
|
||||
const { accessToken } = data;
|
||||
|
||||
if (accessToken) {
|
||||
getIntegration.token = accessToken;
|
||||
|
||||
if (integrationProvider.refreshWait) {
|
||||
await timer(10000);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
}
|
||||
throw new HttpException({ msg: 'Unexpected error' }, 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import { Injectable, NestMiddleware } from '@nestjs/common';
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { AuthService } from '@gitroom/helpers/auth/auth.service';
|
||||
import { User } from '@prisma/client';
|
||||
import { OrganizationService } from '@gitroom/nestjs-libraries/database/prisma/organizations/organization.service';
|
||||
import { UsersService } from '@gitroom/nestjs-libraries/database/prisma/users/users.service';
|
||||
import { getCookieUrlFromDomain } from '@gitroom/helpers/subdomain/subdomain.management';
|
||||
import { HttpForbiddenException } from '@gitroom/nestjs-libraries/services/exception.filter';
|
||||
import { MastraService } from '@gitroom/nestjs-libraries/chat/mastra.service';
|
||||
|
||||
export const removeAuth = (res: Response) => {
|
||||
res.cookie('auth', '', {
|
||||
domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),
|
||||
...(!process.env.NOT_SECURED
|
||||
? {
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
}
|
||||
: {}),
|
||||
expires: new Date(0),
|
||||
maxAge: -1,
|
||||
});
|
||||
res.header('logout', 'true');
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class AuthMiddleware implements NestMiddleware {
|
||||
constructor(
|
||||
private _organizationService: OrganizationService,
|
||||
private _userService: UsersService
|
||||
) {}
|
||||
async use(req: Request, res: Response, next: NextFunction) {
|
||||
const auth = req.headers.auth || req.cookies.auth;
|
||||
if (!auth) {
|
||||
throw new HttpForbiddenException();
|
||||
}
|
||||
try {
|
||||
// Verify the JWT signature only. Never trust authorization-relevant
|
||||
// claims (id, isSuperAdmin, activated) from the token body — always
|
||||
// re-resolve the user from the database using the id.
|
||||
const payload = AuthService.verifyJWT(auth) as User | null;
|
||||
const orgHeader = req.cookies.showorg || req.headers.showorg;
|
||||
|
||||
if (!payload?.id) {
|
||||
throw new HttpForbiddenException();
|
||||
}
|
||||
|
||||
let user = (await this._userService.getUserById(payload.id)) as User | null;
|
||||
|
||||
if (!user) {
|
||||
throw new HttpForbiddenException();
|
||||
}
|
||||
|
||||
if (!user.activated) {
|
||||
throw new HttpForbiddenException();
|
||||
}
|
||||
|
||||
const impersonate = req.cookies.impersonate || req.headers.impersonate;
|
||||
if (user?.isSuperAdmin && impersonate) {
|
||||
const loadImpersonate = await this._organizationService.getUserOrg(
|
||||
impersonate
|
||||
);
|
||||
|
||||
if (loadImpersonate) {
|
||||
user = loadImpersonate.user;
|
||||
user.isSuperAdmin = true;
|
||||
delete user.password;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-expect-error
|
||||
req.user = user;
|
||||
|
||||
// @ts-ignore
|
||||
loadImpersonate.organization.users =
|
||||
loadImpersonate.organization.users.filter(
|
||||
(f) => f.userId === user.id
|
||||
);
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-expect-error
|
||||
req.org = loadImpersonate.organization;
|
||||
next();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
delete user.password;
|
||||
const organization = (
|
||||
await this._organizationService.getOrgsByUserId(user.id)
|
||||
).filter((f) => !f.users[0].disabled);
|
||||
const setOrg =
|
||||
organization.find((org) => org.id === orgHeader) || organization[0];
|
||||
|
||||
if (!organization) {
|
||||
throw new HttpForbiddenException();
|
||||
}
|
||||
|
||||
if (!setOrg.apiKey) {
|
||||
await this._organizationService.updateApiKey(setOrg.id);
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-expect-error
|
||||
req.user = user;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-expect-error
|
||||
req.org = setOrg;
|
||||
} catch (err) {
|
||||
throw new HttpForbiddenException();
|
||||
}
|
||||
next();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Provider, User } from '@prisma/client';
|
||||
import { CreateOrgUserDto } from '@gitroom/nestjs-libraries/dtos/auth/create.org.user.dto';
|
||||
import { LoginUserDto } from '@gitroom/nestjs-libraries/dtos/auth/login.user.dto';
|
||||
import { UsersService } from '@gitroom/nestjs-libraries/database/prisma/users/users.service';
|
||||
import { OrganizationService } from '@gitroom/nestjs-libraries/database/prisma/organizations/organization.service';
|
||||
import { AuthService as AuthChecker } from '@gitroom/helpers/auth/auth.service';
|
||||
import { AuthProviderManager } from '@gitroom/backend/services/auth/providers/providers.manager';
|
||||
import dayjs from 'dayjs';
|
||||
import { NotificationService } from '@gitroom/nestjs-libraries/database/prisma/notifications/notification.service';
|
||||
import { ForgotReturnPasswordDto } from '@gitroom/nestjs-libraries/dtos/auth/forgot-return.password.dto';
|
||||
import { EmailService } from '@gitroom/nestjs-libraries/services/email.service';
|
||||
import { NewsletterService } from '@gitroom/nestjs-libraries/newsletter/newsletter.service';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(
|
||||
private _userService: UsersService,
|
||||
private _organizationService: OrganizationService,
|
||||
private _notificationService: NotificationService,
|
||||
private _emailService: EmailService,
|
||||
private _providerManager: AuthProviderManager
|
||||
) {}
|
||||
async canRegister(provider: string) {
|
||||
if (
|
||||
process.env.DISABLE_REGISTRATION !== 'true' ||
|
||||
provider === Provider.GENERIC
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return (await this._organizationService.getCount()) === 0;
|
||||
}
|
||||
|
||||
async routeAuth(
|
||||
provider: Provider,
|
||||
body: CreateOrgUserDto | LoginUserDto,
|
||||
ip: string,
|
||||
userAgent: string,
|
||||
addToOrg?: boolean | { orgId: string; role: 'USER' | 'ADMIN'; id: string }
|
||||
) {
|
||||
if (provider === Provider.LOCAL) {
|
||||
if (process.env.DISALLOW_PLUS && body.email.includes('+')) {
|
||||
throw new Error('Email with plus sign is not allowed');
|
||||
}
|
||||
if (body instanceof CreateOrgUserDto) {
|
||||
body.email = body.email.toLowerCase();
|
||||
}
|
||||
const user = await this._userService.getUserByEmail(body.email);
|
||||
if (body instanceof CreateOrgUserDto) {
|
||||
if (user) {
|
||||
throw new Error('Email already exists');
|
||||
}
|
||||
|
||||
if (!(await this.canRegister(provider))) {
|
||||
throw new Error('Registration is disabled');
|
||||
}
|
||||
|
||||
const create = await this._organizationService.createOrgAndUser(
|
||||
body,
|
||||
ip,
|
||||
userAgent
|
||||
);
|
||||
|
||||
const addedOrg =
|
||||
addToOrg && typeof addToOrg !== 'boolean'
|
||||
? await this._organizationService.addUserToOrg(
|
||||
create.users[0].user.id,
|
||||
addToOrg.id,
|
||||
addToOrg.orgId,
|
||||
addToOrg.role
|
||||
)
|
||||
: false;
|
||||
|
||||
const obj = { addedOrg, jwt: await this.jwt(create.users[0].user) };
|
||||
await this._emailService.sendEmail(
|
||||
body.email,
|
||||
'Activate your account',
|
||||
`Click <a href="${process.env.FRONTEND_URL}/auth/activate/${obj.jwt}">here</a> to activate your account`,
|
||||
'top'
|
||||
);
|
||||
return obj;
|
||||
}
|
||||
|
||||
if (!user || !AuthChecker.comparePassword(body.password, user.password)) {
|
||||
throw new Error('Invalid user name or password');
|
||||
}
|
||||
|
||||
if (!user.activated) {
|
||||
throw new Error('User is not activated');
|
||||
}
|
||||
|
||||
return { addedOrg: false, jwt: await this.jwt(user) };
|
||||
}
|
||||
|
||||
const user = await this.loginOrRegisterProvider(
|
||||
provider,
|
||||
body as CreateOrgUserDto,
|
||||
ip,
|
||||
userAgent
|
||||
);
|
||||
|
||||
const addedOrg =
|
||||
addToOrg && typeof addToOrg !== 'boolean'
|
||||
? await this._organizationService.addUserToOrg(
|
||||
user.id,
|
||||
addToOrg.id,
|
||||
addToOrg.orgId,
|
||||
addToOrg.role
|
||||
)
|
||||
: false;
|
||||
return { addedOrg, jwt: await this.jwt(user) };
|
||||
}
|
||||
|
||||
public getOrgFromCookie(cookie?: string) {
|
||||
if (!cookie) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const getOrg: any = AuthChecker.verifyJWT(cookie);
|
||||
if (dayjs(getOrg.timeLimit).isBefore(dayjs())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return getOrg as {
|
||||
email: string;
|
||||
role: 'USER' | 'ADMIN';
|
||||
orgId: string;
|
||||
id: string;
|
||||
};
|
||||
} catch (err) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async loginOrRegisterProvider(
|
||||
provider: Provider,
|
||||
body: CreateOrgUserDto,
|
||||
ip: string,
|
||||
userAgent: string
|
||||
) {
|
||||
const providerInstance = this._providerManager.getProvider(provider);
|
||||
const providerUser = await providerInstance.getUser(body.providerToken);
|
||||
|
||||
if (!providerUser) {
|
||||
throw new Error('Invalid provider token');
|
||||
}
|
||||
|
||||
const user = await this._userService.getUserByProvider(
|
||||
providerUser.id,
|
||||
provider
|
||||
);
|
||||
if (user) {
|
||||
return user;
|
||||
}
|
||||
|
||||
if (!(await this.canRegister(provider))) {
|
||||
throw new Error('Registration is disabled');
|
||||
}
|
||||
|
||||
const create = await this._organizationService.createOrgAndUser(
|
||||
{
|
||||
company: body.company,
|
||||
email: providerUser.email,
|
||||
password: '',
|
||||
provider,
|
||||
providerId: providerUser.id,
|
||||
datafast_visitor_id: body.datafast_visitor_id,
|
||||
},
|
||||
ip,
|
||||
userAgent
|
||||
);
|
||||
|
||||
this._track('register', providerUser.email, body.datafast_visitor_id).catch(
|
||||
(err) => {}
|
||||
);
|
||||
|
||||
await NewsletterService.register(providerUser.email);
|
||||
|
||||
try {
|
||||
if (providerInstance?.postRegistration) {
|
||||
await providerInstance.postRegistration(body.providerToken, create.id);
|
||||
}
|
||||
} catch (err) {
|
||||
// Don't fail registration if postRegistration fails
|
||||
}
|
||||
|
||||
return create.users[0].user;
|
||||
}
|
||||
|
||||
private async _track(
|
||||
name: string,
|
||||
email: string,
|
||||
datafast_visitor_id: string
|
||||
) {
|
||||
if (email && datafast_visitor_id && process.env.DATAFAST_API_KEY) {
|
||||
try {
|
||||
await fetch('https://datafa.st/api/v1/goals', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${process.env.DATAFAST_API_KEY}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
datafast_visitor_id: datafast_visitor_id,
|
||||
name: name,
|
||||
metadata: {
|
||||
email,
|
||||
},
|
||||
}),
|
||||
});
|
||||
} catch (err) {}
|
||||
}
|
||||
}
|
||||
|
||||
async forgot(email: string) {
|
||||
const user = await this._userService.getUserByEmail(email);
|
||||
if (!user || user.providerName !== Provider.LOCAL) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const resetValues = AuthChecker.signJWT({
|
||||
id: user.id,
|
||||
expires: dayjs().add(20, 'minutes').format('YYYY-MM-DD HH:mm:ss'),
|
||||
});
|
||||
|
||||
await this._notificationService.sendEmail(
|
||||
user.email,
|
||||
'Reset your password',
|
||||
`You have requested to reset your passsord. <br />Click <a href="${process.env.FRONTEND_URL}/auth/forgot/${resetValues}">here</a> to reset your password<br />The link will expire in 20 minutes`
|
||||
);
|
||||
}
|
||||
|
||||
forgotReturn(body: ForgotReturnPasswordDto) {
|
||||
const user = AuthChecker.verifyJWT(body.token) as {
|
||||
id: string;
|
||||
expires: string;
|
||||
};
|
||||
if (dayjs(user.expires).isBefore(dayjs())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return this._userService.updatePassword(user.id, body.password);
|
||||
}
|
||||
|
||||
async activate(code: string, tracking: string) {
|
||||
const user = AuthChecker.verifyJWT(code) as {
|
||||
id: string;
|
||||
activated: boolean;
|
||||
email: string;
|
||||
};
|
||||
if (user.id && !user.activated) {
|
||||
const getUserAgain = await this._userService.getUserByEmail(user.email);
|
||||
if (getUserAgain.activated) {
|
||||
return false;
|
||||
}
|
||||
await this._userService.activateUser(user.id);
|
||||
user.activated = true;
|
||||
this._track('register', user.email, tracking).catch((err) => {});
|
||||
await NewsletterService.register(user.email);
|
||||
return this.jwt(user as any);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
async resendActivationEmail(email: string) {
|
||||
const user = await this._userService.getUserByEmail(email);
|
||||
|
||||
if (!user) {
|
||||
throw new Error('User not found');
|
||||
}
|
||||
|
||||
if (user.activated) {
|
||||
throw new Error('Account is already activated');
|
||||
}
|
||||
|
||||
const jwt = await this.jwt(user);
|
||||
|
||||
await this._emailService.sendEmail(
|
||||
user.email,
|
||||
'Activate your account',
|
||||
`Click <a href="${process.env.FRONTEND_URL}/auth/activate/${jwt}">here</a> to activate your account`,
|
||||
'top'
|
||||
);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
oauthLink(provider: string, query?: any) {
|
||||
const providerInstance = this._providerManager.getProvider(provider);
|
||||
return providerInstance.generateLink(query);
|
||||
}
|
||||
|
||||
async checkExists(provider: string, code: string, redirectUri?: string) {
|
||||
const providerInstance = this._providerManager.getProvider(provider);
|
||||
const token = await providerInstance.getToken(code, redirectUri);
|
||||
const user = await providerInstance.getUser(token);
|
||||
if (!user) {
|
||||
throw new Error('Invalid user');
|
||||
}
|
||||
const checkExists = await this._userService.getUserByProvider(
|
||||
user.id,
|
||||
provider as Provider
|
||||
);
|
||||
if (checkExists) {
|
||||
return { jwt: await this.jwt(checkExists) };
|
||||
}
|
||||
|
||||
return { token };
|
||||
}
|
||||
|
||||
private async jwt(user: User) {
|
||||
if (user.password) {
|
||||
delete user.password;
|
||||
}
|
||||
return AuthChecker.signJWT(user);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { HttpException, HttpStatus } from '@nestjs/common';
|
||||
|
||||
export enum Sections {
|
||||
CHANNEL = 'channel',
|
||||
POSTS_PER_MONTH = 'posts_per_month',
|
||||
VIDEOS_PER_MONTH = 'videos_per_month',
|
||||
TEAM_MEMBERS = 'team_members',
|
||||
COMMUNITY_FEATURES = 'community_features',
|
||||
FEATURED_BY_GITROOM = 'featured_by_gitroom',
|
||||
AI = 'ai',
|
||||
IMPORT_FROM_CHANNELS = 'import_from_channels',
|
||||
ADMIN = 'admin',
|
||||
WEBHOOKS = 'webhooks',
|
||||
}
|
||||
|
||||
export enum AuthorizationActions {
|
||||
Create = 'create',
|
||||
Read = 'read',
|
||||
Update = 'update',
|
||||
Delete = 'delete',
|
||||
}
|
||||
|
||||
export class SubscriptionException extends HttpException {
|
||||
constructor(message: { section: Sections; action: AuthorizationActions }) {
|
||||
super(message, HttpStatus.PAYMENT_REQUIRED);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
import { AuthorizationActions, Sections } from './permission.exception.class';
|
||||
|
||||
export const CHECK_POLICIES_KEY = 'check_policy';
|
||||
export type AbilityPolicy = [AuthorizationActions, Sections];
|
||||
export const CheckPolicies = (...handlers: AbilityPolicy[]) =>
|
||||
SetMetadata(CHECK_POLICIES_KEY, handlers);
|
||||
@@ -0,0 +1,69 @@
|
||||
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import {
|
||||
AppAbility,
|
||||
PermissionsService,
|
||||
} from '@gitroom/backend/services/auth/permissions/permissions.service';
|
||||
import {
|
||||
AbilityPolicy,
|
||||
CHECK_POLICIES_KEY,
|
||||
} from '@gitroom/backend/services/auth/permissions/permissions.ability';
|
||||
import { Organization } from '@prisma/client';
|
||||
import { Request } from 'express';
|
||||
import { SubscriptionException } from './permission.exception.class';
|
||||
|
||||
@Injectable()
|
||||
export class PoliciesGuard implements CanActivate {
|
||||
constructor(
|
||||
private _reflector: Reflector,
|
||||
private _authorizationService: PermissionsService
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request: Request = context.switchToHttp().getRequest();
|
||||
if (
|
||||
request.path.indexOf('/auth') > -1 ||
|
||||
request.path.indexOf('/auth') > -1 ||
|
||||
request.path.indexOf('/integrations/social-connect') > -1 ||
|
||||
request.path.indexOf('/integrations/provider') > -1
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const policyHandlers =
|
||||
this._reflector.get<AbilityPolicy[]>(
|
||||
CHECK_POLICIES_KEY,
|
||||
context.getHandler()
|
||||
) || [];
|
||||
|
||||
if (!policyHandlers || !policyHandlers.length) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-expect-error
|
||||
const { org }: { org: Organization } = request;
|
||||
|
||||
const refreshChannelId = typeof request.query?.refresh === 'string' ? request.query.refresh : undefined;
|
||||
|
||||
// @ts-ignore
|
||||
const ability = await this._authorizationService.check(org.id, org.createdAt, org.users[0].role, policyHandlers, refreshChannelId);
|
||||
|
||||
const item = policyHandlers.find(
|
||||
(handler) => !this.execPolicyHandler(handler, ability)
|
||||
);
|
||||
|
||||
if (item) {
|
||||
throw new SubscriptionException({
|
||||
section: item[1],
|
||||
action: item[0],
|
||||
});
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private execPolicyHandler(handler: AbilityPolicy, ability: AppAbility) {
|
||||
return ability.can(handler[0], handler[1]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
import { Ability, AbilityBuilder, AbilityClass } from '@casl/ability';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { pricing } from '@gitroom/nestjs-libraries/database/prisma/subscriptions/pricing';
|
||||
import { SubscriptionService } from '@gitroom/nestjs-libraries/database/prisma/subscriptions/subscription.service';
|
||||
import { PostsService } from '@gitroom/nestjs-libraries/database/prisma/posts/posts.service';
|
||||
import { IntegrationService } from '@gitroom/nestjs-libraries/database/prisma/integrations/integration.service';
|
||||
import dayjs from 'dayjs';
|
||||
import { WebhooksService } from '@gitroom/nestjs-libraries/database/prisma/webhooks/webhooks.service';
|
||||
import { AuthorizationActions, Sections } from './permission.exception.class';
|
||||
|
||||
export type AppAbility = Ability<[AuthorizationActions, Sections]>;
|
||||
|
||||
@Injectable()
|
||||
export class PermissionsService {
|
||||
constructor(
|
||||
private _subscriptionService: SubscriptionService,
|
||||
private _postsService: PostsService,
|
||||
private _integrationService: IntegrationService,
|
||||
private _webhooksService: WebhooksService
|
||||
) {}
|
||||
async getPackageOptions(orgId: string) {
|
||||
const subscription =
|
||||
await this._subscriptionService.getSubscriptionByOrganizationId(orgId);
|
||||
|
||||
const tier =
|
||||
subscription?.subscriptionTier ||
|
||||
(!process.env.STRIPE_PUBLISHABLE_KEY ? 'PRO' : 'FREE');
|
||||
|
||||
const { channel, ...all } = pricing[tier];
|
||||
return {
|
||||
subscription,
|
||||
options: {
|
||||
...all,
|
||||
...{ channel: tier === 'FREE' ? channel : -10 },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async check(
|
||||
orgId: string,
|
||||
created_at: Date,
|
||||
permission: 'USER' | 'ADMIN' | 'SUPERADMIN',
|
||||
requestedPermission: Array<[AuthorizationActions, Sections]>,
|
||||
refreshChannelId?: string
|
||||
) {
|
||||
const { can, build } = new AbilityBuilder<
|
||||
Ability<[AuthorizationActions, Sections]>
|
||||
>(Ability as AbilityClass<AppAbility>);
|
||||
|
||||
if (
|
||||
requestedPermission.length === 0 ||
|
||||
!process.env.STRIPE_PUBLISHABLE_KEY
|
||||
) {
|
||||
for (const [action, section] of requestedPermission) {
|
||||
can(action, section);
|
||||
}
|
||||
return build({
|
||||
detectSubjectType: (item) =>
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
item.constructor,
|
||||
});
|
||||
}
|
||||
|
||||
const { subscription, options } = await this.getPackageOptions(orgId);
|
||||
for (const [action, section] of requestedPermission) {
|
||||
// check for the amount of channels
|
||||
if (section === Sections.CHANNEL) {
|
||||
// Refreshing an existing channel doesn't add a new one, so skip the limit check
|
||||
// but only if the channel actually belongs to this org
|
||||
if (refreshChannelId) {
|
||||
const existingIntegration =
|
||||
await this._integrationService.getIntegrationById(
|
||||
orgId,
|
||||
refreshChannelId
|
||||
);
|
||||
if (existingIntegration) {
|
||||
can(action, section);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
const totalChannels = (
|
||||
await this._integrationService.getIntegrationsList(orgId)
|
||||
).filter((f) => !f.refreshNeeded).length;
|
||||
|
||||
if (
|
||||
(options.channel && options.channel > totalChannels) ||
|
||||
(subscription?.totalChannels || 0) > totalChannels
|
||||
) {
|
||||
can(action, section);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (section === Sections.WEBHOOKS) {
|
||||
const totalWebhooks = await this._webhooksService.getTotal(orgId);
|
||||
if (totalWebhooks < options.webhooks) {
|
||||
can(AuthorizationActions.Create, section);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// check for posts per month
|
||||
if (section === Sections.POSTS_PER_MONTH) {
|
||||
const createdAt =
|
||||
(await this._subscriptionService.getSubscription(orgId))?.createdAt ||
|
||||
created_at;
|
||||
const totalMonthPast = Math.abs(
|
||||
dayjs(createdAt).diff(dayjs(), 'month')
|
||||
);
|
||||
const checkFrom = dayjs(createdAt).add(totalMonthPast, 'month');
|
||||
const count = await this._postsService.countPostsFromDay(
|
||||
orgId,
|
||||
checkFrom.toDate()
|
||||
);
|
||||
|
||||
if (count < options.posts_per_month) {
|
||||
can(action, section);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (section === Sections.TEAM_MEMBERS && options.team_members) {
|
||||
can(action, section);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
section === Sections.ADMIN &&
|
||||
['ADMIN', 'SUPERADMIN'].includes(permission)
|
||||
) {
|
||||
can(action, section);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
section === Sections.COMMUNITY_FEATURES &&
|
||||
options.community_features
|
||||
) {
|
||||
can(action, section);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
section === Sections.FEATURED_BY_GITROOM &&
|
||||
options.featured_by_gitroom
|
||||
) {
|
||||
can(action, section);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (section === Sections.AI && options.ai) {
|
||||
can(action, section);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
section === Sections.IMPORT_FROM_CHANNELS &&
|
||||
options.import_from_channels
|
||||
) {
|
||||
can(action, section);
|
||||
}
|
||||
}
|
||||
|
||||
return build({
|
||||
detectSubjectType: (item) =>
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
item.constructor,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import {
|
||||
ArgumentsHost,
|
||||
Catch,
|
||||
ExceptionFilter,
|
||||
HttpException,
|
||||
} from '@nestjs/common';
|
||||
import { AuthorizationActions, Sections, SubscriptionException } from '@gitroom/backend/services/auth/permissions/permission.exception.class';
|
||||
|
||||
@Catch(SubscriptionException)
|
||||
export class SubscriptionExceptionFilter implements ExceptionFilter {
|
||||
catch(exception: HttpException, host: ArgumentsHost) {
|
||||
const ctx = host.switchToHttp();
|
||||
const response = ctx.getResponse();
|
||||
const status = exception.getStatus();
|
||||
const error: { section: Sections; action: AuthorizationActions } =
|
||||
exception.getResponse() as any;
|
||||
|
||||
const message = getErrorMessage(error);
|
||||
|
||||
response.status(status).json({
|
||||
statusCode: status,
|
||||
message,
|
||||
url: process.env.FRONTEND_URL + '/billing',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const getErrorMessage = (error: {
|
||||
section: Sections;
|
||||
action: AuthorizationActions;
|
||||
}) => {
|
||||
switch (error.section) {
|
||||
case Sections.POSTS_PER_MONTH:
|
||||
switch (error.action) {
|
||||
default:
|
||||
return 'You have reached the maximum number of posts for your subscription. Please upgrade your subscription to add more posts.';
|
||||
}
|
||||
case Sections.CHANNEL:
|
||||
switch (error.action) {
|
||||
default:
|
||||
return 'You have reached the maximum number of channels for your subscription. Please upgrade your subscription to add more channels.';
|
||||
}
|
||||
case Sections.WEBHOOKS:
|
||||
switch (error.action) {
|
||||
default:
|
||||
return 'You have reached the maximum number of webhooks for your subscription. Please upgrade your subscription to add more webhooks.';
|
||||
}
|
||||
case Sections.VIDEOS_PER_MONTH:
|
||||
switch (error.action) {
|
||||
default:
|
||||
return 'You have reached the maximum number of generated videos for your subscription. Please upgrade your subscription to generate more videos.';
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,34 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
export abstract class AuthProviderAbstract {
|
||||
abstract generateLink(query?: any): Promise<string> | string;
|
||||
abstract getToken(code: string, redirectUri?: string): Promise<string>;
|
||||
abstract getUser(
|
||||
providerToken: string
|
||||
): Promise<{ email: string; id: string }> | false;
|
||||
async postRegistration(
|
||||
providerToken: string,
|
||||
orgId: string
|
||||
): Promise<void> {}
|
||||
}
|
||||
|
||||
export interface AuthProviderParams {
|
||||
provider: string;
|
||||
}
|
||||
|
||||
export function AuthProvider(params: AuthProviderParams) {
|
||||
return function (target: any) {
|
||||
Injectable()(target);
|
||||
|
||||
const existingMetadata =
|
||||
Reflect.getMetadata('auth-provider', AuthProviderAbstract) || [];
|
||||
|
||||
existingMetadata.push({ target, provider: params.provider });
|
||||
|
||||
Reflect.defineMetadata(
|
||||
'auth-provider',
|
||||
existingMetadata,
|
||||
AuthProviderAbstract
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import {
|
||||
AuthProvider,
|
||||
AuthProviderAbstract,
|
||||
} from '@gitroom/backend/services/auth/providers.interface';
|
||||
import { NeynarAPIClient } from '@neynar/nodejs-sdk';
|
||||
|
||||
const client = new NeynarAPIClient({
|
||||
apiKey: process.env.NEYNAR_SECRET_KEY || '00000000-000-0000-000-000000000000',
|
||||
});
|
||||
|
||||
@AuthProvider({ provider: 'FARCASTER' })
|
||||
export class FarcasterProvider extends AuthProviderAbstract {
|
||||
generateLink() {
|
||||
return '';
|
||||
}
|
||||
|
||||
async getToken(code: string, _redirectUri?: string) {
|
||||
const data = JSON.parse(Buffer.from(code, 'base64').toString());
|
||||
const status = await client.lookupSigner({ signerUuid: data.signer_uuid });
|
||||
if (status.status === 'approved') {
|
||||
return data.signer_uuid;
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
async getUser(providerToken: string) {
|
||||
const status = await client.lookupSigner({ signerUuid: providerToken });
|
||||
if (status.status !== 'approved') {
|
||||
return {
|
||||
id: '',
|
||||
email: '',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
id: String('farcaster_' + status.fid),
|
||||
email: String('farcaster_' + status.fid),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import {
|
||||
AuthProvider,
|
||||
AuthProviderAbstract,
|
||||
} from '@gitroom/backend/services/auth/providers.interface';
|
||||
|
||||
@AuthProvider({ provider: 'GITHUB' })
|
||||
export class GithubProvider extends AuthProviderAbstract {
|
||||
generateLink(): string {
|
||||
return `https://github.com/login/oauth/authorize?client_id=${
|
||||
process.env.GITHUB_CLIENT_ID
|
||||
}&scope=user:email&redirect_uri=${encodeURIComponent(
|
||||
`${process.env.FRONTEND_URL}/settings`
|
||||
)}`;
|
||||
}
|
||||
|
||||
async getToken(code: string, _redirectUri?: string): Promise<string> {
|
||||
const { access_token } = await (
|
||||
await fetch('https://github.com/login/oauth/access_token', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
client_id: process.env.GITHUB_CLIENT_ID,
|
||||
client_secret: process.env.GITHUB_CLIENT_SECRET,
|
||||
code,
|
||||
redirect_uri: `${process.env.FRONTEND_URL}/settings`,
|
||||
}),
|
||||
})
|
||||
).json();
|
||||
|
||||
return access_token;
|
||||
}
|
||||
|
||||
async getUser(access_token: string): Promise<{ email: string; id: string }> {
|
||||
const data = await (
|
||||
await fetch('https://api.github.com/user', {
|
||||
headers: {
|
||||
Authorization: `token ${access_token}`,
|
||||
},
|
||||
})
|
||||
).json();
|
||||
|
||||
const [{ email }] = await (
|
||||
await fetch('https://api.github.com/user/emails', {
|
||||
headers: {
|
||||
Authorization: `token ${access_token}`,
|
||||
},
|
||||
})
|
||||
).json();
|
||||
|
||||
return {
|
||||
email: email,
|
||||
id: String(data.id),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { google } from 'googleapis';
|
||||
import {
|
||||
AuthProvider,
|
||||
AuthProviderAbstract,
|
||||
} from '@gitroom/backend/services/auth/providers.interface';
|
||||
|
||||
const defaultRedirect = () =>
|
||||
`${process.env.FRONTEND_URL}/integrations/social/youtube`;
|
||||
|
||||
const makeClient = (redirectUri: string) =>
|
||||
new google.auth.OAuth2({
|
||||
clientId: process.env.YOUTUBE_CLIENT_ID,
|
||||
clientSecret: process.env.YOUTUBE_CLIENT_SECRET,
|
||||
redirectUri,
|
||||
});
|
||||
|
||||
@AuthProvider({ provider: 'GOOGLE' })
|
||||
export class GoogleProvider extends AuthProviderAbstract {
|
||||
generateLink(query?: { redirect_uri?: string }) {
|
||||
const redirectUri = query?.redirect_uri || defaultRedirect();
|
||||
return makeClient(redirectUri).generateAuthUrl({
|
||||
access_type: 'online',
|
||||
prompt: 'consent',
|
||||
state: 'login',
|
||||
redirect_uri: redirectUri,
|
||||
scope: [
|
||||
'https://www.googleapis.com/auth/userinfo.profile',
|
||||
'https://www.googleapis.com/auth/userinfo.email',
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
async getToken(code: string, redirectUri?: string) {
|
||||
const client = makeClient(redirectUri || defaultRedirect());
|
||||
const { tokens } = await client.getToken(code);
|
||||
return tokens.access_token!;
|
||||
}
|
||||
|
||||
async getUser(providerToken: string) {
|
||||
const client = makeClient(defaultRedirect());
|
||||
client.setCredentials({ access_token: providerToken });
|
||||
const { data } = await google
|
||||
.oauth2({ version: 'v2', auth: client })
|
||||
.userinfo.get();
|
||||
|
||||
return {
|
||||
id: data.id!,
|
||||
email: data.email!,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import {
|
||||
AuthProvider,
|
||||
AuthProviderAbstract,
|
||||
} from '@gitroom/backend/services/auth/providers.interface';
|
||||
|
||||
@AuthProvider({ provider: 'GENERIC' })
|
||||
export class OauthProvider extends AuthProviderAbstract {
|
||||
private getConfig() {
|
||||
const {
|
||||
POSTIZ_OAUTH_AUTH_URL,
|
||||
POSTIZ_OAUTH_CLIENT_ID,
|
||||
POSTIZ_OAUTH_CLIENT_SECRET,
|
||||
POSTIZ_OAUTH_TOKEN_URL,
|
||||
POSTIZ_OAUTH_USERINFO_URL,
|
||||
FRONTEND_URL,
|
||||
} = process.env;
|
||||
|
||||
if (
|
||||
!POSTIZ_OAUTH_USERINFO_URL ||
|
||||
!POSTIZ_OAUTH_TOKEN_URL ||
|
||||
!POSTIZ_OAUTH_CLIENT_ID ||
|
||||
!POSTIZ_OAUTH_CLIENT_SECRET ||
|
||||
!POSTIZ_OAUTH_AUTH_URL ||
|
||||
!FRONTEND_URL
|
||||
) {
|
||||
throw new Error('POSTIZ_OAUTH environment variables are not set');
|
||||
}
|
||||
|
||||
return {
|
||||
authUrl: POSTIZ_OAUTH_AUTH_URL,
|
||||
clientId: POSTIZ_OAUTH_CLIENT_ID,
|
||||
clientSecret: POSTIZ_OAUTH_CLIENT_SECRET,
|
||||
tokenUrl: POSTIZ_OAUTH_TOKEN_URL,
|
||||
userInfoUrl: POSTIZ_OAUTH_USERINFO_URL,
|
||||
frontendUrl: FRONTEND_URL,
|
||||
};
|
||||
}
|
||||
|
||||
generateLink(): string {
|
||||
const { authUrl, clientId, frontendUrl } = this.getConfig();
|
||||
const params = new URLSearchParams({
|
||||
client_id: clientId,
|
||||
scope: 'openid profile email',
|
||||
response_type: 'code',
|
||||
redirect_uri: `${frontendUrl}/settings`,
|
||||
});
|
||||
|
||||
return `${authUrl}?${params.toString()}`;
|
||||
}
|
||||
|
||||
async getToken(code: string, _redirectUri?: string): Promise<string> {
|
||||
const { tokenUrl, clientId, clientSecret, frontendUrl } = this.getConfig();
|
||||
const response = await fetch(`${tokenUrl}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
Accept: 'application/json',
|
||||
},
|
||||
body: new URLSearchParams({
|
||||
grant_type: 'authorization_code',
|
||||
client_id: clientId,
|
||||
client_secret: clientSecret,
|
||||
code,
|
||||
redirect_uri: `${frontendUrl}/settings`,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.text();
|
||||
throw new Error(`Token request failed: ${error}`);
|
||||
}
|
||||
|
||||
const { access_token } = await response.json();
|
||||
return access_token;
|
||||
}
|
||||
|
||||
async getUser(access_token: string): Promise<{ email: string; id: string }> {
|
||||
const { userInfoUrl } = this.getConfig();
|
||||
const response = await fetch(`${userInfoUrl}`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${access_token}`,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.text();
|
||||
throw new Error(`User info request failed: ${error}`);
|
||||
}
|
||||
|
||||
const { email, sub: id } = await response.json();
|
||||
return { email, id };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { ModuleRef } from '@nestjs/core';
|
||||
import { AuthProviderAbstract } from '@gitroom/backend/services/auth/providers.interface';
|
||||
|
||||
@Injectable()
|
||||
export class AuthProviderManager {
|
||||
constructor(private _moduleRef: ModuleRef) {}
|
||||
|
||||
getProvider(provider: string): AuthProviderAbstract {
|
||||
const metadata =
|
||||
Reflect.getMetadata('auth-provider', AuthProviderAbstract) || [];
|
||||
|
||||
const found = metadata.find(
|
||||
(m: any) => m.provider === provider
|
||||
);
|
||||
|
||||
if (!found) {
|
||||
throw new Error(`Auth provider ${provider} not found`);
|
||||
}
|
||||
|
||||
return this._moduleRef.get(found.target, { strict: false });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import {
|
||||
AuthProvider,
|
||||
AuthProviderAbstract,
|
||||
} from '@gitroom/backend/services/auth/providers.interface';
|
||||
import { randomBytes } from 'crypto';
|
||||
import { ioRedis } from '@gitroom/nestjs-libraries/redis/redis.service';
|
||||
import bs58 from 'bs58';
|
||||
import nacl from 'tweetnacl';
|
||||
|
||||
function hexToUint8Array(hex) {
|
||||
if (hex.startsWith('0x')) {
|
||||
hex = hex.slice(2);
|
||||
}
|
||||
|
||||
if (hex.length % 2 !== 0) {
|
||||
throw new Error('Invalid hex string. It must have an even length.');
|
||||
}
|
||||
|
||||
const byteLength = hex.length / 2;
|
||||
const uint8Array = new Uint8Array(byteLength);
|
||||
|
||||
for (let i = 0; i < byteLength; i++) {
|
||||
const byteHex = hex.substr(i * 2, 2);
|
||||
uint8Array[i] = parseInt(byteHex, 16);
|
||||
}
|
||||
|
||||
return uint8Array;
|
||||
}
|
||||
|
||||
@AuthProvider({ provider: 'WALLET' })
|
||||
export class WalletProvider extends AuthProviderAbstract {
|
||||
async generateLink(params: { publicKey: string }) {
|
||||
if (!params.publicKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
const challenge = randomBytes(32).toString('hex');
|
||||
await ioRedis.set(`wallet:${params.publicKey}`, challenge, 'EX', 60);
|
||||
|
||||
return challenge;
|
||||
}
|
||||
|
||||
async getToken(code: string, _redirectUri?: string) {
|
||||
const { publicKey, challenge, signature } = JSON.parse(
|
||||
Buffer.from(code, 'base64').toString()
|
||||
);
|
||||
|
||||
if (!publicKey || !challenge || !signature) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const redisGet = await ioRedis.get(`wallet:${publicKey}`);
|
||||
if (redisGet !== challenge) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const publicKeyUint8 = bs58.decode(publicKey);
|
||||
const messageUint8 = new TextEncoder().encode(challenge);
|
||||
const signatureUint8 = hexToUint8Array(signature);
|
||||
const isValid = nacl.sign.detached.verify(
|
||||
messageUint8,
|
||||
signatureUint8,
|
||||
publicKeyUint8
|
||||
);
|
||||
|
||||
if (!isValid) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return code;
|
||||
}
|
||||
|
||||
async getUser(providerToken: string) {
|
||||
if ((await this.getToken(providerToken)) === '') {
|
||||
return {
|
||||
id: '',
|
||||
email: '',
|
||||
};
|
||||
}
|
||||
|
||||
const { publicKey } = JSON.parse(
|
||||
Buffer.from(providerToken, 'base64').toString()
|
||||
);
|
||||
|
||||
return {
|
||||
id: String(`wallet_${publicKey}`),
|
||||
email: String(`wallet_${publicKey}`),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { HttpStatus, Injectable, NestMiddleware } from '@nestjs/common';
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { OrganizationService } from '@gitroom/nestjs-libraries/database/prisma/organizations/organization.service';
|
||||
import { OAuthService } from '@gitroom/nestjs-libraries/database/prisma/oauth/oauth.service';
|
||||
import { HttpForbiddenException } from '@gitroom/nestjs-libraries/services/exception.filter';
|
||||
|
||||
@Injectable()
|
||||
export class PublicAuthMiddleware implements NestMiddleware {
|
||||
constructor(
|
||||
private _organizationService: OrganizationService,
|
||||
private _oauthService: OAuthService
|
||||
) {}
|
||||
async use(req: Request, res: Response, next: NextFunction) {
|
||||
const auth = (req.headers.authorization ||
|
||||
req.headers.Authorization) as string;
|
||||
if (!auth) {
|
||||
res.status(HttpStatus.UNAUTHORIZED).json({ msg: 'No API Key found' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (auth.startsWith('pos_')) {
|
||||
const authorization = await this._oauthService.getOrgByOAuthToken(auth);
|
||||
if (!authorization) {
|
||||
res
|
||||
.status(HttpStatus.UNAUTHORIZED)
|
||||
.json({ msg: 'Invalid OAuth token' });
|
||||
return;
|
||||
}
|
||||
|
||||
const org = authorization.organization;
|
||||
if (!!process.env.STRIPE_SECRET_KEY && !org.subscription) {
|
||||
res
|
||||
.status(HttpStatus.UNAUTHORIZED)
|
||||
.json({ msg: 'No subscription found' });
|
||||
return;
|
||||
}
|
||||
|
||||
// @ts-ignore
|
||||
req.org = { ...org, users: [{ users: { role: 'SUPERADMIN' } }] };
|
||||
} else {
|
||||
const org = await this._organizationService.getOrgByApiKey(auth);
|
||||
if (!org) {
|
||||
res
|
||||
.status(HttpStatus.UNAUTHORIZED)
|
||||
.json({ msg: 'Invalid API key' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!!process.env.STRIPE_SECRET_KEY && !org.subscription) {
|
||||
res
|
||||
.status(HttpStatus.UNAUTHORIZED)
|
||||
.json({ msg: 'No subscription found' });
|
||||
return;
|
||||
}
|
||||
|
||||
// @ts-ignore
|
||||
req.org = { ...org, users: [{ users: { role: 'SUPERADMIN' } }] };
|
||||
}
|
||||
} catch (err) {
|
||||
throw new HttpForbiddenException();
|
||||
}
|
||||
next();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"],
|
||||
"compilerOptions": {
|
||||
"module": "CommonJS",
|
||||
"resolveJsonModule": true,
|
||||
"declaration": true,
|
||||
"removeComments": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"experimentalDecorators": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"target": "ES2021",
|
||||
"sourceMap": true,
|
||||
"incremental": true,
|
||||
"skipLibCheck": true,
|
||||
"strictNullChecks": false,
|
||||
"noImplicitAny": false,
|
||||
"strictBindCallApply": false,
|
||||
"forceConsistentCasingInFileNames": false,
|
||||
"noFallthroughCasesInSwitch": false,
|
||||
"outDir": "./dist"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"declaration": true,
|
||||
"removeComments": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"target": "es2017",
|
||||
"sourceMap": true,
|
||||
"esModuleInterop": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
dist/
|
||||
node_modules/
|
||||
[._]*.s[a-v][a-z]
|
||||
[._]*.sw[a-p]
|
||||
[._]s[a-rt-v][a-z]
|
||||
[._]ss[a-gi-z]
|
||||
[._]sw[a-p]
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/nest-cli",
|
||||
"collection": "@nestjs/schematics",
|
||||
"monorepo": false,
|
||||
"sourceRoot": "src",
|
||||
"entryFile": "../../dist/commands/apps/commands/src/main",
|
||||
"language": "ts",
|
||||
"generateOptions": {
|
||||
"spec": false
|
||||
},
|
||||
"compilerOptions": {
|
||||
"manualRestart": true,
|
||||
"tsConfigPath": "./tsconfig.build.json",
|
||||
"webpack": false,
|
||||
"deleteOutDir": true,
|
||||
"assets": [],
|
||||
"watchAssets": false,
|
||||
"plugins": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"name": "postiz-command",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"scripts": {
|
||||
"dev": "dotenv -e ../../.env -- nest start --watch --entryFile=./apps/command/src/main",
|
||||
"build": "cross-env NODE_ENV=production nest build",
|
||||
"start": "node ./dist/apps/command/src/main.js"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC"
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { CommandModule as ExternalCommandModule } from 'nestjs-command';
|
||||
import { DatabaseModule } from '@gitroom/nestjs-libraries/database/prisma/database.module';
|
||||
import { RefreshTokens } from './tasks/refresh.tokens';
|
||||
import { ConfigurationTask } from './tasks/configuration';
|
||||
import { AgentRun } from './tasks/agent.run';
|
||||
import { AgentModule } from '@gitroom/nestjs-libraries/agent/agent.module';
|
||||
|
||||
@Module({
|
||||
imports: [ExternalCommandModule, DatabaseModule, AgentModule],
|
||||
controllers: [],
|
||||
providers: [RefreshTokens, ConfigurationTask, AgentRun],
|
||||
get exports() {
|
||||
return [...this.imports, ...this.providers];
|
||||
},
|
||||
})
|
||||
export class CommandModule {}
|
||||