77 Commits
Author SHA1 Message Date
Mark Gregory 976f161550 fix: preserve empty Laravel views directory for deployment 2026-10-20 10:57:19 +01:00
Mark Gregory 1424133b0a added theme support 2026-10-20 10:55:54 +01:00
Mark Gregory 835008e99d added theme support 2026-10-20 10:53:10 +01:00
Mark Gregory e926301c12 added theme support 2026-10-20 10:46:10 +01:00
Mark Gregory 1f17a98158 added theme support 2026-10-20 10:44:42 +01:00
Mark Gregory a0dc4787ab added theme support 2026-10-20 10:41:40 +01:00
Mark Gregory 8854604593 added theme support 2026-10-20 10:40:24 +01:00
Mark Gregory b159b2e16c added theme support 2026-10-20 10:38:03 +01:00
Mark Gregory c198374d49 added theme support 2026-10-20 10:37:13 +01:00
Mark Gregory 63582531e3 added theme support 2026-10-20 10:29:35 +01:00
Mark Gregory c5353d0351 added theme support 2026-10-20 10:27:30 +01:00
Mark Gregory f0e31aad6b added theme support 2026-10-20 10:23:23 +01:00
Mark Gregory 1d70a9c8cf added theme support 2026-10-20 10:22:21 +01:00
Mark Gregory 42c074d966 added theme support 2026-10-20 10:19:18 +01:00
Mark Gregory c5f6871e8d download fixes 2026-10-20 10:17:23 +01:00
Mark Gregory b02d4259c3 download fixes 2026-10-20 10:16:48 +01:00
Mark Gregory 3f54289a9d download fixes 2026-10-20 10:10:34 +01:00
Mark Gregory 5d0faef236 download fixes 2026-10-20 10:10:06 +01:00
Mark Gregory f8e1170d5f download fixes 2026-10-20 10:06:04 +01:00
Mark Gregory ec13e7339a download fixes 2026-10-20 09:59:26 +01:00
Mark Gregory bfa4a2312c download fixes 2026-10-20 09:57:43 +01:00
Mark Gregory 1dab26931a update 2026-10-20 09:49:44 +01:00
Mark Gregory 1409d19e3d download fixes 2026-10-12 10:56:55 +01:00
Mark Gregory f9123813fb download fixes 2026-10-12 10:54:23 +01:00
Mark Gregory 9c3353924b download fixes 2026-10-12 10:50:27 +01:00
Mark Gregory d415b42044 download fixes 2026-10-12 10:48:30 +01:00
Mark Gregory d94845b1f6 download fixes 2026-10-12 10:32:50 +01:00
Mark Gregory c6411075d9 download fixes 2026-10-12 10:25:48 +01:00
Mark Gregory ae7b36a4bf download fixes 2026-10-12 10:24:08 +01:00
Mark Gregory e7c9e839fb download fixes 2026-10-12 10:21:25 +01:00
Mark Gregory 259b1eac12 download fixes 2026-10-12 10:18:16 +01:00
Mark Gregory 9ae51ada72 download fixes 2026-10-12 10:09:00 +01:00
Mark Gregory 85f9e56b03 deployer fixes 2026-10-12 09:53:48 +01:00
Mark Gregory 2139e55137 deployer fixes 2026-10-07 11:42:30 +01:00
Mark Gregory d92e89ea2f Merge branch 'stage' 2026-10-06 15:17:26 +01:00
Mark Gregory b3ca947d7d SEO additions index now 2026-10-06 15:15:53 +01:00
Mark Gregory 1930fdc0e4 SEO additions 2026-10-06 01:43:15 +01:00
Mark Gregory 93f640b6bc Clean up account provisioner comment 2026-10-02 10:54:24 +01:00
Mark Gregory b9e5604128 Add failed jobs queue migration 2026-10-02 10:54:00 +01:00
Mark Gregory c99e97a621 SEO additions 2026-10-02 10:26:52 +01:00
Mark Gregory eaedf1c559 SEO additions 2026-10-02 10:21:54 +01:00
Mark Gregory cbb1f0c366 SEO additions 2026-10-02 09:58:22 +01:00
Mark Gregory 9a6687096a SEO additions 2026-10-02 09:39:45 +01:00
Mark Gregory fa6ffa5cd9 SEO additions 2026-10-01 14:20:44 +01:00
Mark Gregory 99ab7a7ee3 SEO additions 2026-10-01 12:08:23 +01:00
Mark Gregory 98ddc22bd7 SEO additions 2026-10-01 11:55:37 +01:00
Mark Gregory 23a9b1dbcf SEO additions 2026-10-01 11:25:05 +01:00
Mark Gregory 1986ff1c43 Merge branch 'develop' into stage 2026-10-01 11:16:09 +01:00
Mark Gregory a8eff45f49 SEO additions 2026-10-01 11:15:55 +01:00
Mark Gregory a94f294184 new terms of service and refunds 2026-10-01 11:08:19 +01:00
Mark Gregory ddd5949595 new terms of service and refunds 2026-10-01 11:05:35 +01:00
Mark Gregory 57967dd969 updates 2026-10-01 11:03:06 +01:00
Mark Gregory f1f8518da4 new terms of service and refunds 2026-10-01 10:57:39 +01:00
Mark Gregory 59bafece3c new terms of service and refunds 2026-10-01 08:15:19 +01:00
Mark Gregory a003b2e043 new terms of service and refunds 2026-10-01 08:12:19 +01:00
Mark Gregory 7ad68a415b new terms of service and refunds 2026-10-01 08:06:08 +01:00
Mark Gregory 0bcf23d45b new terms of service and refunds 2026-10-01 08:00:18 +01:00
Mark Gregory c357a35b77 update to provisioner code nwew paddle code 2026-09-30 17:35:08 +01:00
Mark Gregory f507981cbd update to provisioner code nwew paddle code 2026-09-30 17:29:45 +01:00
Mark Gregory ddfb19d9a9 Merge branch 'main' into develop 2026-09-30 17:03:14 +01:00
Mark Gregory 53c45f55ec update to provisioner code nwew paddle code 2026-09-30 16:58:59 +01:00
Mark Gregory cef2f15490 update to provisioner code nwew paddle code 2026-09-30 16:32:29 +01:00
Mark Gregory cf34134b69 update to provisioner code nwew paddle code 2026-09-30 16:19:43 +01:00
Mark Gregory 8c61803aba Merge branch 'main' into develop 2026-09-30 16:15:37 +01:00
Mark Gregory bae2622370 update to provisioner code nwew paddle code 2026-09-30 16:15:10 +01:00
Mark Gregory b390d584f1 Merge branch 'stage' into develop
# Conflicts:
#	app/Console/Commands/SonarDeskAccountsBackfill.php
2026-09-30 13:21:18 +01:00
Mark Gregory 527bb1b017 update to provisioner code nwew paddle code 2026-09-30 13:15:21 +01:00
Mark Gregory 0f051bb956 update to provisioner code 2026-09-30 13:05:20 +01:00
Mark Gregory 2dde56a2f6 update to provisioner code 2026-09-30 12:59:42 +01:00
Mark Gregory 58eec7da9a update to provisioner code 2026-09-30 12:55:32 +01:00
Mark Gregory 6850a00e76 update to provisioner code 2026-09-30 12:52:29 +01:00
Mark Gregory 2d9d07f722 update to provisioner code 2026-09-30 12:49:17 +01:00
Mark Gregory 20dbb09433 update to provisioner code 2026-09-30 12:40:29 +01:00
Mark Gregory 5b3413549d update to provisioner code 2026-09-30 12:38:04 +01:00
Mark Gregory 15b8d9b75b new stage code 2026-09-30 12:19:35 +01:00
Mark Gregory a32238e632 new stage code 2026-09-30 11:47:04 +01:00
Mark Gregory df61a1e789 updated deployer code 2026-09-30 11:44:14 +01:00
293 changed files with 10876 additions and 761 deletions
View File
+1
View File
@@ -25,3 +25,4 @@ _ide_helper.php
Homestead.json
Homestead.yaml
Thumbs.db
/.scannerwork/
-6
View File
@@ -1,6 +0,0 @@
projectKey=sonar_desk
serverUrl=https://sonarcube.absdev.net
serverVersion=26.9.0.129388
dashboardUrl=https://sonarcube.absdev.net/dashboard?id=sonar_desk
ceTaskId=ed0bb599-656b-42f0-a0ec-c838a1ab98b2
ceTaskUrl=https://sonarcube.absdev.net/api/ce/task?id=ed0bb599-656b-42f0-a0ec-c838a1ab98b2
@@ -0,0 +1,59 @@
<?php
namespace App\Console\Commands;
use Modules\Licensing\Models\License;
use App\Models\User;
use App\Services\Accounts\PurchasedAccountProvisioner;
use Illuminate\Console\Command;
final class SonarDeskAccountsBackfill extends Command
{
protected $signature = 'sonardesk:accounts:backfill {--dry-run : Report missing customer accounts without creating them} {--no-email : Create accounts without sending password setup links}';
protected $description = 'Create portal accounts for existing licence holders that do not already have one.';
public function handle(PurchasedAccountProvisioner $accounts): int
{
$customers = License::query()
->whereNotNull('customer_email')
->where('customer_email', '<>', '')
->select(['customer_email', 'customer_name'])
->orderBy('customer_email')
->get()
->unique(fn (License $license) => strtolower(trim((string) $license->customer_email)));
$missing = 0;
$created = 0;
foreach ($customers as $license) {
$email = strtolower(trim((string) $license->customer_email));
if ($email === '') {
continue;
}
if (User::query()->whereRaw('lower(email) = ?', [$email])->exists()) {
continue;
}
$missing++;
if ($this->option('dry-run')) {
$this->line("MISSING {$email}");
continue;
}
if ($accounts->ensure($email, $license->customer_name, ! $this->option('no-email'))) {
$created++;
$this->info("CREATED {$email}");
}
}
if ($this->option('dry-run')) {
$this->info("{$missing} account(s) would be created.");
} else {
$this->info("{$created} account(s) created.");
}
return self::SUCCESS;
}
}
+59
View File
@@ -0,0 +1,59 @@
<?php
namespace App\Console\Commands;
use App\Models\CmsPage;
use App\Services\IndexNowService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Route;
use Throwable;
final class SubmitIndexNow extends Command
{
protected $signature = 'indexnow:submit {urls?* : Absolute URLs to submit} {--all : Submit all public indexable SonarDesk URLs}';
protected $description = 'Submit public SonarDesk URLs to IndexNow';
public function handle(IndexNowService $indexNow): int
{
if (! config('indexnow.enabled')) {
$this->warn('IndexNow is disabled. Set INDEXNOW_ENABLED=true to enable submissions.');
return self::FAILURE;
}
$urls = $this->argument('urls');
if ($this->option('all') || $urls === []) {
$urls = $this->allPublicUrls();
}
try {
$response = $indexNow->submit($urls);
} catch (Throwable $e) {
$this->error($e->getMessage());
return self::FAILURE;
}
if ($response === null || ! $response->successful()) {
$this->error('IndexNow rejected the submission'.($response ? ' (HTTP '.$response->status().').' : '.'));
return self::FAILURE;
}
$this->info('Submitted '.count($urls).' URL(s) to IndexNow (HTTP '.$response->status().').');
return self::SUCCESS;
}
/** @return array<int, string> */
private function allPublicUrls(): array
{
$routes = ['home', 'features', 'buy', 'release', 'support', 'privacy', 'terms', 'refund', 'cookies'];
$urls = collect($routes)->filter(fn (string $name) => Route::has($name))->map(fn (string $name) => route($name));
$pages = CmsPage::query()
->where('is_published', true)
->where('robots_index', true)
->where(fn ($query) => $query->whereNull('published_at')->orWhere('published_at', '<=', now()))
->pluck('slug')
->map(fn (string $slug) => route('cms.show', ['slug' => $slug]));
return $urls->merge($pages)->unique()->values()->all();
}
}
@@ -3,8 +3,8 @@
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\License;
use App\Models\LicenseActivation;
use Modules\Licensing\Models\License;
use Modules\Licensing\Models\LicenseActivation;
use App\Models\User;
use Illuminate\Http\Request;
@@ -4,6 +4,7 @@ namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\CmsPage;
use App\Services\IndexNowService;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
@@ -12,11 +13,24 @@ final class CmsPageController extends Controller
{
public function index() { return view('admin.cms.index', ['pages' => CmsPage::latest()->paginate(25)]); }
public function create() { return view('admin.cms.form', ['page' => new CmsPage()]); }
public function store(Request $request) { $page = CmsPage::create($this->validated($request)); return redirect()->route('admin.cms.edit', $page)->with('status', 'Page created.'); }
public function store(Request $request, IndexNowService $indexNow) { $page = CmsPage::create($this->validated($request)); $this->submitIfIndexable($page, $indexNow); return redirect()->route('admin.cms.edit', $page)->with('status', 'Page created.'); }
public function edit(CmsPage $page) { return view('admin.cms.form', compact('page')); }
public function update(Request $request, CmsPage $page) { $page->update($this->validated($request, $page)); return back()->with('status', 'Page updated.'); }
public function update(Request $request, CmsPage $page, IndexNowService $indexNow) { $page->update($this->validated($request, $page)); $this->submitIfIndexable($page, $indexNow); return back()->with('status', 'Page updated.'); }
public function destroy(CmsPage $page) { $page->delete(); return redirect()->route('admin.cms.index')->with('status', 'Page deleted.'); }
private function submitIfIndexable(CmsPage $page, IndexNowService $indexNow): void
{
if (! $page->is_published || ! $page->robots_index || ($page->published_at && $page->published_at->isFuture())) {
return;
}
try {
$indexNow->submit([route('cms.show', ['slug' => $page->slug])]);
} catch (\Throwable $e) {
report($e);
}
}
private function validated(Request $request, ?CmsPage $page = null): array
{
$request->merge(['slug' => Str::slug($request->input('slug') ?: $request->input('title', ''))]);
@@ -27,7 +41,17 @@ final class CmsPageController extends Controller
'body' => ['required','string'],
'meta_title' => ['nullable','string','max:160'],
'meta_description' => ['nullable','string','max:320'],
'meta_keywords' => ['nullable','string','max:500'],
'canonical_url' => ['nullable','url:http,https','max:2048'],
'og_title' => ['nullable','string','max:160'],
'og_description' => ['nullable','string','max:320'],
'og_image' => ['nullable','url:http,https','max:2048'],
'sitemap_priority' => ['required','numeric','min:0','max:1'],
'sitemap_change_frequency' => ['required', Rule::in(['always','hourly','daily','weekly','monthly','yearly','never'])],
]);
$data['robots_index'] = $request->boolean('robots_index');
$data['robots_follow'] = $request->boolean('robots_follow');
$data['include_in_sitemap'] = $request->boolean('include_in_sitemap');
$data['is_published'] = $request->boolean('is_published');
$data['published_at'] = $data['is_published'] ? ($page?->published_at ?? now()) : null;
return $data;
@@ -0,0 +1,30 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\DownloadProduct;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
final class DownloadProductController extends Controller {
public function index() { return view('admin.download-products.index', ['products'=>DownloadProduct::latest()->get()]); }
public function store(Request $request) {
$data=$request->validate(['name'=>'required|string|max:150','description'=>'nullable|string|max:12000','version'=>'nullable|string|max:80','platform'=>'nullable|string|max:120','package'=>'required|file|max:1048576','is_published'=>'sometimes|boolean']);
$file=$request->file('package');
$path=$file->store('download-products','local');
DownloadProduct::create(['name'=>$data['name'],'description'=>$data['description']??null,'version'=>$data['version']??null,'platform'=>$data['platform']??null,'file_path'=>$path,'original_filename'=>$file->getClientOriginalName(),'file_size'=>$file->getSize(),'is_published'=>$request->boolean('is_published')]);
return back()->with('status','Product added.');
}
public function update(Request $request, DownloadProduct $product) {
$data=$request->validate(['name'=>'required|string|max:150','description'=>'nullable|string|max:12000','version'=>'nullable|string|max:80','platform'=>'nullable|string|max:120','package'=>'nullable|file|max:1048576','is_published'=>'sometimes|boolean']);
$changes=['name'=>$data['name'],'description'=>$data['description']??null,'version'=>$data['version']??null,'platform'=>$data['platform']??null,'is_published'=>$request->boolean('is_published')];
if ($request->hasFile('package')) { $file=$request->file('package'); $path=$file->store('download-products','local'); $old=$product->file_path; $changes+=['file_path'=>$path,'original_filename'=>$file->getClientOriginalName(),'file_size'=>$file->getSize()]; $product->update($changes); if($old) Storage::disk('local')->delete($old); }
else $product->update($changes);
return back()->with('status','Product updated.');
}
public function publication(Request $request, DownloadProduct $product) {
$data = $request->validate(['is_published' => 'required|boolean']);
$product->update(['is_published' => (bool) $data['is_published']]);
return back()->with('status', $product->is_published ? 'Product published.' : 'Product unpublished.');
}
public function destroy(DownloadProduct $product) { if($product->file_path) Storage::disk('local')->delete($product->file_path); $product->delete(); return back()->with('status','Product deleted.'); }
}
@@ -0,0 +1,101 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\SiteSetting;
use App\Models\SonarDeskRelease;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;
final class ReleaseController extends Controller
{
public function index()
{
return view('admin.releases.index', [
'releases' => SonarDeskRelease::latest()->paginate(30),
'publishedCount' => SonarDeskRelease::where('is_published', true)->count(),
'downloadCount' => SonarDeskRelease::sum('download_count'),
]);
}
public function create() { return view('admin.releases.form', ['release' => new SonarDeskRelease]); }
public function edit(SonarDeskRelease $release) { return view('admin.releases.form', compact('release')); }
public function store(Request $request): RedirectResponse
{
$release = new SonarDeskRelease;
$this->persist($request, $release);
return redirect()->route('admin.releases.index')->with('status', 'Release created.');
}
public function update(Request $request, SonarDeskRelease $release): RedirectResponse
{
$this->persist($request, $release);
return redirect()->route('admin.releases.index')->with('status', 'Release updated.');
}
public function destroy(SonarDeskRelease $release): RedirectResponse
{
if ($release->file_path) Storage::disk('local')->delete($release->file_path);
$release->delete();
return back()->with('status', 'Release deleted.');
}
public function settings()
{
$keys = ['downloads.eyebrow','downloads.title','downloads.intro','downloads.requirements','downloads.support_text'];
$settings = collect($keys)->mapWithKeys(fn ($key) => [$key => SiteSetting::valueFor($key)]);
return view('admin.releases.settings', compact('settings'));
}
public function updateSettings(Request $request): RedirectResponse
{
$data = $request->validate([
'eyebrow' => ['required','string','max:80'], 'title' => ['required','string','max:120'],
'intro' => ['required','string','max:500'], 'requirements' => ['required','string','max:500'],
'support_text' => ['required','string','max:500'],
]);
foreach ($data as $key => $value) SiteSetting::put('downloads.'.$key, $value);
return back()->with('status', 'Download page content updated.');
}
private function persist(Request $request, SonarDeskRelease $release): void
{
$data = $request->validate([
'version' => ['required','string','max:40'], 'build_number' => ['required','integer','min:1'],
'channel' => ['required', Rule::in(['stable','beta'])], 'minimum_macos' => ['nullable','string','max:30'],
'release_notes' => ['nullable','string','max:20000'], 'sparkle_signature' => ['nullable','string','max:2000'],
'package' => [
$release->exists ? 'nullable' : 'required',
'file',
'max:1048576',
function (string $attribute, $value, \Closure $fail): void {
$extension = strtolower($value->getClientOriginalExtension());
if (! in_array($extension, ['dmg', 'zip'], true)) {
$fail('The package must be a DMG or ZIP file.');
}
},
],
'is_published' => ['nullable','boolean'], 'is_featured' => ['nullable','boolean'],
]);
$data['is_published'] = $request->boolean('is_published');
$data['is_featured'] = $request->boolean('is_featured');
if ($data['is_featured']) SonarDeskRelease::query()->update(['is_featured' => false]);
if ($request->hasFile('package')) {
if ($release->file_path) Storage::disk('local')->delete($release->file_path);
$file = $request->file('package');
$path = $file->store('sonardesk/releases', 'local');
$data['file_path'] = $path;
$data['original_filename'] = $file->getClientOriginalName();
$data['file_size'] = $file->getSize();
$data['sha256'] = hash_file('sha256', $file->getRealPath());
}
unset($data['package']);
$data['published_at'] = $data['is_published'] ? ($release->published_at ?: now()) : null;
$release->fill($data)->save();
}
}
@@ -0,0 +1,50 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\SiteSetting;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
final class SeoSettingsController extends Controller
{
private const KEYS = [
'seo_site_name', 'seo_title_suffix', 'seo_default_title', 'seo_default_description',
'seo_default_keywords', 'seo_canonical_base_url', 'seo_default_og_image', 'seo_twitter_site',
'seo_organization_name', 'seo_organization_logo', 'seo_google_site_verification',
];
public function edit(): View
{
return view('admin.seo.edit', [
'settings' => collect(self::KEYS)->mapWithKeys(fn (string $key) => [$key => SiteSetting::valueFor($key, '')]),
'robotsEnabled' => SiteSetting::booleanFor('seo_robots_enabled', true),
]);
}
public function update(Request $request): RedirectResponse
{
$data = $request->validate([
'seo_site_name' => ['required', 'string', 'max:80'],
'seo_title_suffix' => ['nullable', 'string', 'max:80'],
'seo_default_title' => ['required', 'string', 'max:160'],
'seo_default_description' => ['required', 'string', 'max:320'],
'seo_default_keywords' => ['nullable', 'string', 'max:500'],
'seo_canonical_base_url' => ['nullable', 'url:http,https', 'max:2048'],
'seo_default_og_image' => ['nullable', 'url:http,https', 'max:2048'],
'seo_twitter_site' => ['nullable', 'string', 'max:40', 'regex:/^@?[A-Za-z0-9_]{1,15}$/'],
'seo_organization_name' => ['nullable', 'string', 'max:120'],
'seo_organization_logo' => ['nullable', 'url:http,https', 'max:2048'],
'seo_google_site_verification' => ['nullable', 'string', 'max:255'],
]);
foreach (self::KEYS as $key) {
SiteSetting::put($key, isset($data[$key]) ? trim((string) $data[$key]) : null);
}
SiteSetting::put('seo_robots_enabled', $request->boolean('seo_robots_enabled') ? '1' : '0');
return back()->with('status', 'SEO settings updated.');
}
}
@@ -0,0 +1,156 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Modules\Licensing\Models\License;
use Modules\Licensing\Models\LicenseActivation;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Password;
use Illuminate\Validation\Rule;
final class UserController extends Controller
{
public function index(Request $request)
{
$query = User::query()->latest();
if ($search = trim((string) $request->query('q'))) {
$query->where(fn ($q) => $q
->where('name', 'like', "%{$search}%")
->orWhere('email', 'like', "%{$search}%"));
}
if ($request->query('status') === 'admin') {
$query->where('is_admin', true);
} elseif ($request->query('status') === 'suspended') {
$query->whereNotNull('disabled_at');
} elseif ($request->query('status') === 'unverified') {
$query->whereNull('email_verified_at');
}
$users = $query->paginate(50)->withQueryString();
$emails = $users->getCollection()->pluck('email')->map(fn ($email) => strtolower($email))->all();
$licenseCounts = License::query()
->selectRaw('LOWER(customer_email) as email_key, COUNT(*) as aggregate')
->whereIn(DB::raw('LOWER(customer_email)'), $emails)
->groupBy(DB::raw('LOWER(customer_email)'))
->pluck('aggregate', 'email_key');
return view('admin.users.index', compact('users', 'licenseCounts'));
}
public function show(User $user)
{
$licenses = License::with(['product', 'activations'])
->whereRaw('LOWER(customer_email) = ?', [strtolower($user->email)])
->latest()
->get();
return view('admin.users.show', compact('user', 'licenses'));
}
public function update(Request $request, User $user)
{
$data = $request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'email', 'max:255', Rule::unique('users', 'email')->ignore($user->id)],
'is_admin' => ['nullable', 'boolean'],
]);
$oldEmail = strtolower($user->email);
$newEmail = strtolower(trim($data['email']));
$isSelf = $request->user()->is($user);
DB::transaction(function () use ($user, $data, $oldEmail, $newEmail, $isSelf): void {
$user->name = trim($data['name']);
$user->email = $newEmail;
if (! $isSelf) {
$user->is_admin = (bool) ($data['is_admin'] ?? false);
}
$user->save();
if ($oldEmail !== $newEmail) {
License::whereRaw('LOWER(customer_email) = ?', [$oldEmail])
->update(['customer_email' => $newEmail]);
}
});
return redirect()->route('admin.users.show', $user)->with('status', 'User updated.');
}
public function verify(User $user)
{
if (! $user->hasVerifiedEmail()) {
$user->markEmailAsVerified();
}
return back()->with('status', 'Email marked as verified.');
}
public function resendVerification(User $user)
{
if (! $user->hasVerifiedEmail()) {
$user->sendEmailVerificationNotification();
}
return back()->with('status', 'Verification email sent.');
}
public function sendPasswordReset(User $user)
{
$status = Password::sendResetLink(['email' => $user->email]);
return $status === Password::RESET_LINK_SENT
? back()->with('status', 'Password reset link sent.')
: back()->withErrors(['email' => __($status)]);
}
public function suspend(Request $request, User $user)
{
abort_if($request->user()->is($user), 422, 'You cannot suspend your own administrator account.');
$user->forceFill(['disabled_at' => now(), 'remember_token' => null])->save();
return back()->with('status', 'User suspended.');
}
public function restore(User $user)
{
$user->forceFill(['disabled_at' => null])->save();
return back()->with('status', 'User restored.');
}
public function destroy(Request $request, User $user)
{
abort_if($request->user()->is($user), 422, 'You cannot delete your own administrator account.');
$user->delete();
return redirect()->route('admin.users.index')->with('status', 'User deleted. Licences were retained.');
}
public function updateLicense(Request $request, User $user, License $license)
{
$this->ensureOwnsLicense($user, $license);
$data = $request->validate(['activation_limit' => ['required', 'integer', 'min:1', 'max:1000']]);
$license->update(['activation_limit' => $data['activation_limit']]);
return back()->with('status', 'Activation limit updated.');
}
public function deactivate(User $user, License $license, LicenseActivation $activation)
{
$this->ensureOwnsLicense($user, $license);
abort_unless((string) $activation->license_id === (string) $license->id, 404);
$activation->update(['deactivated_at' => now()]);
return back()->with('status', 'Device activation released.');
}
private function ensureOwnsLicense(User $user, License $license): void
{
abort_unless(strtolower((string) $license->customer_email) === strtolower($user->email), 404);
}
}
@@ -1,78 +0,0 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\LicenseWebhookEvent;
use App\Services\Licensing\LicenseDeliveryService;
use App\Services\Payments\LemonSqueezyWebhookVerifier;
use App\Services\Payments\PaddleWebhookVerifier;
use App\Services\Payments\PurchaseProvisioner;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
final class PaymentWebhookController extends Controller
{
public function __invoke(string $provider, Request $request, PurchaseProvisioner $provisioner, LicenseDeliveryService $delivery): JsonResponse
{
$raw = (string) $request->getContent();
$verifier = match ($provider) {
'paddle' => app(PaddleWebhookVerifier::class),'lemon-squeezy' => app(LemonSqueezyWebhookVerifier::class),default => null
};
if (! $verifier) {
return response()->json(['message' => 'Unknown webhook provider.'], 404);
}
try {
$verifier->verify($request, $raw);
} catch (\Throwable $e) {
report($e);
return response()->json(['message' => 'Invalid webhook signature.'], 400);
}
try {
$payload = json_decode($raw, true, flags: JSON_THROW_ON_ERROR);
} catch (\Throwable) {
return response()->json(['message' => 'Invalid JSON.'], 400);
}
$externalID = (string) ($provider === 'paddle' ? ($payload['event_id'] ?? '') : ($payload['meta']['event_name'] ?? '').':'.($payload['data']['id'] ?? ''));
$eventType = (string) ($provider === 'paddle' ? ($payload['event_type'] ?? 'unknown') : ($payload['meta']['event_name'] ?? 'unknown'));
if ($externalID === '') {
return response()->json(['message' => 'Webhook event has no stable identifier.'], 400);
}
try {
DB::transaction(function () use ($provider, $externalID, $eventType, $payload, $raw, $provisioner) {
$event = LicenseWebhookEvent::firstOrCreate(['provider' => $provider, 'external_event_id' => $externalID], ['event_type' => $eventType, 'payload_sha256' => hash('sha256', $raw), 'payload' => $payload]);
if ($event->processed_at) {
return;
}
if (! hash_equals($event->payload_sha256, hash('sha256', $raw))) {
throw new \RuntimeException('Webhook ID was reused with a different payload.');
}
try {
$provisioner->provision($provider, $payload);
$event->update(['processed_at' => now(), 'processing_error' => null]);
} catch (\Throwable $e) {
$event->update(['processing_error' => mb_substr($e->getMessage(), 0, 4000)]);
throw $e;
}
});
} catch (\Throwable $e) {
report($e);
return response()->json(['message' => 'Webhook could not be processed.'], 500);
}
// Delivery is intentionally outside the webhook transaction. A temporary mail
// outage must not roll back an otherwise valid Paddle event. Pending outbox
// rows remain available for portal resend or a later webhook delivery attempt.
try {
$delivery->deliverPending(10);
} catch (\Throwable $e) {
report($e);
}
return response()->json(['ok' => true]);
}
}
@@ -16,7 +16,7 @@ final class AuthenticatedSessionController extends Controller
public function store(Request $request)
{
$credentials = $request->validate(['email' => ['required', 'email'], 'password' => ['required', 'string']]);
if (! Auth::attempt(['email' => strtolower($credentials['email']), 'password' => $credentials['password']], $request->boolean('remember'))) {
if (! Auth::attempt(['email' => strtolower($credentials['email']), 'password' => $credentials['password'], 'disabled_at' => null], $request->boolean('remember'))) {
return back()->withErrors(['email' => 'The supplied credentials are invalid.'])->onlyInput('email');
}
$request->session()->regenerate();
@@ -0,0 +1,85 @@
<?php
namespace App\Http\Controllers;
use App\Models\SiteSetting;
use App\Models\DownloadProduct;
use App\Models\SonarDeskRelease;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
final class ReleaseController extends Controller
{
public function index()
{
$latest = SonarDeskRelease::published()->where('is_featured', true)->orderByDesc('published_at')->first()
?? SonarDeskRelease::published()->where('channel', 'stable')->orderByDesc('published_at')->orderByDesc('id')->first();
$releases = SonarDeskRelease::published()
->when($latest, fn ($query) => $query->whereKeyNot($latest->getKey()))
->orderByDesc('published_at')->paginate(12);
$settings = $this->settings();
$products = DownloadProduct::where('is_published', true)->whereNotNull('file_path')
->when($latest, fn ($query) => $query->whereRaw('LOWER(name) <> ?', ['sonardesk']))
->orderBy('name')->get();
return view('downloads.index', compact('latest', 'releases', 'settings', 'products'));
}
public function sonarDeskDetails()
{
$latest = SonarDeskRelease::published()->where('is_featured', true)->orderByDesc('published_at')->first()
?? SonarDeskRelease::published()->where('channel', 'stable')->orderByDesc('published_at')->orderByDesc('id')->firstOrFail();
$settings = $this->settings();
return view('downloads.sonardesk', compact('latest', 'settings'));
}
public function latest(): BinaryFileResponse
{
$release = SonarDeskRelease::published()->where('channel', 'stable')->orderByDesc('published_at')->firstOrFail();
return $this->send($release);
}
public function download(SonarDeskRelease $release): BinaryFileResponse
{
abort_unless($release->is_published && $release->published_at && $release->file_path, 404);
return $this->send($release);
}
public function productDetails(DownloadProduct $product)
{
abort_unless($product->is_published && $product->file_path, 404);
return view('downloads.product', compact('product'));
}
public function productDownload(DownloadProduct $product): BinaryFileResponse
{
abort_unless($product->is_published && $product->file_path && Storage::disk('local')->exists($product->file_path), 404);
$product->increment('download_count');
return response()->download(Storage::disk('local')->path($product->file_path), $product->original_filename);
}
public function appcast(): Response
{
$releases = SonarDeskRelease::published()->where('channel', 'stable')->orderByDesc('published_at')->limit(20)->get();
return response()->view('downloads.appcast', compact('releases'), 200, ['Content-Type' => 'application/rss+xml; charset=UTF-8']);
}
private function send(SonarDeskRelease $release): BinaryFileResponse
{
abort_unless(Storage::disk('local')->exists($release->file_path), 404);
$release->increment('download_count');
return response()->download(Storage::disk('local')->path($release->file_path), $release->original_filename ?: 'SonarDesk-'.$release->version.'.dmg');
}
private function settings(): array
{
return [
'eyebrow' => SiteSetting::valueFor('downloads.eyebrow', 'SonarDesk for macOS'),
'title' => SiteSetting::valueFor('downloads.title', 'Download SonarDesk'),
'intro' => SiteSetting::valueFor('downloads.intro', 'A focused native SonarQube workspace, designed for macOS and built for daily engineering work.'),
'requirements' => SiteSetting::valueFor('downloads.requirements', 'Apple silicon and Intel Macs supported. A SonarQube server and valid SonarDesk licence are required.'),
'support_text' => SiteSetting::valueFor('downloads.support_text', 'Need help installing or activating SonarDesk? Our support team can help.'),
];
}
}
+65
View File
@@ -0,0 +1,65 @@
<?php
namespace App\Http\Controllers;
use App\Models\CmsPage;
use App\Models\SiteSetting;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Route;
final class SeoController extends Controller
{
public function sitemap(): Response
{
$static = collect([
['route' => 'home', 'priority' => '1.0', 'frequency' => 'weekly'],
['route' => 'features', 'priority' => '0.9', 'frequency' => 'monthly'],
['route' => 'buy', 'priority' => '0.9', 'frequency' => 'monthly'],
['route' => 'release', 'priority' => '0.8', 'frequency' => 'weekly'],
['route' => 'support', 'priority' => '0.6', 'frequency' => 'monthly'],
['route' => 'privacy', 'priority' => '0.3', 'frequency' => 'yearly'],
['route' => 'terms', 'priority' => '0.3', 'frequency' => 'yearly'],
['route' => 'refund', 'priority' => '0.3', 'frequency' => 'yearly'],
['route' => 'cookies', 'priority' => '0.3', 'frequency' => 'yearly'],
])->filter(fn (array $item) => Route::has($item['route']))->values();
$pages = CmsPage::query()
->where('is_published', true)
->where('include_in_sitemap', true)
->where('robots_index', true)
->where(fn ($query) => $query->whereNull('published_at')->orWhere('published_at', '<=', now()))
->orderBy('slug')
->get();
return response()
->view('seo.sitemap', compact('static', 'pages'))
->header('Content-Type', 'application/xml; charset=UTF-8')
->header('Cache-Control', 'public, max-age=3600');
}
public function indexNowKey(string $key): Response
{
$configured = trim((string) config('indexnow.key'));
abort_unless(config('indexnow.enabled') && $configured !== '' && hash_equals($configured, $key), 404);
return response($configured, 200, [
'Content-Type' => 'text/plain; charset=UTF-8',
'Cache-Control' => 'public, max-age=86400',
]);
}
public function robots(): Response
{
$indexable = app()->environment('production') && SiteSetting::booleanFor('seo_robots_enabled', true);
$body = $indexable
? "User-agent: *\nAllow: /\nDisallow: /admin/\nDisallow: /portal/\nDisallow: /login\nDisallow: /register\n\nSitemap: ".route('sitemap')."\n"
: "User-agent: *\nDisallow: /\n";
return response($body, 200, [
'Content-Type' => 'text/plain; charset=UTF-8',
'Cache-Control' => 'public, max-age=3600',
]);
}
}
+9 -2
View File
@@ -6,10 +6,17 @@ use Illuminate\Database\Eloquent\Model;
final class CmsPage extends Model
{
protected $fillable = ['title', 'slug', 'excerpt', 'body', 'meta_title', 'meta_description', 'is_published', 'published_at'];
protected $fillable = [
'title', 'slug', 'excerpt', 'body', 'meta_title', 'meta_description', 'meta_keywords',
'canonical_url', 'og_title', 'og_description', 'og_image', 'robots_index', 'robots_follow',
'include_in_sitemap', 'sitemap_priority', 'sitemap_change_frequency', 'is_published', 'published_at',
];
protected function casts(): array
{
return ['is_published' => 'boolean', 'published_at' => 'datetime'];
return [
'is_published' => 'boolean', 'published_at' => 'datetime', 'robots_index' => 'boolean',
'robots_follow' => 'boolean', 'include_in_sitemap' => 'boolean', 'sitemap_priority' => 'decimal:1',
];
}
}
+8
View File
@@ -0,0 +1,8 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
final class DownloadProduct extends Model {
protected $fillable = ['name','description','version','platform','file_path','original_filename','file_size','download_count','is_published'];
protected function casts(): array { return ['is_published'=>'boolean','file_size'=>'integer','download_count'=>'integer']; }
public function getFormattedSizeAttribute(): string { return $this->file_size >= 1048576 ? number_format($this->file_size/1048576,1).' MB' : number_format($this->file_size/1024,1).' KB'; }
}
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
final class SiteSetting extends Model
{
protected $table = 'sonardesk_site_settings';
protected $primaryKey = 'key';
public $incrementing = false;
protected $keyType = 'string';
protected $fillable = ['key', 'value'];
public static function valueFor(string $key, ?string $default = null): ?string
{
return Cache::remember('sonardesk.setting.'.$key, 300, fn () => static::query()->find($key)?->value ?? $default);
}
public static function booleanFor(string $key, bool $default = false): bool
{
$value = static::valueFor($key);
return $value === null ? $default : filter_var($value, FILTER_VALIDATE_BOOLEAN);
}
public static function put(string $key, ?string $value): void
{
static::query()->updateOrCreate(['key' => $key], ['value' => $value]);
Cache::forget('sonardesk.setting.'.$key);
}
}
+40
View File
@@ -0,0 +1,40 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
final class SonarDeskRelease extends Model
{
protected $table = 'sonardesk_releases';
protected $fillable = [
'version', 'build_number', 'channel', 'minimum_macos', 'file_path',
'original_filename', 'file_size', 'sha256', 'sparkle_signature',
'release_notes', 'is_published', 'is_featured', 'published_at', 'download_count',
];
protected function casts(): array
{
return [
'is_published' => 'boolean',
'is_featured' => 'boolean',
'published_at' => 'datetime',
'file_size' => 'integer',
'download_count' => 'integer',
];
}
public function scopePublished($query)
{
return $query->where('is_published', true)->whereNotNull('file_path')->whereNotNull('published_at');
}
public function getFormattedSizeAttribute(): string
{
$bytes = (int) $this->file_size;
if ($bytes < 1024) return $bytes.' B';
if ($bytes < 1048576) return number_format($bytes / 1024, 1).' KB';
if ($bytes < 1073741824) return number_format($bytes / 1048576, 1).' MB';
return number_format($bytes / 1073741824, 2).' GB';
}
}
+9 -2
View File
@@ -11,12 +11,19 @@ class User extends Authenticatable implements MustVerifyEmail
{
use HasFactory, Notifiable;
protected $fillable = ['name', 'email', 'password', 'is_admin'];
protected $fillable = [
'name',
'email',
'email_verified_at',
'password',
'is_admin',
'disabled_at',
];
protected $hidden = ['password', 'remember_token'];
protected function casts(): array
{
return ['email_verified_at' => 'datetime', 'password' => 'hashed', 'is_admin' => 'boolean'];
return ['email_verified_at' => 'datetime', 'password' => 'hashed', 'is_admin' => 'boolean', 'disabled_at' => 'datetime'];
}
}
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
}
}
@@ -1,26 +0,0 @@
<?php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
final class SonarDeskLicensingServiceProvider extends ServiceProvider
{
public function boot(): void
{
RateLimiter::for('license-activation', function (Request $request): array {
return [
Limit::perMinute(12)->by($request->ip()),
Limit::perMinute(6)->by(hash('sha256', (string) $request->input('installationID'))),
];
});
RateLimiter::for('login', fn (Request $request) => Limit::perMinute(5)
->by(strtolower((string) $request->input('email')).'|'.$request->ip()));
RateLimiter::for('registration', fn (Request $request) => Limit::perHour(5)->by($request->ip()));
}
}
@@ -0,0 +1,108 @@
<?php
namespace App\Services\Accounts;
use App\Models\User;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;
use RuntimeException;
final class PurchasedAccountProvisioner
{
public function ensure(
?string $email,
?string $name = null,
bool $sendSetupLink = true
): ?User {
$email = strtolower(trim((string) $email));
if ($email === '' || ! filter_var($email, FILTER_VALIDATE_EMAIL)) {
return null;
}
/*
* Fast path for the normal case.
*
* Paddle can deliver several related webhook events concurrently, so
* this lookup alone cannot guarantee that another request will not
* create the user between this SELECT and our INSERT.
*/
$user = $this->findByEmail($email);
if ($user) {
return $user;
}
$created = false;
try {
$user = User::create([
'name' => $this->displayName($name, $email),
'email' => $email,
'email_verified_at' => now(),
'password' => Str::random(64),
'is_admin' => false,
]);
$created = true;
} catch (UniqueConstraintViolationException $exception) {
/*
* Another webhook may have created this account after our SELECT
* but before our INSERT. In that case the unique email constraint
* correctly rejects our INSERT; simply reuse the account that won
* the race.
*/
$user = $this->findByEmail($email);
if (! $user) {
/*
* The unique violation was not caused by the email account
* appearing concurrently, so preserve the original failure.
*/
throw $exception;
}
}
/*
* Only the request that actually created the account should send the
* account setup/reset link. Concurrent Paddle events must not result
* in several setup emails being sent to the customer.
*/
if ($created && $sendSetupLink) {
DB::afterCommit(static function () use ($email): void {
Password::sendResetLink(['email' => $email]);
});
}
return $user;
}
private function findByEmail(string $email): ?User
{
return User::query()
->whereRaw('LOWER(email) = ?', [$email])
->first();
}
private function displayName(?string $name, string $email): string
{
$name = trim((string) $name);
if ($name !== '') {
return mb_substr($name, 0, 120);
}
$localPart = strstr($email, '@', true) ?: 'SonarDesk Customer';
$localPart = trim(str_replace(['.', '_', '-'], ' ', $localPart));
return mb_substr(
$localPart !== ''
? ucwords($localPart)
: 'SonarDesk Customer',
0,
120
);
}
}
+65
View File
@@ -0,0 +1,65 @@
<?php
namespace App\Services;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use InvalidArgumentException;
final class IndexNowService
{
/** @param array<int, string> $urls */
public function submit(array $urls): ?Response
{
if (! config('indexnow.enabled')) {
Log::info('IndexNow submission skipped: disabled.');
return null;
}
$key = trim((string) config('indexnow.key'));
if ($key === '') {
throw new InvalidArgumentException('INDEXNOW_KEY is not configured.');
}
$urls = collect($urls)
->filter(fn ($url) => is_string($url) && filter_var($url, FILTER_VALIDATE_URL))
->unique()
->values()
->all();
if ($urls === []) {
throw new InvalidArgumentException('No valid URLs were supplied to IndexNow.');
}
$host = parse_url($urls[0], PHP_URL_HOST);
if (! is_string($host) || $host === '') {
throw new InvalidArgumentException('Could not determine the IndexNow host.');
}
foreach ($urls as $url) {
if (parse_url($url, PHP_URL_HOST) !== $host) {
throw new InvalidArgumentException('All IndexNow URLs must use the same host.');
}
}
$response = Http::asJson()
->acceptJson()
->timeout(10)
->retry(2, 500)
->post((string) config('indexnow.endpoint'), [
'host' => $host,
'key' => $key,
'keyLocation' => 'https://'.$host.'/'.$key.'.txt',
'urlList' => $urls,
]);
if ($response->successful()) {
Log::info('IndexNow URLs submitted.', ['host' => $host, 'count' => count($urls), 'status' => $response->status()]);
} else {
Log::warning('IndexNow submission failed.', ['host' => $host, 'count' => count($urls), 'status' => $response->status(), 'body' => $response->body()]);
}
return $response;
}
}
@@ -0,0 +1,63 @@
<?php
namespace App\Services\Payments;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;
final class CustomerAccountProvisioner
{
public function ensure(?string $email, ?string $name = null): ?User
{
$email = strtolower(trim((string) $email));
if ($email === '' || ! filter_var($email, FILTER_VALIDATE_EMAIL)) {
return null;
}
$user = User::whereRaw('lower(email) = ?', [$email])->first();
if ($user) {
return $user;
}
$displayName = trim((string) $name);
if ($displayName === '') {
$displayName = Str::headline(Str::before($email, '@')) ?: 'SonarDesk Customer';
}
$user = User::firstOrCreate(
['email' => $email],
[
'name' => $displayName,
// The customer never receives or knows this password. They choose their
// own password through Laravel's signed, single-use reset flow.
'password' => Str::random(64),
// Access still requires possession of the mailbox because account setup
// is completed using the reset link sent to this address.
'email_verified_at' => now(),
],
);
if ($user->wasRecentlyCreated) {
DB::afterCommit(function () use ($email): void {
try {
$status = Password::sendResetLink(['email' => $email]);
if ($status !== Password::RESET_LINK_SENT) {
Log::warning('SonarDesk customer account created but setup email was not sent.', [
'email' => $email,
'status' => $status,
]);
}
} catch (\Throwable $exception) {
// A mail outage must never undo a paid licence. The customer can
// also use Forgot Password once mail is restored.
report($exception);
}
});
}
return $user;
}
}
-82
View File
@@ -1,82 +0,0 @@
<?php
namespace App\Services\Payments;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
use RuntimeException;
final class PaddleClient
{
public function customer(?string $customerID): ?array
{
if (! $customerID || ! config('sonardesk.paddle.api_key')) {
return null;
}
$response = $this->request()->get('/customers/'.$customerID);
if (! $response->successful()) {
return null;
}
$data = $response->json('data');
return is_array($data) ? $data : null;
}
public function updateSubscriptionPrice(string $subscriptionID, string $priceID): array
{
$this->requireWritableConfiguration();
$response = $this->request()->patch('/subscriptions/'.$subscriptionID, [
'proration_billing_mode' => 'prorated_immediately',
'items' => [[
'price_id' => $priceID,
'quantity' => 1,
]],
]);
return $this->subscriptionData($response, 'Paddle could not update the subscription.');
}
public function cancelSubscriptionImmediately(string $subscriptionID): array
{
$this->requireWritableConfiguration();
$response = $this->request()->post('/subscriptions/'.$subscriptionID.'/cancel', [
'effective_from' => 'immediately',
]);
return $this->subscriptionData($response, 'Paddle could not cancel the subscription.');
}
private function request()
{
return Http::baseUrl((string) config('sonardesk.paddle.api_url'))
->withToken((string) config('sonardesk.paddle.api_key'))
->acceptJson()
->timeout(15);
}
private function requireWritableConfiguration(): void
{
if (trim((string) config('sonardesk.paddle.api_key')) === '') {
throw new RuntimeException('Paddle subscription management is not configured.');
}
}
private function subscriptionData(Response $response, string $fallback): array
{
if (! $response->successful()) {
$detail = trim((string) ($response->json('error.detail') ?? ''));
throw new RuntimeException($detail !== '' ? $detail : $fallback);
}
$data = $response->json('data');
if (! is_array($data)) {
throw new RuntimeException($fallback);
}
return $data;
}
}
@@ -1,267 +0,0 @@
<?php
namespace App\Services\Payments;
use App\Models\License;
use App\Models\LicenseProduct;
use App\Models\LicenseDeliveryOutbox;
use App\Services\Licensing\LicenseIssuer;
use Illuminate\Support\Carbon;
use RuntimeException;
final class PurchaseProvisioner
{
public function __construct(private LicenseIssuer $issuer, private PaddleClient $paddle) {}
public function provision(string $provider, array $event): void
{
if ($provider === 'paddle') {
$this->provisionPaddle($event);
return;
}
if ($provider === 'lemon-squeezy') {
$this->provisionLemonSqueezy($event);
return;
}
throw new RuntimeException('Unsupported payment provider.');
}
private function provisionPaddle(array $event): void
{
$type = (string) ($event['event_type'] ?? '');
$data = $event['data'] ?? [];
if (str_starts_with($type, 'subscription.')) {
$this->syncPaddleSubscription($type, $data);
return;
}
if ($type === 'transaction.completed') {
$this->syncPaddleTransaction($data);
return;
}
if ($type === 'transaction.refunded') {
$transactionID = (string) ($data['id'] ?? '');
if ($transactionID !== '') {
License::where('payment_provider', 'paddle')
->where('external_order_id', $transactionID)
->whereNull('external_subscription_id')
->whereNull('revoked_at')
->update(['revoked_at' => now(), 'revoke_reason' => 'Payment refunded']);
}
}
}
private function syncPaddleSubscription(string $type, array $data): void
{
$subscriptionID = (string) ($data['id'] ?? '');
if ($subscriptionID === '') {
throw new RuntimeException('Paddle subscription webhook has no subscription ID.');
}
$status = (string) ($data['status'] ?? '');
$item = $this->firstRecurringItem($data['items'] ?? []);
$price = $item['price'] ?? [];
$priceID = (string) ($price['id'] ?? $item['price_id'] ?? '');
$productID = (string) ($price['product_id'] ?? $item['product_id'] ?? '');
$license = License::where('payment_provider', 'paddle')
->where('external_subscription_id', $subscriptionID)
->first();
if (! $license) {
$product = $this->mappedProduct('paddle', $priceID, $productID);
$custom = is_array($data['custom_data'] ?? null) ? $data['custom_data'] : [];
$customer = $this->paddle->customer($this->nullableString($data['customer_id'] ?? null)) ?? [];
[$license] = $this->issuer->issue(
$product,
$this->nullableString($custom['customer_name'] ?? $custom['name'] ?? $customer['name'] ?? null),
$this->nullableString($custom['customer_email'] ?? $custom['email'] ?? $customer['email'] ?? null),
'paddle',
$this->nullableString($data['transaction_id'] ?? null),
$this->nullableString($data['customer_id'] ?? null),
true,
);
$license->external_subscription_id = $subscriptionID;
} elseif ($priceID !== '' && $priceID !== $license->external_price_id) {
// Upgrades/downgrades change the entitlement attached to the existing key.
$product = $this->mappedProduct('paddle', $priceID, $productID);
$license->license_product_id = $product->id;
$license->edition = $product->edition;
$license->activation_limit = $product->activation_limit;
$license->max_major_version = $product->max_major_version;
}
$periodEnd = $data['current_billing_period']['ends_at'] ?? null;
$scheduled = $data['scheduled_change'] ?? null;
$cancelAt = is_array($scheduled) && ($scheduled['action'] ?? null) === 'cancel'
? ($scheduled['effective_at'] ?? null)
: null;
$license->external_customer_id = $this->nullableString($data['customer_id'] ?? null) ?? $license->external_customer_id;
$this->backfillPaddleCustomer($license, $data);
$license->external_price_id = $priceID !== '' ? $priceID : $license->external_price_id;
$license->subscription_status = $status !== '' ? $status : $license->subscription_status;
$license->current_period_ends_at = $periodEnd ? Carbon::parse($periodEnd) : $license->current_period_ends_at;
$license->cancel_scheduled_at = $cancelAt ? Carbon::parse($cancelAt) : null;
if (in_array($status, ['active', 'trialing'], true)) {
$license->revoked_at = null;
$license->revoke_reason = null;
// Trialing/active subscriptions remain valid through the current period.
$license->expires_at = $periodEnd ? Carbon::parse($periodEnd) : null;
} elseif ($status === 'past_due') {
// Do not instantly kill a licence on the first failed renewal. Preserve the
// period Paddle says is current; a later canceled event ends entitlement.
$license->expires_at = $periodEnd ? Carbon::parse($periodEnd) : ($license->expires_at ?? now()->addDays(7));
} elseif (in_array($status, ['canceled', 'paused'], true)) {
$license->expires_at = now();
$license->revoked_at = now();
$license->revoke_reason = $status === 'paused' ? 'Subscription paused' : 'Subscription canceled';
}
$license->save();
}
private function syncPaddleTransaction(array $data): void
{
$subscriptionID = $this->nullableString($data['subscription_id'] ?? null);
$transactionID = (string) ($data['id'] ?? '');
// Recurring purchases are provisioned from subscription events because those
// events contain the authoritative trial/status/current-period state.
if ($subscriptionID) {
License::where('payment_provider', 'paddle')
->where('external_subscription_id', $subscriptionID)
->whereNull('external_order_id')
->update(['external_order_id' => $transactionID ?: null]);
return;
}
// Keep support for any future one-time Paddle licence product.
$item = $data['items'][0] ?? [];
$price = $item['price'] ?? [];
$priceID = (string) ($price['id'] ?? $item['price_id'] ?? '');
$productID = (string) ($price['product_id'] ?? $item['product_id'] ?? '');
$product = $this->mappedProduct('paddle', $priceID, $productID);
$custom = is_array($data['custom_data'] ?? null) ? $data['custom_data'] : [];
$customer = $this->paddle->customer($this->nullableString($data['customer_id'] ?? null)) ?? [];
$this->issuer->issue(
$product,
$this->nullableString($custom['customer_name'] ?? $custom['name'] ?? $customer['name'] ?? null),
$this->nullableString($custom['customer_email'] ?? $custom['email'] ?? $customer['email'] ?? null),
'paddle',
$transactionID,
$this->nullableString($data['customer_id'] ?? null),
true,
);
}
private function provisionLemonSqueezy(array $event): void
{
$type = (string) ($event['meta']['event_name'] ?? '');
$attributes = $event['data']['attributes'] ?? [];
$order = (string) ($event['data']['id'] ?? $attributes['order_id'] ?? '');
if (in_array($type, ['order_refunded', 'subscription_expired'], true)) {
License::where('payment_provider', 'lemon-squeezy')
->where('external_order_id', $order)
->whereNull('revoked_at')
->update(['revoked_at' => now(), 'revoke_reason' => 'Payment refunded or subscription expired']);
return;
}
if (! in_array($type, ['order_created', 'subscription_created'], true)) {
return;
}
$product = $this->mappedProduct(
'lemon-squeezy',
(string) ($attributes['variant_id'] ?? ''),
(string) ($attributes['product_id'] ?? ''),
);
$this->issuer->issue(
$product,
$this->nullableString($attributes['user_name'] ?? null),
$this->nullableString($attributes['user_email'] ?? null),
'lemon-squeezy',
$order,
$this->nullableString($attributes['customer_id'] ?? null),
true,
);
}
private function backfillPaddleCustomer(License $license, array $data): void
{
$custom = is_array($data['custom_data'] ?? null) ? $data['custom_data'] : [];
$customer = $this->paddle->customer($this->nullableString($data['customer_id'] ?? $license->external_customer_id)) ?? [];
$name = $this->nullableString($custom['customer_name'] ?? $custom['name'] ?? $customer['name'] ?? null);
$email = $this->nullableString($custom['customer_email'] ?? $custom['email'] ?? $customer['email'] ?? null);
if (! $license->customer_name && $name) {
$license->customer_name = $name;
}
if (! $license->customer_email && $email) {
$license->customer_email = strtolower($email);
LicenseDeliveryOutbox::where('license_id', $license->id)
->whereNull('delivered_at')
->update(['recipient_email' => strtolower($email)]);
}
}
private function mappedProduct(string $provider, string $priceID, string $productID): LicenseProduct
{
// Price IDs are the authoritative mapping because monthly and annual prices
// intentionally share the same Paddle product ID.
if ($priceID !== '') {
$product = LicenseProduct::where('payment_provider', $provider)
->where('external_price_id', $priceID)
->where('active', true)
->first();
} else {
$product = LicenseProduct::where('payment_provider', $provider)
->where('external_product_id', $productID)
->where('active', true)
->first();
}
if (! $product) {
throw new RuntimeException("No active licence product maps to {$provider} price {$priceID} / product {$productID}.");
}
return $product;
}
private function firstRecurringItem(array $items): array
{
foreach ($items as $item) {
if (($item['recurring'] ?? true) === true) {
return $item;
}
}
return $items[0] ?? [];
}
private function nullableString(mixed $value): ?string
{
if (! is_scalar($value)) {
return null;
}
$value = trim((string) $value);
return $value === '' ? null : $value;
}
}
+1 -1
View File
@@ -13,7 +13,7 @@ return Application::configure(basePath: dirname(__DIR__))
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
//
$middleware->web(append: [\Modules\Stylist\Http\Middleware\ApplyActiveTheme::class]);
})
->withExceptions(function (Exceptions $exceptions): void {
$exceptions->shouldRenderJsonWhen(
+1 -3
View File
@@ -1,7 +1,5 @@
<?php
use App\Providers\SonarDeskLicensingServiceProvider;
return [
SonarDeskLicensingServiceProvider::class,
App\Providers\AppServiceProvider::class,
];
+21 -2
View File
@@ -3,13 +3,31 @@
"name": "laravel/laravel",
"type": "project",
"description": "The skeleton application for the Laravel framework.",
"keywords": ["laravel", "framework"],
"keywords": [
"laravel",
"framework"
],
"license": "MIT",
"repositories": [
{
"type": "vcs",
"url": "git@github.com:MPBA-Ltd/laravel_modules.git"
},
{
"type": "vcs",
"url": "git@github.com:MPBA-Ltd/laravel_settings.git"
},
{
"type": "vcs",
"url": "git@github.com:MPBA-Ltd/laravel-charts.git"
}
],
"require": {
"php": "^8.3",
"deployer/deployer": "^8.0",
"laravel/framework": "^13.17",
"laravel/tinker": "^3.0",
"mpba/laravel-modules": "dev-main",
"predis/predis": "^3.6"
},
"require-dev": {
@@ -25,7 +43,8 @@
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
"Database\\Seeders\\": "database/seeders/",
"Modules\\": "modules/"
}
},
"autoload-dev": {
Generated
+110 -13
View File
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "1f5b5a47e5910fdf5b2c47e1bc45e1b0",
"content-hash": "d92f21f84e06e667b70468859bfaffd0",
"packages": [
{
"name": "brick/math",
@@ -1542,16 +1542,16 @@
},
{
"name": "league/commonmark",
"version": "2.10.1",
"version": "2.10.3",
"source": {
"type": "git",
"url": "https://github.com/thephpleague/commonmark.git",
"reference": "9d489ab67a02960fd8ffe624d93f751daf95439e"
"reference": "6efbd9c472b91db0a3350fcd601c8332c2382e1f"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/thephpleague/commonmark/zipball/9d489ab67a02960fd8ffe624d93f751daf95439e",
"reference": "9d489ab67a02960fd8ffe624d93f751daf95439e",
"url": "https://api.github.com/repos/thephpleague/commonmark/zipball/6efbd9c472b91db0a3350fcd601c8332c2382e1f",
"reference": "6efbd9c472b91db0a3350fcd601c8332c2382e1f",
"shasum": ""
},
"require": {
@@ -1645,7 +1645,7 @@
"type": "tidelift"
}
],
"time": "2026-09-07T13:44:26+00:00"
"time": "2026-09-21T13:07:34+00:00"
},
{
"name": "league/config",
@@ -2256,6 +2256,101 @@
],
"time": "2026-09-02T12:39:56+00:00"
},
{
"name": "mpba/laravel-modules",
"version": "dev-main",
"source": {
"type": "git",
"url": "https://github.com/MPBA-Ltd/laravel_modules.git",
"reference": "55d802560f6404d6b9fd71a89561ed46d32124ff"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/MPBA-Ltd/laravel_modules/zipball/55d802560f6404d6b9fd71a89561ed46d32124ff",
"reference": "55d802560f6404d6b9fd71a89561ed46d32124ff",
"shasum": ""
},
"require": {
"ext-json": "*",
"php": ">=7.3"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^2.16",
"laravel/framework": "^8.0",
"mockery/mockery": "~1.0",
"orchestra/testbench": "^6.0",
"phpstan/phpstan": "^0.12.14",
"phpunit/phpunit": "^8.5",
"spatie/phpunit-snapshot-assertions": "^2.1.0"
},
"default-branch": true,
"type": "library",
"extra": {
"laravel": {
"providers": [
"mpba\\Modules\\LaravelModulesServiceProvider"
],
"aliases": {
"Module": "mpba\\Modules\\Facades\\Module"
}
},
"branch-alias": {
"dev-master": "8.0-dev"
}
},
"autoload": {
"psr-4": {
"mpba\\Modules\\": "src"
},
"files": [
"src/helpers.php"
]
},
"autoload-dev": {
"psr-4": {
"mpba\\Modules\\Tests\\": "tests",
"Modules\\Recipe\\": "tests/stubs/valid/Recipe"
}
},
"scripts": {
"update-snapshots": [
"./vendor/bin/phpunit --no-coverage -d --update-snapshots"
],
"test": [
"vendor/bin/phpunit"
],
"test-coverage": [
"vendor/bin/phpunit --debug --coverage-html coverage"
],
"pcf": [
"vendor/bin/php-cs-fixer fix --verbose"
]
},
"license": [
"MIT"
],
"authors": [
{
"name": "Mark Gregory",
"email": "mark.gregory@mpba.co.uk",
"homepage": "https://mpba.co.uk",
"role": "Developer"
}
],
"description": "Laravel Module management",
"keywords": [
"laravel",
"module",
"modules",
"mpba",
"rad"
],
"support": {
"source": "https://github.com/MPBA-Ltd/laravel_modules/tree/main",
"issues": "https://github.com/MPBA-Ltd/laravel_modules/issues"
},
"time": "2026-09-30T13:50:27+00:00"
},
{
"name": "nesbot/carbon",
"version": "3.13.2",
@@ -4875,16 +4970,16 @@
},
{
"name": "symfony/polyfill-php80",
"version": "v1.37.0",
"version": "v1.43.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-php80.git",
"reference": "dfb55726c3a76ea3b6459fcfda1ec2d80a682411"
"reference": "9c6a5d6b01ca51d486c813e9a9c0ed55f208bb74"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/dfb55726c3a76ea3b6459fcfda1ec2d80a682411",
"reference": "dfb55726c3a76ea3b6459fcfda1ec2d80a682411",
"url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/9c6a5d6b01ca51d486c813e9a9c0ed55f208bb74",
"reference": "9c6a5d6b01ca51d486c813e9a9c0ed55f208bb74",
"shasum": ""
},
"require": {
@@ -4935,7 +5030,7 @@
"shim"
],
"support": {
"source": "https://github.com/symfony/polyfill-php80/tree/v1.37.0"
"source": "https://github.com/symfony/polyfill-php80/tree/v1.43.0"
},
"funding": [
{
@@ -4955,7 +5050,7 @@
"type": "tidelift"
}
],
"time": "2026-04-10T16:19:22+00:00"
"time": "2026-09-25T15:50:05+00:00"
},
{
"name": "symfony/polyfill-php82",
@@ -8709,7 +8804,9 @@
],
"aliases": [],
"minimum-stability": "stable",
"stability-flags": [],
"stability-flags": {
"mpba/laravel-modules": 20
},
"prefer-stable": true,
"prefer-lowest": false,
"platform": {
+7
View File
@@ -0,0 +1,7 @@
<?php
return [
'enabled' => (bool) env('INDEXNOW_ENABLED', false),
'key' => env('INDEXNOW_KEY'),
'endpoint' => env('INDEXNOW_ENDPOINT', 'https://api.indexnow.org/indexnow'),
];
-15
View File
@@ -28,21 +28,6 @@ return [
'notify_admin_users' => filter_var(env('SONARDESK_SUPPORT_NOTIFY_ADMINS', true), FILTER_VALIDATE_BOOL),
],
'paddle' => [
'api_key' => env('PADDLE_API_KEY'),
'client_side_token' => env('PADDLE_CLIENT_SIDE_TOKEN'),
'environment' => env('PADDLE_ENVIRONMENT', env('APP_ENV') === 'production' ? 'production' : 'sandbox'),
'api_url' => env('PADDLE_API_URL', env('APP_ENV') === 'production' ? 'https://api.paddle.com' : 'https://sandbox-api.paddle.com'),
'webhook_secret' => env('PADDLE_WEBHOOK_SECRET'),
'timestamp_tolerance' => (int) env('PADDLE_WEBHOOK_TOLERANCE', 300),
// SonarDesk is one Paddle product with four recurring prices.
'product_id' => env('PADDLE_PRODUCT_ID'),
'personal_monthly_price_id' => env('PADDLE_PERSONAL_MONTHLY_PRICE_ID'),
'personal_annual_price_id' => env('PADDLE_PERSONAL_ANNUAL_PRICE_ID'),
'professional_monthly_price_id' => env('PADDLE_PROFESSIONAL_MONTHLY_PRICE_ID'),
'professional_annual_price_id' => env('PADDLE_PROFESSIONAL_ANNUAL_PRICE_ID'),
],
'lemon_squeezy' => [
'webhook_secret' => env('LEMON_SQUEEZY_WEBHOOK_SECRET'),
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
/**
* @extends Factory<\App\Models\User>
*/
class UserFactory extends Factory
{
protected static ?string $password;
public function definition(): array
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => static::$password ??= Hash::make('password'),
'remember_token' => Str::random(10),
'is_admin' => false,
];
}
public function unverified(): static
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
}
@@ -0,0 +1,42 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
public function up(): void
{
Schema::create('sonardesk_releases', function (Blueprint $table): void {
$table->id();
$table->string('version', 40);
$table->unsignedInteger('build_number')->default(1);
$table->string('channel', 20)->default('stable');
$table->string('minimum_macos', 30)->nullable();
$table->string('file_path')->nullable();
$table->string('original_filename')->nullable();
$table->unsignedBigInteger('file_size')->nullable();
$table->string('sha256', 64)->nullable();
$table->text('sparkle_signature')->nullable();
$table->text('release_notes')->nullable();
$table->boolean('is_published')->default(false)->index();
$table->boolean('is_featured')->default(false)->index();
$table->timestamp('published_at')->nullable()->index();
$table->unsignedBigInteger('download_count')->default(0);
$table->timestamps();
$table->unique(['version', 'build_number', 'channel']);
});
Schema::create('sonardesk_site_settings', function (Blueprint $table): void {
$table->string('key')->primary();
$table->text('value')->nullable();
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('sonardesk_site_settings');
Schema::dropIfExists('sonardesk_releases');
}
};
@@ -0,0 +1,35 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
public function up(): void
{
Schema::table('cms_pages', function (Blueprint $table): void {
$table->string('meta_keywords', 500)->nullable()->after('meta_description');
$table->string('canonical_url', 2048)->nullable()->after('meta_keywords');
$table->string('og_title')->nullable()->after('canonical_url');
$table->string('og_description', 320)->nullable()->after('og_title');
$table->string('og_image', 2048)->nullable()->after('og_description');
$table->boolean('robots_index')->default(true)->after('og_image');
$table->boolean('robots_follow')->default(true)->after('robots_index');
$table->boolean('include_in_sitemap')->default(true)->after('robots_follow')->index();
$table->decimal('sitemap_priority', 2, 1)->default(0.5)->after('include_in_sitemap');
$table->string('sitemap_change_frequency', 20)->default('monthly')->after('sitemap_priority');
});
}
public function down(): void
{
Schema::table('cms_pages', function (Blueprint $table): void {
$table->dropIndex(['include_in_sitemap']);
$table->dropColumn([
'meta_keywords', 'canonical_url', 'og_title', 'og_description', 'og_image',
'robots_index', 'robots_follow', 'include_in_sitemap', 'sitemap_priority',
'sitemap_change_frequency',
]);
});
}
};
@@ -0,0 +1,22 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
if (Schema::hasTable('users') && ! Schema::hasColumn('users', 'disabled_at')) {
Schema::table('users', fn (Blueprint $table) => $table->timestamp('disabled_at')->nullable()->index()->after('is_admin'));
}
}
public function down(): void
{
if (Schema::hasTable('users') && Schema::hasColumn('users', 'disabled_at')) {
Schema::table('users', fn (Blueprint $table) => $table->dropColumn('disabled_at'));
}
}
};
@@ -0,0 +1,26 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('failed_jobs', function (Blueprint $table): void {
$table->id();
$table->string('uuid')->unique();
$table->text('connection');
$table->text('queue');
$table->longText('payload');
$table->longText('exception');
$table->timestamp('failed_at')->useCurrent();
});
}
public function down(): void
{
Schema::dropIfExists('failed_jobs');
}
};
@@ -0,0 +1,18 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
public function up(): void {
Schema::create('download_products', function (Blueprint $table) {
$table->id(); $table->string('name'); $table->text('description')->nullable();
$table->string('version')->nullable(); $table->string('platform')->nullable();
$table->string('file_path')->nullable(); $table->string('original_filename')->nullable();
$table->unsignedBigInteger('file_size')->default(0); $table->unsignedBigInteger('download_count')->default(0);
$table->boolean('is_published')->default(false); $table->timestamps();
});
}
public function down(): void { Schema::dropIfExists('download_products'); }
};
+15 -5
View File
@@ -18,18 +18,27 @@ add('shared_dirs', ['storage']);
add('writable_dirs', ['storage', 'bootstrap/cache']);
// Host Definitions
host('production')
->set('hostname', 'sonardsk.absdev.net')
host('prod')
->set('hostname', '217.154.47.197')
->set('remote_user', 'mag')
->set('branch', 'main')
->set('deploy_path', '/var/www/sonardesk/main');
->set('php_version', '8.5')
->set('deploy_path', '/var/www/sonardesk/prod');
host('stage')
->set('hostname', 'sonardesk.stage.absdev.net')
->set('hostname', '192.168.1.2')
->set('remote_user', 'mag')
->set('branch', 'stage')
->set('php_version', '8.3')
->set('deploy_path', '/var/www/sonardesk/stage');
host('develop')
->set('hostname', '10.211.55.100')
->set('remote_user', 'mag')
->set('php_version', '8.3')
->set('branch', 'develop')
->set('deploy_path', '/var/www/sonardesk/develop');
task('build', function (): void {
run('export NVM_DIR="$HOME/.nvm" && [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" && nvm use {{node_version}} && cd {{release_path}} && npm ci --no-audit --no-fund');
run('export NVM_DIR="$HOME/.nvm" && [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" && nvm use {{node_version}} && cd {{release_path}} && npm run build');
@@ -48,9 +57,10 @@ task('artisan:clear', function (): void {
run('cd {{release_path}} && php artisan route:clear');
});
task('services:restart', function (): void {
$phpVersion = currentHost()->get('php_version');
run('sudo -n nginx -t');
run('sudo -n systemctl reload nginx');
run('sudo -n systemctl restart php8.3-fpm');
run("sudo -n systemctl restart php{$phpVersion}-fpm");
});
after('deploy:update_code', 'deploy:write_revision_file');
View File
View File
@@ -107,7 +107,7 @@ The current code uses subscription events as the authoritative state for recurri
Copy the webhook endpoint secret.
### E. Production `.env`
### E. Production `../.env`
Set the following values on the production server. Do not commit them.
@@ -135,7 +135,7 @@ Also configure the existing SonarDesk licence signing keys, mailer, support emai
### F. Seed the price mapping
After the production IDs are in `.env`:
After the production IDs are in `../.env`:
```bash
php artisan config:clear
+28
View File
@@ -0,0 +1,28 @@
# SonarDesk release distribution
The website now owns SonarDesk release distribution from the admin area.
## Deploy
1. Deploy the code normally.
2. Run `php artisan migrate --force`.
3. Ensure Laravel's `storage` directory remains shared/persistent between releases (the existing Deployer configuration already shares `storage`).
4. Ensure the web/PHP upload limits are large enough for the DMG. For a 1 GB application limit, configure nginx `client_max_body_size` and PHP `upload_max_filesize` / `post_max_size` accordingly.
## Publishing a build
Open **Admin → Releases → New release**. Enter the marketing version, build number, minimum macOS version and release notes, upload the signed/notarized DMG or ZIP, and paste the Sparkle EdDSA signature when Sparkle is enabled. Save as a draft until the package is ready, then publish it.
Published stable releases automatically feed:
- `/release` — customer-facing distribution centre
- `/download` — latest stable package
- `/updates/appcast.xml` — Sparkle feed
- the licence portal download call-to-action
- licence delivery email download call-to-action
The SHA-256 checksum and file size are calculated on upload. Download counts are tracked per release.
## Sparkle
Generate the EdDSA signature with the Sparkle release tooling and paste it into the release editor. Configure the macOS app's feed URL to the production `/updates/appcast.xml` endpoint. Do not place Sparkle private signing keys on the public web server.
View File
+8
View File
@@ -0,0 +1,8 @@
<?php
return [
'name' => 'Licensing',
'features' =>
[
],
];
View File
@@ -1,8 +1,8 @@
<?php
namespace App\Console\Commands;
namespace Modules\Licensing\Console;
use App\Services\Licensing\LicenseDeliveryService;
use Modules\Licensing\Services\LicenseDeliveryService;
use Illuminate\Console\Command;
final class SonarDeskLicenseDeliver extends Command
@@ -1,9 +1,9 @@
<?php
namespace App\Console\Commands;
namespace Modules\Licensing\Console;
use App\Models\LicenseProduct;
use App\Services\Licensing\LicenseIssuer;
use Modules\Licensing\Models\LicenseProduct;
use Modules\Licensing\Services\LicenseIssuer;
use Illuminate\Console\Command;
class SonarDeskLicenseIssue extends Command
@@ -1,8 +1,8 @@
<?php
namespace App\Console\Commands;
namespace Modules\Licensing\Console;
use App\Models\License;
use Modules\Licensing\Models\License;
use Illuminate\Console\Command;
class SonarDeskLicenseRevoke extends Command
@@ -1,8 +1,8 @@
<?php
namespace App\Console\Commands;
namespace Modules\Licensing\Console;
use App\Models\LicenseProduct;
use Modules\Licensing\Models\LicenseProduct;
use Illuminate\Console\Command;
class SonarDeskProductCreate extends Command
@@ -0,0 +1,92 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('license_products', function (Blueprint $table) {
$table->id();
$table->string('code')->unique();
$table->string('name');
$table->string('edition')->default('Professional');
$table->unsignedInteger('activation_limit')->default(1);
$table->unsignedInteger('max_major_version')->nullable();
$table->string('payment_provider')->nullable();
$table->string('external_product_id')->nullable();
$table->string('external_price_id')->nullable();
$table->boolean('active')->default(true);
$table->timestamps();
$table->unique(['payment_provider', 'external_price_id']);
});
Schema::create('licenses', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->foreignId('license_product_id')->constrained('license_products');
$table->string('license_key_hash', 64)->unique();
$table->string('license_key_last4', 4);
$table->string('customer_name')->nullable();
$table->string('customer_email')->nullable()->index();
$table->string('edition');
$table->unsignedInteger('activation_limit');
$table->unsignedInteger('max_major_version')->nullable();
$table->timestamp('expires_at')->nullable();
$table->timestamp('revoked_at')->nullable();
$table->string('revoke_reason')->nullable();
$table->string('payment_provider')->nullable();
$table->string('external_order_id')->nullable();
$table->string('external_customer_id')->nullable();
$table->timestamps();
$table->unique(['payment_provider', 'external_order_id']);
});
Schema::create('license_delivery_outbox', function (Blueprint $table) {
$table->id();
$table->uuid('license_id')->unique();
$table->text('encrypted_license_key');
$table->string('recipient_email')->nullable();
$table->timestamp('delivered_at')->nullable();
$table->timestamps();
$table->foreign('license_id')->references('id')->on('licenses')->cascadeOnDelete();
});
Schema::create('license_activations', function (Blueprint $table) {
$table->id();
$table->uuid('license_id');
$table->uuid('installation_id');
$table->string('platform', 32)->nullable();
$table->string('app_version', 32)->nullable();
$table->timestamp('activated_at');
$table->timestamp('last_seen_at')->nullable();
$table->timestamp('deactivated_at')->nullable();
$table->foreign('license_id')->references('id')->on('licenses')->cascadeOnDelete();
$table->unique(['license_id', 'installation_id']);
$table->index(['license_id', 'deactivated_at']);
});
Schema::create('license_webhook_events', function (Blueprint $table) {
$table->id();
$table->string('provider');
$table->string('external_event_id');
$table->string('event_type');
$table->string('payload_sha256', 64);
$table->json('payload');
$table->timestamp('processed_at')->nullable();
$table->text('processing_error')->nullable();
$table->timestamps();
$table->unique(['provider', 'external_event_id']);
});
}
public function down(): void
{
Schema::dropIfExists('license_webhook_events');
Schema::dropIfExists('license_activations');
Schema::dropIfExists('license_delivery_outbox');
Schema::dropIfExists('licenses');
Schema::dropIfExists('license_products');
}
};
@@ -0,0 +1,30 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
if (Schema::hasTable('users') && ! Schema::hasColumn('users', 'is_admin')) {
Schema::table('users', fn (Blueprint $table) => $table->boolean('is_admin')->default(false)->index());
}
if (Schema::hasTable('license_activations') && ! Schema::hasColumn('license_activations', 'installation_name')) {
Schema::table('license_activations', fn (Blueprint $table) => $table->string('installation_name')->nullable()->after('installation_id'));
}
}
public function down(): void
{
if (Schema::hasTable('license_activations') && Schema::hasColumn('license_activations', 'installation_name')) {
Schema::table('license_activations', fn (Blueprint $table) => $table->dropColumn('installation_name'));
}
if (Schema::hasTable('users') && Schema::hasColumn('users', 'is_admin')) {
Schema::table('users', fn (Blueprint $table) => $table->dropColumn('is_admin'));
}
}
};
@@ -0,0 +1,21 @@
<?php
namespace Modules\Licensing\Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class LicensingDatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Model::unguard();
// $this->call("OthersTableSeeder");
}
}
View File
+12
View File
@@ -0,0 +1,12 @@
<?php
use Modules\Licensing\Support\ModuleInfo;
if (! function_exists('licensing_feature_enabled')) {
/**
* Check if a feature is enabled in the config.
*/
function licensing_feature_enabled(string $key): bool
{
return (bool) config(ModuleInfo::nameLower().".features.{$key}", false);
}
}
@@ -1,13 +1,13 @@
<?php
namespace App\Http\Controllers\Api;
namespace Modules\Licensing\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\License;
use App\Models\LicenseActivation;
use App\Services\Licensing\LicenseKey;
use App\Services\Licensing\LicenseSigner;
use App\Services\Licensing\LicenseTokenVerifier;
use Modules\Licensing\Models\License;
use Modules\Licensing\Models\LicenseActivation;
use Modules\Licensing\Services\LicenseKey;
use Modules\Licensing\Services\LicenseSigner;
use Modules\Licensing\Services\LicenseTokenVerifier;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
@@ -0,0 +1,191 @@
<?php
namespace Modules\Licensing\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Modules\Licensing\Models\LicenseWebhookEvent;
use Modules\Licensing\Services\LicenseDeliveryService;
use App\Services\Payments\LemonSqueezyWebhookVerifier;
use Modules\Paddle\Services\PaddleWebhookVerifier;
use Modules\Paddle\Services\PurchaseProvisioner;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use RuntimeException;
use Throwable;
final class PaymentWebhookController extends Controller
{
public function __invoke(
string $provider,
Request $request,
PurchaseProvisioner $provisioner,
LicenseDeliveryService $delivery
): JsonResponse {
$raw = (string) $request->getContent();
$verifier = match ($provider) {
'paddle' => app(PaddleWebhookVerifier::class),
'lemon-squeezy' => app(LemonSqueezyWebhookVerifier::class),
default => null,
};
if (! $verifier) {
return response()->json([
'message' => 'Unknown webhook provider.',
], 404);
}
try {
$verifier->verify($request, $raw);
} catch (Throwable $e) {
report($e);
return response()->json([
'message' => 'Invalid webhook signature.',
], 400);
}
try {
$payload = json_decode(
$raw,
true,
flags: JSON_THROW_ON_ERROR
);
} catch (Throwable) {
return response()->json([
'message' => 'Invalid JSON.',
], 400);
}
$externalID = (string) (
$provider === 'paddle'
? ($payload['event_id'] ?? '')
: ($payload['meta']['event_name'] ?? '')
.':'
.($payload['data']['id'] ?? '')
);
$eventType = (string) (
$provider === 'paddle'
? ($payload['event_type'] ?? 'unknown')
: ($payload['meta']['event_name'] ?? 'unknown')
);
if ($externalID === '') {
return response()->json([
'message' => 'Webhook event has no stable identifier.',
], 400);
}
$payloadHash = hash('sha256', $raw);
try {
/*
* Paddle can deliver several related events concurrently.
*
* Laravel retries this complete transaction when MySQL reports
* a deadlock. Five attempts gives short-lived lock contention
* enough opportunity to resolve without acknowledging an event
* that was not actually processed.
*/
DB::transaction(
function () use (
$provider,
$externalID,
$eventType,
$payload,
$payloadHash,
$provisioner
): void {
/*
* Insert the event if this is its first delivery.
*
* Once present, lock the row so duplicate deliveries of
* the same event cannot provision concurrently.
*/
LicenseWebhookEvent::firstOrCreate(
[
'provider' => $provider,
'external_event_id' => $externalID,
],
[
'event_type' => $eventType,
'payload_sha256' => $payloadHash,
'payload' => $payload,
]
);
$event = LicenseWebhookEvent::query()
->where('provider', $provider)
->where('external_event_id', $externalID)
->lockForUpdate()
->firstOrFail();
if ($event->processed_at) {
return;
}
if (! hash_equals(
(string) $event->payload_sha256,
$payloadHash
)) {
throw new RuntimeException(
'Webhook ID was reused with a different payload.'
);
}
try {
$provisioner->provision(
$provider,
$payload
);
$event->processed_at = now();
$event->processing_error = null;
$event->save();
} catch (Throwable $e) {
/*
* This assignment is useful when the surrounding
* transaction eventually succeeds. If processing
* throws, the transaction itself is rolled back and
* Paddle will retry the event.
*/
$event->processing_error = mb_substr(
$e->getMessage(),
0,
4000
);
$event->save();
throw $e;
}
},
5
);
} catch (Throwable $e) {
report($e);
return response()->json([
'message' => 'Webhook could not be processed.',
], 500);
}
/*
* Delivery deliberately happens outside the webhook transaction.
*
* A temporary SMTP failure must not undo a successfully processed
* payment event. The outbox retains anything that still needs
* delivery.
*/
try {
$delivery->deliverPending(10);
} catch (Throwable $e) {
report($e);
}
return response()->json([
'ok' => true,
]);
}
}
@@ -0,0 +1,79 @@
<?php
namespace Modules\Licensing\Http\Controllers;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
class LicensingController extends Controller
{
/**
* Display a listing of the resource.
* @return Renderable
*/
public function index()
{
return view('licensing::index');
}
/**
* Show the form for creating a new resource.
* @return Renderable
*/
public function create()
{
return view('licensing::create');
}
/**
* Store a newly created resource in storage.
* @param Request $request
* @return Renderable
*/
public function store(Request $request)
{
//
}
/**
* Show the specified resource.
* @param int $id
* @return Renderable
*/
public function show($id)
{
return view('licensing::show');
}
/**
* Show the form for editing the specified resource.
* @param int $id
* @return Renderable
*/
public function edit($id)
{
return view('licensing::edit');
}
/**
* Update the specified resource in storage.
* @param Request $request
* @param int $id
* @return Renderable
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
* @param int $id
* @return Renderable
*/
public function destroy($id)
{
//
}
}
@@ -1,13 +1,13 @@
<?php
namespace App\Http\Controllers\Portal;
namespace Modules\Licensing\Http\Controllers\Portal;
use App\Http\Controllers\Controller;
use App\Models\License;
use App\Models\LicenseDeliveryOutbox;
use App\Models\LicenseProduct;
use App\Services\Payments\PaddleClient;
use App\Services\Licensing\LicenseDeliveryService;
use Modules\Licensing\Models\License;
use Modules\Licensing\Models\LicenseDeliveryOutbox;
use Modules\Licensing\Models\LicenseProduct;
use Modules\Paddle\Services\PaddleClient;
use Modules\Licensing\Services\LicenseDeliveryService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use RuntimeException;
@@ -131,7 +131,7 @@ final class PortalController extends Controller
private function professionalPriceFor(License $license): string
{
$paddle = config('sonardesk.paddle');
$paddle = config('paddle');
$current = (string) $license->external_price_id;
if ($current === (string) ($paddle['personal_annual_price_id'] ?? '')) {
View File
@@ -1,6 +1,6 @@
<?php
namespace App\Models;
namespace Modules\Licensing\Models;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
@@ -1,6 +1,6 @@
<?php
namespace App\Models;
namespace Modules\Licensing\Models;
use Illuminate\Database\Eloquent\Model;
@@ -1,6 +1,6 @@
<?php
namespace App\Models;
namespace Modules\Licensing\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
@@ -1,6 +1,6 @@
<?php
namespace App\Models;
namespace Modules\Licensing\Models;
use Illuminate\Database\Eloquent\Model;
@@ -1,6 +1,6 @@
<?php
namespace App\Models;
namespace Modules\Licensing\Models;
use Illuminate\Database\Eloquent\Model;
@@ -0,0 +1,177 @@
<?php
namespace Modules\Licensing\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Database\Eloquent\Factory;
use Illuminate\Support\Facades\File;
use Modules\Licensing\Support\ModuleInfo;
use Config;
class LicensingServiceProvider extends ServiceProvider
{
/**
* @var string $moduleName
*/
protected string $moduleName = 'Licensing';
/**
* @var string $moduleNameLower
*/
protected string $moduleNameLower = 'licensing';
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides():array
{
return [];
}
/**
* Boot the application events.
*
* @return void
*/
public function boot() : void
{
\Illuminate\Support\Facades\Blade::anonymousComponentPath(
base_path('modules/Licensing/Resources/views/components/layouts'),
'layouts'
);
RateLimiter::for('login', fn (Request $request) => Limit::perMinute(5)
->by(strtolower((string) $request->input('email')).'|'.$request->ip()));
RateLimiter::for('registration', fn (Request $request) =>
Limit::perHour(5)->by($request->ip())
);
RateLimiter::for('license-activation', function (Request $request): array {
return [
Limit::perMinute(12)->by($request->ip()),
Limit::perMinute(6)->by(hash('sha256', (string) $request->input('installationID'))),
];
});
$this->registerTranslations();
$this->registerConfig();
$this->registerViews();
$this->registerHelpers();
$this->registerCommands();
$this->loadMigrationsFrom(module_path(ModuleInfo::name(), 'Database/Migrations'));
}
/**
* Register the service provider.
*
* @return void
*/
public function register(): void
{
$this->app->register(RouteServiceProvider::class);
}
/**
* Register the helpers.
*
* @return void
*/
protected function registerHelpers(): void
{
foreach (glob(__DIR__.'/../Helpers/*.php') as $filename) {
require_once $filename;
}
}
/**
* Dynamically Register Commands.
*
* @return void
*/
public function registerCommands(): void
{
if (!$this->app->runningInConsole()) {
return;
}
$commandPath = __DIR__ . '/../Console';
$commands = collect(File::allFiles($commandPath))
->map(function ($file) {
$class = 'Modules\\' . $this->moduleName . '\\Console\\' . $file->getFilenameWithoutExtension();
return $class;
})
->filter(function ($class) {
return class_exists($class);
})
->values()
->all();
$this->commands($commands);
}
/**
* Register config.
*
* @return void
*/
protected function registerConfig(): void
{
$this->publishes([
module_path(ModuleInfo::name(), 'Config/config.php') => config_path( ModuleInfo::nameLower(). '.php'),
], 'config');
$this->mergeConfigFrom(
module_path(ModuleInfo::name(), 'Config/config.php'), ModuleInfo::nameLower()
);
}
/**
* Register views.
*
* @return void
*/
public function registerViews(): void
{
$viewPath = resource_path('views/modules/' . ModuleInfo::nameLower());
$sourcePath = module_path(ModuleInfo::name(), 'Resources/views');
$this->publishes([
$sourcePath => $viewPath
], ['views', ModuleInfo::nameLower() . '-module-views']);
$this->loadViewsFrom(array_merge($this->getPublishableViewPaths(), [$sourcePath]), ModuleInfo::nameLower());
}
/**
* Register translations.
*
* @return void
*/
public function registerTranslations(): void
{
$langPath = resource_path('lang/modules/' . ModuleInfo::nameLower());
if (is_dir($langPath)) {
$this->loadTranslationsFrom($langPath, ModuleInfo::nameLower());
} else {
$this->loadTranslationsFrom(module_path(ModuleInfo::name(), 'Resources/lang'), ModuleInfo::nameLower());
}
}
/**
* Regsiter View Paths
* @return array
*/
private function getPublishableViewPaths(): array
{
$paths = [];
foreach (Config::get('view.paths') as $path) {
if (is_dir($path . '/modules/' . ModuleInfo::nameLower())) {
$paths[] = $path . '/modules/' . ModuleInfo::nameLower();
}
}
return $paths;
}
}
@@ -0,0 +1,69 @@
<?php
namespace Modules\Licensing\Providers;
use Illuminate\Support\Facades\Route;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
class RouteServiceProvider extends ServiceProvider
{
/**
* The module namespace to assume when generating URLs to actions.
*
* @var string
*/
protected $moduleNamespace = 'Modules\Licensing\Http\Controllers';
/**
* Called before routes are registered.
*
* Register any model bindings or pattern based filters.
*
* @return void
*/
public function boot()
{
parent::boot();
}
/**
* Define the routes for the application.
*
* @return void
*/
public function map()
{
$this->mapApiRoutes();
$this->mapWebRoutes();
}
/**
* Define the "web" routes for the application.
*
* These routes all receive session state, CSRF protection, etc.
*
* @return void
*/
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->moduleNamespace)
->group(module_path('Licensing', '/Routes/web.php'));
}
/**
* Define the "api" routes for the application.
*
* These routes are typically stateless.
*
* @return void
*/
protected function mapApiRoutes()
{
Route::prefix('api')
->middleware('api')
->namespace($this->moduleNamespace)
->group(module_path('Licensing', '/Routes/api.php'));
}
}
@@ -0,0 +1,9 @@
@props(['title' => null])
@extends('layouts.app')
@section('title', $title ?? config('app.name'))
@section('content')
{{ $slot }}
@endsection
@@ -18,3 +18,6 @@ To activate:
@endif
Keep this key private.
DOWNLOAD SONARDESK
{{ $downloadUrl }}
@@ -13,6 +13,7 @@
<ol style="padding-left:22px;line-height:1.8;margin-top:0"><li>Open SonarDesk on your Mac.</li><li>Open <strong>Settings → Licence</strong>.</li><li>Paste the licence key above and select <strong>Activate</strong>.</li></ol>
@if($expiresAt)<p style="line-height:1.6">Current entitlement period: <strong>{{ $expiresAt->format('j M Y') }}</strong>.</p>@endif
@if($portalUrl)<p style="margin:24px 0"><a href="{{ $portalUrl }}" style="display:inline-block;background:#2563eb;color:#fff;text-decoration:none;padding:12px 18px;border-radius:8px;font-weight:600">Manage your licence</a></p>@endif
<p style="margin:24px 0"><a href="{{ $downloadUrl }}" style="display:inline-block;background:#0f172a;color:#ffffff;text-decoration:none;font-weight:700;padding:12px 18px;border-radius:8px">Download SonarDesk</a></p>
<p style="margin:22px 0 0;color:#64748b;font-size:13px;line-height:1.6">Keep this key private. If you did not make this purchase, contact SonarDesk support.</p>
</td></tr></table>
</td></tr></table>
@@ -0,0 +1,9 @@
@extends('licensing::layouts.master')
@section('content')
<h1>Hello World</h1>
<p>
This view is loaded from module: {!! config('licensing.name') !!}
</p>
@endsection
@@ -0,0 +1,19 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Module Licensing</title>
{{-- Laravel Mix - CSS File --}}
{{-- <link rel="stylesheet" href="{{ mix('css/licensing.css') }}"> --}}
</head>
<body>
@yield('content')
{{-- Laravel Mix - JS File --}}
{{-- <script src="{{ mix('js/licensing.js') }}"></script> --}}
</body>
</html>
View File
+12
View File
@@ -0,0 +1,12 @@
<?php
use Illuminate\Support\Facades\Route;
use Modules\Licensing\Http\Controllers\Api\LicenseActivationController;
use Modules\Licensing\Http\Controllers\Api\PaymentWebhookController;
Route::prefix('v1')->group(function (): void {
Route::post('/activate', [LicenseActivationController::class, 'activate'])->middleware('throttle:license-activation');
Route::post('/validate', [LicenseActivationController::class, 'validateInstallation'])->middleware('throttle:license-activation');
Route::post('/deactivate', [LicenseActivationController::class, 'deactivate'])->middleware('throttle:license-activation');
Route::post('/webhooks/{provider}', PaymentWebhookController::class)->whereIn('provider', ['paddle', 'lemon-squeezy']);
});
+13
View File
@@ -0,0 +1,13 @@
<?php
use Illuminate\Support\Facades\Route;
use Modules\Licensing\Http\Controllers\Portal\PortalController;
Route::middleware(['auth', 'verified'])->prefix('portal')->name('portal.')->group(function (): void {
Route::get('/', [PortalController::class, 'index'])->name('index');
Route::get('/licences/{license}', [PortalController::class, 'show'])->name('show');
Route::post('/licences/{license}/upgrade', [PortalController::class, 'upgrade'])->middleware('throttle:5,1')->name('upgrade');
Route::delete('/licences/{license}/subscription', [PortalController::class, 'cancel'])->middleware('throttle:5,1')->name('cancel');
Route::post('/licences/{license}/resend', [PortalController::class, 'resend'])->middleware('throttle:3,10')->name('resend');
Route::delete('/licences/{license}/activations/{activation}', [PortalController::class, 'deactivate'])->name('deactivate');
});
@@ -1,8 +1,8 @@
<?php
namespace App\Services\Licensing;
namespace Modules\Licensing\Services;
use App\Models\LicenseDeliveryOutbox;
use Modules\Licensing\Models\LicenseDeliveryOutbox;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Mail;
@@ -38,9 +38,10 @@ final class LicenseDeliveryService
'licenseKey' => $plain,
'expiresAt' => $license->expires_at,
'portalUrl' => config('sonardesk.portal_url') ?: url('/portal'),
'downloadUrl' => route('release'),
];
Mail::send(['html' => 'emails.license-key', 'text' => 'emails.license-key-text'], $data, function ($message) use ($recipient): void {
Mail::send(['html' => 'licensing::emails.license-key', 'text' => 'licensing::emails.license-key-text'], $data, function ($message) use ($recipient): void {
$message->to($recipient)->subject('Your SonarDesk licence key');
});
@@ -1,10 +1,10 @@
<?php
namespace App\Services\Licensing;
namespace Modules\Licensing\Services;
use App\Models\License;
use App\Models\LicenseDeliveryOutbox;
use App\Models\LicenseProduct;
use Modules\Licensing\Models\License;
use Modules\Licensing\Models\LicenseDeliveryOutbox;
use Modules\Licensing\Models\LicenseProduct;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
@@ -1,6 +1,6 @@
<?php
namespace App\Services\Licensing;
namespace Modules\Licensing\Services;
final class LicenseKey
{
@@ -1,8 +1,8 @@
<?php
namespace App\Services\Licensing;
namespace Modules\Licensing\Services;
use App\Models\License;
use Modules\Licensing\Models\License;
use Carbon\CarbonInterface;
use RuntimeException;
@@ -1,6 +1,6 @@
<?php
namespace App\Services\Licensing;
namespace Modules\Licensing\Services;
use RuntimeException;
@@ -14,10 +14,11 @@ final class LicenseTokenVerifier
}
$payload = $this->decode($parts[1]);
$signature = $this->decode($parts[2]);
$public = base64_decode((string) config('sonardesk.public_key'), true);
if ($public === false || strlen($public) !== SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES) {
throw new RuntimeException('Server licence public key is invalid.');
}
// Derive the verification key from the same private seed used by LicenseSigner.
// Keeping a separate SONARDESK_LICENSE_PUBLIC_KEY allowed the two keys to drift:
// activation would sign a perfectly valid token with the new private key, then
// /validate would reject that same token using a stale public key.
$public = $this->publicKeyFromPrivateSeed();
if (! sodium_crypto_sign_verify_detached($signature, $payload, $public)) {
throw new RuntimeException('Licence token signature is invalid.');
}
@@ -26,6 +27,23 @@ final class LicenseTokenVerifier
return is_array($decoded) ? $decoded : throw new RuntimeException('Licence token payload is invalid.');
}
private function publicKeyFromPrivateSeed(): string
{
$path = config('sonardesk.private_key_path');
if (! $path || ! is_file($path)) {
throw new RuntimeException('SONARDESK_LICENSE_PRIVATE_KEY_PATH is not configured or does not exist.');
}
$seed = base64_decode(trim((string) file_get_contents($path)), true);
if ($seed === false || strlen($seed) !== SODIUM_CRYPTO_SIGN_SEEDBYTES) {
throw new RuntimeException('The SonarDesk private key must be a Base64-encoded 32-byte Ed25519 seed.');
}
$pair = sodium_crypto_sign_seed_keypair($seed);
return sodium_crypto_sign_publickey($pair);
}
private function decode(string $value): string
{
$value = strtr($value, '-_', '+/');
View File
+26
View File
@@ -0,0 +1,26 @@
<?php
namespace Modules\Licensing\Support;
class ModuleInfo
{
protected static string $moduleName = 'Licensing';
/**
* defines the Module Name
* @return string
*/
public static function name(): string
{
return static::$moduleName;
}
/**
* define the lowercase version
* @return string
*/
public static function nameLower(): string
{
return strtolower(static::$moduleName);
}
}
View File
View File

Some files were not shown because too many files have changed in this diff Show More