trypost/app/Providers/AppServiceProvider.php

292 lines
10 KiB
PHP
Raw Normal View History

2026-01-15 01:13:44 +00:00
<?php
declare(strict_types=1);
2026-01-15 01:13:44 +00:00
namespace App\Providers;
use App\Listeners\StripeEventListener;
use App\Models\AccessToken;
use App\Models\Account;
use App\Models\AiUsageLog;
use App\Models\Automation;
use App\Models\AutomationNodeRun;
use App\Models\AutomationNodeState;
use App\Models\AutomationRun;
use App\Models\AutomationTriggerItem;
use App\Models\Invite;
use App\Models\Media;
use App\Models\Notification;
refactor: notification preferences, header slots, calendar layout, UI polish Notification preferences: - Create notification_preferences table (post_published, post_failed, account_disconnected booleans per user) - NotificationPreferenceController with firstOrCreate on first visit - SendNotification job respects email preferences before sending - Settings page with toggle switches, i18n in 3 languages - 8 new tests for preferences (controller + wantsEmailFor + job integration) Post published notification: - PostPublished mail + maizzle template - Notify owner on successful publish via SendNotification job - PostPublished type added to notification enum Header & Layout: - Rename AppSidebarHeader to AppHeader with left/center/right slots - showSidebarTrigger prop to hide sidebar toggle - Calendar: controls in header (left: nav, center: date, right: tabs + new post) - Fixed header with scrollable content (flex h-screen pattern) - fullWidth pages use overflow-y-auto (fixes month view scroll) UI improvements: - Action buttons moved to header-right: posts, hashtags, labels - Settings breadcrumbs: "Settings > Profile" pattern - Calendar: remove duplicate New Post button from day view - Remove size="sm" from Schedule/Publish buttons - Remove bg-background from header (inherits from SidebarInset) - Add Cancel button to labels and hashtags create/edit dialogs - Add common.cancel i18n key - Clean up orphaned Calendar breadcrumbs - Fix SocialAccountsGrid buttons to use shadcn Button ghost All 753 tests passing.
2026-03-30 21:18:17 +00:00
use App\Models\NotificationPreference;
use App\Models\Plan;
use App\Models\Post;
use App\Models\PostComment;
use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\Subscription;
use App\Models\SubscriptionItem;
use App\Models\User;
use App\Models\Workspace;
use App\Models\WorkspaceInvite;
use App\Models\WorkspaceLabel;
use App\Models\WorkspaceSignature;
use App\Services\PostHogService;
use App\Services\PostTemplate\Registry as PostTemplateRegistry;
use App\Socialite\DiscordProvider;
use App\Socialite\InstagramProvider;
2026-01-15 17:24:39 +00:00
use App\Socialite\LinkedInPageExtendSocialite;
2026-01-15 01:13:44 +00:00
use Carbon\CarbonImmutable;
use Illuminate\Auth\Notifications\ResetPassword;
use Illuminate\Auth\Notifications\VerifyEmail;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Notifications\Messages\MailMessage;
2026-01-15 01:13:44 +00:00
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\RateLimiter;
2026-01-15 01:13:44 +00:00
use Illuminate\Support\ServiceProvider;
use Illuminate\Validation\Rules\Password;
use Laravel\Cashier\Cashier;
use Laravel\Cashier\Events\WebhookReceived;
use Laravel\Nightwatch\Facades\Nightwatch;
use Laravel\Nightwatch\Records\CacheEvent;
use Laravel\Passport\Passport;
use Laravel\Socialite\Facades\Socialite;
2026-03-31 00:18:07 +00:00
use Laravel\Socialite\Two\GoogleProvider;
use PostHog\PostHog;
use SocialiteProviders\Facebook\FacebookExtendSocialite;
2026-01-15 01:13:44 +00:00
use SocialiteProviders\LinkedIn\LinkedInExtendSocialite;
use SocialiteProviders\Manager\SocialiteWasCalled;
use SocialiteProviders\Pinterest\PinterestExtendSocialite;
2026-01-15 01:13:44 +00:00
use SocialiteProviders\TikTok\TikTokExtendSocialite;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
$this->app->singleton(PostTemplateRegistry::class);
if ($this->app->environment('local') && class_exists(\Laravel\Telescope\TelescopeServiceProvider::class)) {
$this->app->register(\Laravel\Telescope\TelescopeServiceProvider::class);
$this->app->register(TelescopeServiceProvider::class);
}
2026-01-15 01:13:44 +00:00
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
$this->configureDefaults();
$this->configureMorphMap();
2026-03-31 00:18:07 +00:00
$this->configurePostHog();
$this->configureRateLimiting();
2026-01-15 01:13:44 +00:00
$this->configureSocialite();
$this->configureStripeWebhooks();
Cashier::useCustomerModel(Account::class);
Cashier::useSubscriptionModel(Subscription::class);
Cashier::useSubscriptionItemModel(SubscriptionItem::class);
Cashier::keepPastDueSubscriptionsActive();
$this->configurePassport();
}
protected function configurePassport(): void
{
Passport::useTokenModel(AccessToken::class);
MCP: workspace settings, viewer read access, and token access (#241) * Add workspace MCP settings and token access controls. Ship MCP settings UI, OAuth revoke/list helpers, Passport deploy wiring, and workspace.token:mcp gating so assistants can connect without pulling in welcome/onboarding from the parent epic. Co-authored-by: Cursor <cursoragent@cursor.com> * Type MCP client config shapes instead of string checks. Encode http/config-root on each advanced client and tighten primary client ids so snippet generation does not branch on magic strings. Co-authored-by: Cursor <cursoragent@cursor.com> * Polish MCP settings follow-ups from review. Translate Ukrainian MCP copy, deep-link ChatGPT into connector creation, drop an unused asset and revoke arg, and assert PATs are rejected on the MCP endpoint. Co-authored-by: Cursor <cursoragent@cursor.com> * Harden MCP connected clients, revoke scope, and OAuth consent. List recoverable sessions with live refresh tokens, revoke only PATs, throttle registration alone, and block viewers from authorizing MCP. Co-authored-by: Cursor <cursoragent@cursor.com> * Simplify MCP OAuth route throttling to a single middleware group. Co-authored-by: Cursor <cursoragent@cursor.com> * Allow workspace viewers read-only MCP access with web policy writes. Mirror the web app: MCP connects on view + OAuth mcp:use, write tools enforce createPost/update/delete/manageAccounts/manageTeam, and demotion to Viewer keeps grants. Cover role denials, consent, and disconnect. Co-authored-by: Cursor <cursoragent@cursor.com> * Harden MCP tool authz with shared workspace helpers. Route ApiKey tools through AuthorizesMcpTool, fail closed on null user or policy argument, and resolve the current workspace before mutating. Co-authored-by: Cursor <cursoragent@cursor.com> * Drop redundant string casts on validated request data. Enum::from and validated() fields are already strings, so the casts add noise without changing behavior. Co-authored-by: Cursor <cursoragent@cursor.com> * Show only the current user's MCP connections in settings. Match API keys privacy: list and disconnect your own OAuth clients, not teammates' across the account. Co-authored-by: Cursor <cursoragent@cursor.com> * Cover LoadWorkspaceFromToken gaps and harden AuthorizesMcpTool tests. Co-authored-by: Cursor <cursoragent@cursor.com> * Drop redundant is_string guard before UpdatePostTool find. Co-authored-by: Cursor <cursoragent@cursor.com> * Refactor AppSidebar to always show MCP link and simplify route middleware definition in ai.php. The MCP link is now consistently displayed regardless of the current workspace state, and the route middleware syntax has been streamlined. * Refresh MCP connected clients with Inertia usePoll. Co-authored-by: Cursor <cursoragent@cursor.com> * Bump laravel/mcp to 0.9.1 and add the TryPost server icon. Requires laravel/boost 2.5 for the Icon attribute; expose images/trypost/icon.png on TryPostServer. Co-authored-by: Cursor <cursoragent@cursor.com> * Drop no-op ReflectionClass import in TryPostServerTest. Co-authored-by: Cursor <cursoragent@cursor.com> --------- Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-06 12:54:51 +00:00
// API keys may omit an application expiry ("never"). Passport still
// embeds a JWT `exp`, so keep that far ahead and enforce optional
// `oauth_access_tokens.expires_at` in LoadWorkspaceFromToken.
Passport::personalAccessTokensExpireIn(now()->addYears(100));
Passport::tokensCan([
'mcp:use' => 'Use MCP server',
]);
Passport::authorizationView('mcp.authorize');
}
protected function configureMorphMap(): void
{
Relation::enforceMorphMap([
'accessToken' => AccessToken::class,
'account' => Account::class,
'aiUsageLog' => AiUsageLog::class,
'automation' => Automation::class,
'automationNodeRun' => AutomationNodeRun::class,
'automationNodeState' => AutomationNodeState::class,
'automationRun' => AutomationRun::class,
'automationTriggerItem' => AutomationTriggerItem::class,
'invite' => Invite::class,
'media' => Media::class,
'notification' => Notification::class,
refactor: notification preferences, header slots, calendar layout, UI polish Notification preferences: - Create notification_preferences table (post_published, post_failed, account_disconnected booleans per user) - NotificationPreferenceController with firstOrCreate on first visit - SendNotification job respects email preferences before sending - Settings page with toggle switches, i18n in 3 languages - 8 new tests for preferences (controller + wantsEmailFor + job integration) Post published notification: - PostPublished mail + maizzle template - Notify owner on successful publish via SendNotification job - PostPublished type added to notification enum Header & Layout: - Rename AppSidebarHeader to AppHeader with left/center/right slots - showSidebarTrigger prop to hide sidebar toggle - Calendar: controls in header (left: nav, center: date, right: tabs + new post) - Fixed header with scrollable content (flex h-screen pattern) - fullWidth pages use overflow-y-auto (fixes month view scroll) UI improvements: - Action buttons moved to header-right: posts, hashtags, labels - Settings breadcrumbs: "Settings > Profile" pattern - Calendar: remove duplicate New Post button from day view - Remove size="sm" from Schedule/Publish buttons - Remove bg-background from header (inherits from SidebarInset) - Add Cancel button to labels and hashtags create/edit dialogs - Add common.cancel i18n key - Clean up orphaned Calendar breadcrumbs - Fix SocialAccountsGrid buttons to use shadcn Button ghost All 753 tests passing.
2026-03-30 21:18:17 +00:00
'notificationPreference' => NotificationPreference::class,
'plan' => Plan::class,
'post' => Post::class,
'postComment' => PostComment::class,
'postPlatform' => PostPlatform::class,
'socialAccount' => SocialAccount::class,
'subscription' => Subscription::class,
'subscriptionItem' => SubscriptionItem::class,
'user' => User::class,
'workspace' => Workspace::class,
'workspaceInvite' => WorkspaceInvite::class,
'workspaceLabel' => WorkspaceLabel::class,
'workspaceSignature' => WorkspaceSignature::class,
]);
}
2026-03-31 00:18:07 +00:00
protected function configurePostHog(): void
{
if (! PostHogService::isEnabled()) {
return;
2026-03-31 00:18:07 +00:00
}
PostHog::init(config('services.posthog.api_key'), [
'host' => config('services.posthog.host'),
]);
2026-03-31 00:18:07 +00:00
}
protected function configureRateLimiting(): void
{
RateLimiter::for('api', function (Request $request) {
if ($this->app->environment('local')) {
return Limit::none();
}
return Limit::perMinute(60)->by($request->workspace?->id ?: $request->ip());
});
MCP: workspace settings, viewer read access, and token access (#241) * Add workspace MCP settings and token access controls. Ship MCP settings UI, OAuth revoke/list helpers, Passport deploy wiring, and workspace.token:mcp gating so assistants can connect without pulling in welcome/onboarding from the parent epic. Co-authored-by: Cursor <cursoragent@cursor.com> * Type MCP client config shapes instead of string checks. Encode http/config-root on each advanced client and tighten primary client ids so snippet generation does not branch on magic strings. Co-authored-by: Cursor <cursoragent@cursor.com> * Polish MCP settings follow-ups from review. Translate Ukrainian MCP copy, deep-link ChatGPT into connector creation, drop an unused asset and revoke arg, and assert PATs are rejected on the MCP endpoint. Co-authored-by: Cursor <cursoragent@cursor.com> * Harden MCP connected clients, revoke scope, and OAuth consent. List recoverable sessions with live refresh tokens, revoke only PATs, throttle registration alone, and block viewers from authorizing MCP. Co-authored-by: Cursor <cursoragent@cursor.com> * Simplify MCP OAuth route throttling to a single middleware group. Co-authored-by: Cursor <cursoragent@cursor.com> * Allow workspace viewers read-only MCP access with web policy writes. Mirror the web app: MCP connects on view + OAuth mcp:use, write tools enforce createPost/update/delete/manageAccounts/manageTeam, and demotion to Viewer keeps grants. Cover role denials, consent, and disconnect. Co-authored-by: Cursor <cursoragent@cursor.com> * Harden MCP tool authz with shared workspace helpers. Route ApiKey tools through AuthorizesMcpTool, fail closed on null user or policy argument, and resolve the current workspace before mutating. Co-authored-by: Cursor <cursoragent@cursor.com> * Drop redundant string casts on validated request data. Enum::from and validated() fields are already strings, so the casts add noise without changing behavior. Co-authored-by: Cursor <cursoragent@cursor.com> * Show only the current user's MCP connections in settings. Match API keys privacy: list and disconnect your own OAuth clients, not teammates' across the account. Co-authored-by: Cursor <cursoragent@cursor.com> * Cover LoadWorkspaceFromToken gaps and harden AuthorizesMcpTool tests. Co-authored-by: Cursor <cursoragent@cursor.com> * Drop redundant is_string guard before UpdatePostTool find. Co-authored-by: Cursor <cursoragent@cursor.com> * Refactor AppSidebar to always show MCP link and simplify route middleware definition in ai.php. The MCP link is now consistently displayed regardless of the current workspace state, and the route middleware syntax has been streamlined. * Refresh MCP connected clients with Inertia usePoll. Co-authored-by: Cursor <cursoragent@cursor.com> * Bump laravel/mcp to 0.9.1 and add the TryPost server icon. Requires laravel/boost 2.5 for the Icon attribute; expose images/trypost/icon.png on TryPostServer. Co-authored-by: Cursor <cursoragent@cursor.com> * Drop no-op ReflectionClass import in TryPostServerTest. Co-authored-by: Cursor <cursoragent@cursor.com> --------- Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-06 12:54:51 +00:00
RateLimiter::for(
'mcp-oauth-registration',
fn (Request $request): Limit => Limit::perMinute(30)->by($request->ip()),
);
// Signed media uploads (api.uploads.store). MCP hosts share egress IPs
// across tenants — key by workspace_id from the signed URL, with a high
// IP backstop so one client cannot flood every workspace.
RateLimiter::for('signed-uploads', function (Request $request) {
$limits = [
Limit::perMinute((int) config('trypost.media.signed_upload_per_ip_per_minute'))
->by("ip:{$request->ip()}"),
];
$workspaceId = $request->query('workspace_id');
if (filled($workspaceId)) {
array_unshift(
$limits,
Limit::perMinute((int) config('trypost.media.signed_upload_per_workspace_per_minute'))
->by("workspace:{$workspaceId}"),
);
}
return $limits;
});
}
protected function configureStripeWebhooks(): void
{
Event::listen(WebhookReceived::class, StripeEventListener::class);
2026-01-15 01:13:44 +00:00
}
protected function configureSocialite(): void
{
2026-03-31 00:18:07 +00:00
// Google Auth (login/signup) - separate from YouTube OAuth
Socialite::extend('google-auth', function ($app) {
$config = $app['config']['services.google-auth'];
return Socialite::buildProvider(GoogleProvider::class, $config);
});
// Instagram Business Login
Socialite::extend('instagram', function ($app) {
$config = $app['config']['services.instagram'];
return Socialite::buildProvider(InstagramProvider::class, $config);
});
Socialite::extend('discord', function ($app) {
$config = $app['config']['services.discord'];
return Socialite::buildProvider(DiscordProvider::class, $config);
});
Event::listen(SocialiteWasCalled::class, FacebookExtendSocialite::class);
2026-01-15 01:13:44 +00:00
Event::listen(SocialiteWasCalled::class, LinkedInExtendSocialite::class);
Event::listen(SocialiteWasCalled::class, LinkedInPageExtendSocialite::class);
Event::listen(SocialiteWasCalled::class, PinterestExtendSocialite::class);
2026-01-15 01:13:44 +00:00
Event::listen(SocialiteWasCalled::class, TikTokExtendSocialite::class);
}
protected function configureDefaults(): void
{
Date::use(CarbonImmutable::class);
// Disable wrapping of JSON resources
JsonResource::withoutWrapping();
Model::shouldBeStrict(! $this->app->isProduction());
DB::prohibitDestructiveCommands(
app()->isProduction(),
);
2026-01-15 01:13:44 +00:00
Password::defaults(fn (): ?Password => app()->isProduction()
? Password::min(12)
->mixedCase()
->letters()
->numbers()
->symbols()
->uncompromised()
: null
);
Nightwatch::rejectCacheEvents(function (CacheEvent $cacheEvent) {
return in_array($cacheEvent->key, [
'illuminate:foundation:down',
'illuminate:queue:restart',
'illuminate:schedule:interrupt',
]);
});
// Custom email verification template
VerifyEmail::toMailUsing(function (User $user, string $url) {
return (new MailMessage)
->from(config('mail.from.address'), config('mail.from.name'))
->subject('Verify your email address')
->view('mail.email-verification', [
'title' => 'Verify your email address',
'previewText' => 'Please verify your email address.',
'user' => $user,
'url' => $url,
]);
});
// Custom password reset template
ResetPassword::toMailUsing(function (User $user, string $token) {
$url = url(route('password.reset', [
'token' => $token,
'email' => $user->getEmailForPasswordReset(),
], false));
return (new MailMessage)
->from(config('mail.from.address'), config('mail.from.name'))
->subject('Reset your password')
->view('mail.password-reset', [
'title' => 'Reset your password',
'previewText' => 'Reset your password.',
'user' => $user,
'url' => $url,
]);
});
2026-01-15 01:13:44 +00:00
}
}