v2.0.12 — support channel: relay + hyprcrd plugin
Central support desk for the Oumta project. Tickets arrive through a
self-hostable support-relay (public form, SMTP out), hyprcrd pulls
them in as cards, replies go back out through the relay, and KB
fragments are plain hyprcrd cards so the board + search + tags
machinery handles them for free.
support-relay/ (standalone PHP/SQLite service)
- Public form + submit endpoint with IP rate-limit, honeypot, and an
email-matched reply path so users can follow up by typing their
OUMTA-n issue id — mismatched email falls back to a fresh ticket
so a hostile submitter can't hijack someone else's thread.
- One-shot setup wizard configures branding, issue-id prefix, public
URL, mail footer template, SMTP creds (stored AES-256-GCM at rest),
and generates the X-Support-Key API token shown exactly once.
- Hyprcrd-facing API: GET /api/hyprcrd/tickets?since=<iso>, POST
…/reply (sends via SMTP, flips status to answered), PATCH
…/status, DELETE, GET /ping, plus GET/POST /api/hyprcrd/settings
exposing brand/public_url/mail_footer for post-setup edits.
- Minimal dependency-free SMTP client covering STARTTLS/TLS/none,
AUTH LOGIN, RFC 2047 subject encoding, dot-stuffing. Extended to
emit multipart/alternative (plain+HTML) + multipart/related so
outbound mails carry the branded logo via Content-ID embedding;
plain-text fallback stays intact for older clients.
- Mail footer template supports {brand}, {issue_id}, {public_url}
placeholders. Lines with an empty placeholder are dropped, so the
"Reply via …" line vanishes cleanly when no public URL is set.
- Favicon on all public pages. Logo (SVG by default, PNG preferred
when both exist) picked up from logo2026col.* at send time.
- Docker: Dockerfile + docker-compose.yml for a stand-alone test
container, plus a support-relay service in the main compose
(profile "support") so hyprcrd can reach it at http://support-relay
without host-networking shenanigans.
public/plugins/support (hyprcrd client)
- Full-screen Support overlay: ticket list (status-filterable),
active ticket thread, reply composer with KB-fragment search +
click-to-insert, "Save as fragment" button, "Close ticket" shortcut.
- KB fragments are regular cards in a configurable bucket. The
composer just adds a fast search-and-insert path on top.
- Sync-tick hook auto-polls the relay alongside the existing CalDAV
+ relay-mail cycle.
- Settings tab in the main overlay: relay URL, API key, inbox / KB
bucket pickers, connection test, and a "Relay config" subsection
that round-trips to /api/hyprcrd/settings so the mail footer and
branding can be edited without touching the relay's DB.
- Local cache tables support_tickets + support_replies mirror the
relay's authoritative data keyed by relay_id.
Tooling
- dev.sh now opts into both relay + support profiles.
- dev-down.sh wipes support-relay volumes and bind-mount data for a
clean re-setup. Hyprcrd + relay data is preserved.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
2d58cd993e
commit
7bce6a3a36
33 files changed
+2915
-10
No files matched your search
@@ -0,0 +1,139 @@
|
||||
<?php
|
||||
// hyprcrd-facing API. Pulls new/updated tickets, pushes outbound replies
|
||||
// (which the relay then sends via SMTP), syncs status changes. Shared
|
||||
// secret auth via X-Support-Key.
|
||||
|
||||
if (!defined('SUPPORT_RELAY_BOOTSTRAPPED')) { http_response_code(404); exit; }
|
||||
|
||||
// All /api/hyprcrd/* paths require the API key. Guard once up front.
|
||||
if (str_starts_with($route, '/api/hyprcrd/')) {
|
||||
if ($isSetup) supportRelayJson(['error' => 'relay not configured'], 503);
|
||||
if (!supportRelayApiAuth($db)) supportRelayJson(['error' => 'unauthorized'], 401);
|
||||
}
|
||||
|
||||
// Poll: tickets updated after `since` (ISO timestamp). Client stores
|
||||
// the max updated_at it sees and sends that as `since` next time.
|
||||
if ($route === '/api/hyprcrd/tickets' && $method === 'GET') {
|
||||
$since = trim((string)($_GET['since'] ?? ''));
|
||||
$sql = 'SELECT * FROM tickets';
|
||||
$params = [];
|
||||
if ($since !== '') { $sql .= ' WHERE updated_at > :s'; $params['s'] = $since; }
|
||||
$sql .= ' ORDER BY updated_at ASC LIMIT 500';
|
||||
$stmt = $db->prepare($sql);
|
||||
$stmt->execute($params);
|
||||
$tickets = $stmt->fetchAll();
|
||||
$out = [];
|
||||
$ids = [];
|
||||
foreach ($tickets as $t) {
|
||||
$t['issue_id'] = supportRelayIssueId($db, (int)$t['id']);
|
||||
$out[] = $t;
|
||||
$ids[] = (int)$t['id'];
|
||||
}
|
||||
$replies = [];
|
||||
if ($ids) {
|
||||
$ph = implode(',', array_fill(0, count($ids), '?'));
|
||||
$rstmt = $db->prepare("SELECT id, ticket_id, direction, body, sent_at, created_at FROM replies WHERE ticket_id IN ($ph) ORDER BY ticket_id, created_at");
|
||||
$rstmt->execute($ids);
|
||||
foreach ($rstmt->fetchAll() as $r) {
|
||||
$tid = (int)$r['ticket_id'];
|
||||
if (!isset($replies[$tid])) $replies[$tid] = [];
|
||||
$replies[$tid][] = $r;
|
||||
}
|
||||
}
|
||||
foreach ($out as &$t) {
|
||||
$t['replies'] = $replies[(int)$t['id']] ?? [];
|
||||
}
|
||||
unset($t);
|
||||
supportRelayJson(['tickets' => $out]);
|
||||
}
|
||||
|
||||
// Push an outgoing reply. Relay generates the RFC 5322 message, sends
|
||||
// via SMTP, logs the reply. Status flips to "answered" on success.
|
||||
if (preg_match('#^/api/hyprcrd/tickets/(\d+)/reply$#', $route, $m) && $method === 'POST') {
|
||||
$id = (int)$m[1];
|
||||
$input = json_decode(file_get_contents('php://input'), true) ?: [];
|
||||
$body = trim((string)($input['body'] ?? ''));
|
||||
if ($body === '') supportRelayJson(['error' => 'body required'], 400);
|
||||
|
||||
$t = $db->prepare('SELECT * FROM tickets WHERE id = :id');
|
||||
$t->execute(['id' => $id]);
|
||||
$ticket = $t->fetch();
|
||||
if (!$ticket) supportRelayJson(['error' => 'ticket not found'], 404);
|
||||
|
||||
$smtp = supportRelaySmtpConfig($db, $MASTER_KEY);
|
||||
if ($smtp['host'] === '' || $smtp['from'] === '') supportRelayJson(['error' => 'SMTP not configured'], 500);
|
||||
$brand = supportRelayGet($db, 'brand', 'Support');
|
||||
$issueId = supportRelayIssueId($db, $id);
|
||||
$subject = ($ticket['subject'] ?: '(no subject)') . ' [' . $issueId . ']';
|
||||
$message = $body . "\n\n" . supportRelayRenderFooter($db, $issueId);
|
||||
|
||||
$extraHeaders = ['Subject' => $subject, 'X-Support-Ticket' => $issueId];
|
||||
if (!empty($ticket['message_id'])) $extraHeaders['In-Reply-To'] = '<' . $ticket['message_id'] . '>';
|
||||
|
||||
$client = new SmtpClient($smtp);
|
||||
$res = $client->send(
|
||||
$ticket['email'], $smtp['from_name'], $smtp['from'], $message, $extraHeaders,
|
||||
supportRelayMailOptions($message, $brand)
|
||||
);
|
||||
if (!$res['ok']) supportRelayJson(['error' => 'send failed: ' . $res['error']], 500);
|
||||
|
||||
$db->prepare('INSERT INTO replies (ticket_id, direction, body, sent_at) VALUES (:t, "out", :b, datetime("now"))')
|
||||
->execute(['t' => $id, 'b' => $body]);
|
||||
$updateMid = empty($ticket['message_id']) && !empty($res['message_id']);
|
||||
if ($updateMid) {
|
||||
$db->prepare('UPDATE tickets SET status = "answered", updated_at = datetime("now"), last_reply_at = datetime("now"), message_id = :mid WHERE id = :id')
|
||||
->execute(['id' => $id, 'mid' => $res['message_id']]);
|
||||
} else {
|
||||
$db->prepare('UPDATE tickets SET status = "answered", updated_at = datetime("now"), last_reply_at = datetime("now") WHERE id = :id')
|
||||
->execute(['id' => $id]);
|
||||
}
|
||||
supportRelayJson(['ok' => true, 'message_id' => $res['message_id'] ?? null]);
|
||||
}
|
||||
|
||||
// Status change (open / answered / closed)
|
||||
if (preg_match('#^/api/hyprcrd/tickets/(\d+)/status$#', $route, $m) && $method === 'PATCH') {
|
||||
$id = (int)$m[1];
|
||||
$input = json_decode(file_get_contents('php://input'), true) ?: [];
|
||||
$status = trim((string)($input['status'] ?? ''));
|
||||
if (!in_array($status, ['open', 'answered', 'closed'], true)) supportRelayJson(['error' => 'invalid status'], 400);
|
||||
$db->prepare('UPDATE tickets SET status = :s, updated_at = datetime("now") WHERE id = :id')
|
||||
->execute(['s' => $status, 'id' => $id]);
|
||||
supportRelayJson(['ok' => true]);
|
||||
}
|
||||
|
||||
// Delete a ticket — rarely needed but useful for cleanup
|
||||
if (preg_match('#^/api/hyprcrd/tickets/(\d+)$#', $route, $m) && $method === 'DELETE') {
|
||||
$id = (int)$m[1];
|
||||
$db->prepare('DELETE FROM tickets WHERE id = :id')->execute(['id' => $id]);
|
||||
supportRelayJson(['ok' => true]);
|
||||
}
|
||||
|
||||
// Basic health check so hyprcrd can verify connectivity during settings
|
||||
// config without pulling a real payload.
|
||||
if ($route === '/api/hyprcrd/ping' && $method === 'GET') {
|
||||
supportRelayJson(['ok' => true, 'brand' => supportRelayGet($db, 'brand', 'Support')]);
|
||||
}
|
||||
|
||||
// Subset of editable relay settings that the admin (via hyprcrd) is
|
||||
// allowed to change post-setup. SMTP credentials + API key stay locked
|
||||
// to the setup wizard — editing those from an authenticated hyprcrd is
|
||||
// out of scope for V1 and would need stricter handling.
|
||||
if ($route === '/api/hyprcrd/settings' && $method === 'GET') {
|
||||
supportRelayJson([
|
||||
'brand' => supportRelayGet($db, 'brand', 'Support'),
|
||||
'public_url' => supportRelayGet($db, 'public_url', ''),
|
||||
'mail_footer' => supportRelayGet($db, 'mail_footer', '') ?: SUPPORT_RELAY_FOOTER_DEFAULT,
|
||||
'default_footer' => SUPPORT_RELAY_FOOTER_DEFAULT,
|
||||
]);
|
||||
}
|
||||
if ($route === '/api/hyprcrd/settings' && $method === 'POST') {
|
||||
$input = json_decode(file_get_contents('php://input'), true) ?: [];
|
||||
if (array_key_exists('brand', $input)) supportRelaySet($db, 'brand', trim((string)$input['brand']) ?: 'Support');
|
||||
if (array_key_exists('public_url', $input)) supportRelaySet($db, 'public_url', rtrim((string)$input['public_url'], '/'));
|
||||
if (array_key_exists('mail_footer', $input)) {
|
||||
$v = (string)$input['mail_footer'];
|
||||
// Empty string falls back to the built-in default at render time.
|
||||
supportRelaySet($db, 'mail_footer', $v === '' ? null : $v);
|
||||
}
|
||||
supportRelayJson(['ok' => true]);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
<?php
|
||||
// Public-facing routes used by the form JS: submit a ticket, check
|
||||
// ticket status. No auth — rate-limited + honeypot + issue-ID-email
|
||||
// guard against abuse.
|
||||
|
||||
if (!defined('SUPPORT_RELAY_BOOTSTRAPPED')) { http_response_code(404); exit; }
|
||||
|
||||
if ($route === '/api/submit' && $method === 'POST') {
|
||||
if ($isSetup) supportRelayJson(['error' => 'relay not configured'], 503);
|
||||
if (supportRelayRateLimited($db, 'submit', 5, 60)) supportRelayJson(['error' => 'Too many requests. Try again in an hour.'], 429);
|
||||
|
||||
$input = json_decode(file_get_contents('php://input'), true) ?: [];
|
||||
// Honeypot: a hidden field browsers won't fill but bots will. If it's
|
||||
// set, pretend success and drop the submission silently.
|
||||
if (!empty($input['website'])) supportRelayJson(['ok' => true, 'issue_id' => 'OUMTA-0']);
|
||||
|
||||
$email = trim((string)($input['email'] ?? ''));
|
||||
$subject = trim((string)($input['subject'] ?? ''));
|
||||
$body = trim((string)($input['body'] ?? ''));
|
||||
$issueHint = trim((string)($input['issue_id'] ?? ''));
|
||||
|
||||
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) supportRelayJson(['error' => 'valid email required'], 400);
|
||||
if (mb_strlen($body) < 10) supportRelayJson(['error' => 'message too short'], 400);
|
||||
if (mb_strlen($body) > 10000) supportRelayJson(['error' => 'message too long (max 10k)'], 400);
|
||||
if (mb_strlen($subject) > 200) supportRelayJson(['error' => 'subject too long'], 400);
|
||||
|
||||
// If the user claims to reply to an existing ticket, verify the email
|
||||
// matches before appending. Mismatch → treat it as a brand-new ticket
|
||||
// so we don't ghost-route hostile submissions to someone else's thread.
|
||||
$targetId = $issueHint !== '' ? supportRelayParseIssueId($db, $issueHint) : null;
|
||||
if ($targetId) {
|
||||
$t = $db->prepare('SELECT id, email, subject FROM tickets WHERE id = :id');
|
||||
$t->execute(['id' => $targetId]);
|
||||
$row = $t->fetch();
|
||||
if ($row && strtolower($row['email']) === strtolower($email)) {
|
||||
$db->prepare('INSERT INTO replies (ticket_id, direction, body) VALUES (:t, "in", :b)')
|
||||
->execute(['t' => $targetId, 'b' => $body]);
|
||||
$db->prepare('UPDATE tickets SET status = "open", updated_at = datetime("now"), last_reply_at = datetime("now") WHERE id = :id')
|
||||
->execute(['id' => $targetId]);
|
||||
supportRelayJson([
|
||||
'ok' => true,
|
||||
'issue_id' => supportRelayIssueId($db, $targetId),
|
||||
'appended' => true,
|
||||
]);
|
||||
}
|
||||
// Wrong email → fall through to new-ticket path. Don't leak that
|
||||
// the id existed.
|
||||
}
|
||||
|
||||
// New ticket
|
||||
$db->prepare('INSERT INTO tickets (email, subject, body, status) VALUES (:e, :s, :b, "open")')
|
||||
->execute(['e' => strtolower($email), 's' => $subject, 'b' => $body]);
|
||||
$id = (int)$db->lastInsertId();
|
||||
$db->prepare('INSERT INTO replies (ticket_id, direction, body) VALUES (:t, "in", :b)')
|
||||
->execute(['t' => $id, 'b' => $body]);
|
||||
$issueId = supportRelayIssueId($db, $id);
|
||||
|
||||
// Confirmation mail — best-effort, swallow SMTP failures so the user
|
||||
// still gets their issue id even if the mail gateway is misbehaving.
|
||||
$smtp = supportRelaySmtpConfig($db, $MASTER_KEY);
|
||||
if ($smtp['host'] !== '' && $smtp['from'] !== '') {
|
||||
$brand = supportRelayGet($db, 'brand', 'Support');
|
||||
$body = "Hi,\n\nwe received your support request.\n\nIssue: " . $issueId
|
||||
. "\nSubject: " . ($subject ?: '(no subject)')
|
||||
. "\n\n" . supportRelayRenderFooter($db, $issueId);
|
||||
$client = new SmtpClient($smtp);
|
||||
$brandName = supportRelayGet($db, 'brand', 'Support');
|
||||
$client->send(
|
||||
$email, $smtp['from_name'], $smtp['from'], $body,
|
||||
['Subject' => '[' . $issueId . '] ' . ($subject !== '' ? $subject : 'Support request received')],
|
||||
supportRelayMailOptions($body, $brandName)
|
||||
);
|
||||
}
|
||||
|
||||
supportRelayJson(['ok' => true, 'issue_id' => $issueId]);
|
||||
}
|
||||
|
||||
if (preg_match('#^/api/ticket/([A-Za-z0-9-]+)$#', $route, $m) && $method === 'GET') {
|
||||
if ($isSetup) supportRelayJson(['error' => 'relay not configured'], 503);
|
||||
$email = trim((string)($_GET['email'] ?? ''));
|
||||
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) supportRelayJson(['error' => 'email required'], 400);
|
||||
$id = supportRelayParseIssueId($db, $m[1]);
|
||||
if (!$id) supportRelayJson(['error' => 'not found'], 404);
|
||||
$t = $db->prepare('SELECT id, email, subject, status, created_at, updated_at FROM tickets WHERE id = :id');
|
||||
$t->execute(['id' => $id]);
|
||||
$row = $t->fetch();
|
||||
if (!$row || strtolower($row['email']) !== strtolower($email)) supportRelayJson(['error' => 'not found'], 404);
|
||||
// Public status view: only the outbound replies (what we answered).
|
||||
// Internal notes / inbound replay stays hidden.
|
||||
$reps = $db->prepare('SELECT body, created_at FROM replies WHERE ticket_id = :id AND direction = "out" ORDER BY created_at ASC');
|
||||
$reps->execute(['id' => $id]);
|
||||
supportRelayJson([
|
||||
'issue_id' => supportRelayIssueId($db, $id),
|
||||
'subject' => $row['subject'],
|
||||
'status' => $row['status'],
|
||||
'created_at' => $row['created_at'],
|
||||
'updated_at' => $row['updated_at'],
|
||||
'replies' => $reps->fetchAll(),
|
||||
]);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
// Non-API routes for the human-facing pages: the submit form at `/`,
|
||||
// the "check my ticket" status page at `/ticket/XXX`.
|
||||
|
||||
if (!defined('SUPPORT_RELAY_BOOTSTRAPPED')) { http_response_code(404); exit; }
|
||||
|
||||
if ($route === '/' || $route === '/index.php' || $route === '') {
|
||||
require __DIR__ . '/../../ui/form.php';
|
||||
exit;
|
||||
}
|
||||
|
||||
if (preg_match('#^/ticket/([A-Za-z0-9-]+)$#', $route, $m)) {
|
||||
// Render the public status view. Actual data comes via the JS call
|
||||
// to /api/ticket/{id}?email=… once the user types their email.
|
||||
require __DIR__ . '/../../ui/status.php';
|
||||
exit;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
// /api/setup — one-shot configuration on first install. After the admin
|
||||
// completes this form the API key becomes required for every /api/*
|
||||
// route and the setup endpoint returns 403. Designed to be impossible
|
||||
// to re-trigger without clearing `settings.setup_done` in the DB.
|
||||
|
||||
if (!defined('SUPPORT_RELAY_BOOTSTRAPPED')) { http_response_code(404); exit; }
|
||||
|
||||
if ($route === '/api/setup' && $method === 'POST') {
|
||||
if (!$isSetup) supportRelayJson(['error' => 'already configured'], 403);
|
||||
if (supportRelayRateLimited($db, 'setup', 10, 10)) supportRelayJson(['error' => 'too many attempts'], 429);
|
||||
|
||||
$input = json_decode(file_get_contents('php://input'), true) ?: [];
|
||||
// Required fields
|
||||
$brand = trim((string)($input['brand'] ?? 'Oumta Support'));
|
||||
$prefix = strtoupper(preg_replace('/[^A-Z0-9]/i', '', (string)($input['issue_prefix'] ?? 'OUMTA')));
|
||||
$publicUrl = rtrim((string)($input['public_url'] ?? ''), '/');
|
||||
$footer = trim((string)($input['mail_footer'] ?? ''));
|
||||
$smtpHost = trim((string)($input['smtp_host'] ?? ''));
|
||||
$smtpPort = (int)($input['smtp_port'] ?? 587);
|
||||
$smtpUser = trim((string)($input['smtp_user'] ?? ''));
|
||||
$smtpPw = (string)($input['smtp_password'] ?? '');
|
||||
$smtpFrom = trim((string)($input['smtp_from'] ?? ''));
|
||||
$smtpFromN = trim((string)($input['smtp_from_name'] ?? $brand));
|
||||
$smtpEnc = in_array($input['smtp_encryption'] ?? 'starttls', ['starttls', 'tls', 'none'], true)
|
||||
? $input['smtp_encryption'] : 'starttls';
|
||||
|
||||
if ($smtpHost === '') supportRelayJson(['error' => 'SMTP host required'], 400);
|
||||
if (!filter_var($smtpFrom, FILTER_VALIDATE_EMAIL)) supportRelayJson(['error' => 'SMTP from must be a valid email'], 400);
|
||||
if ($prefix === '' || strlen($prefix) > 12) supportRelayJson(['error' => 'issue prefix 1-12 chars, letters/digits only'], 400);
|
||||
|
||||
// Generate the API key now, show it back ONCE — admin copies it to
|
||||
// hyprcrd. A second request after setup can't re-read or rotate it
|
||||
// except through a re-install (clear setup_done). That's fine for a
|
||||
// single-user admin workflow.
|
||||
$apiKey = bin2hex(random_bytes(24));
|
||||
|
||||
supportRelaySet($db, 'brand', $brand);
|
||||
supportRelaySet($db, 'issue_prefix', $prefix);
|
||||
if ($publicUrl !== '') supportRelaySet($db, 'public_url', $publicUrl);
|
||||
if ($footer !== '') supportRelaySet($db, 'mail_footer', $footer);
|
||||
supportRelaySet($db, 'smtp_host', $smtpHost);
|
||||
supportRelaySet($db, 'smtp_port', (string)$smtpPort);
|
||||
supportRelaySet($db, 'smtp_user', $smtpUser);
|
||||
if ($smtpPw !== '') supportRelaySet($db, 'smtp_password', supportRelayEncrypt($smtpPw, $MASTER_KEY));
|
||||
supportRelaySet($db, 'smtp_from', $smtpFrom);
|
||||
supportRelaySet($db, 'smtp_from_name', $smtpFromN);
|
||||
supportRelaySet($db, 'smtp_encryption', $smtpEnc);
|
||||
supportRelaySet($db, 'api_key', $apiKey);
|
||||
supportRelaySet($db, 'setup_done', '1');
|
||||
|
||||
supportRelayJson(['ok' => true, 'api_key' => $apiKey]);
|
||||
}
|
||||
Reference in new issue
Block a user