plugin(collab-buckets): collaborative buckets via relay
End-to-end shared buckets between relay tenants. Bucket metadata + members sync through new relay routes (collab-buckets, collab-cards, collab-locks); card content rides the existing inter-tenant encryption hop. Edit locks, ownership transfer, LWW conflict stashing, undo for local-bucket destructive actions, "Make collaborative…" upgrade path, and a resilient outbox for relay-down create attempts. See plugins/collab-buckets/README.md and TODO.md for the full picture. Core hooks added so the plugin can integrate without monkey-patching: - buckets.js context menu: collab-aware rename/color/delete + Members & owner / Make collaborative entries - editor.js dispatches hyprcrd:editor-open / hyprcrd:editor-close for the per-card edit-lock heartbeat - app.js exposes window.state for the plugin's MutationObserver - index.php POST/PATCH/DELETE on /api/buckets refuse to mutate collab buckets directly (must go through the relay) - Database.php adds buckets.collab_uid column + unique partial index - import handler now restores color and collab_uid (was silently dropping color, which caused the test runner's auto-restore to wipe custom bucket colors) - relay bootstrap creates collab_buckets, collab_bucket_members, collab_cards, collab_card_locks tables and prunes tombstones / expired locks on every request Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
a29708df85
commit
26ffa0e71f
16 files changed
+3017
-13
No files matched your search
@@ -0,0 +1,167 @@
|
||||
<?php
|
||||
// Collab card routes (Phase 3):
|
||||
// POST /api/collab-cards upsert a card in a collab bucket
|
||||
// GET /api/collab-cards?since=<ts> pull deltas since a timestamp
|
||||
// DELETE /api/collab-cards/{bucket}/{card} tombstone a card
|
||||
//
|
||||
// Encryption hop (same pattern as chat.php):
|
||||
// POST: arrives encrypted with the sender's client secret → relay
|
||||
// decrypts with that secret (via masterDecrypt of their
|
||||
// secret_encrypted) → re-encrypts under the inter-tenant key →
|
||||
// stored at rest.
|
||||
// GET: for each row visible to the caller, decrypt from inter-tenant
|
||||
// key → re-encrypt with the recipient's client secret → return.
|
||||
//
|
||||
// Membership check: every operation requires the caller to be a current
|
||||
// member of the bucket_uid referenced. Drops silently when the caller
|
||||
// leaves or is kicked.
|
||||
|
||||
if (!defined('RELAY_BOOTSTRAPPED')) { http_response_code(404); exit; }
|
||||
|
||||
$clientTenant = $clientTenant ?? authClient($db);
|
||||
|
||||
/** Is $tenantId a member of $bucketUid right now? */
|
||||
function collabCardsIsMember(PDO $db, string $bucketUid, int $tenantId): bool {
|
||||
$stmt = $db->prepare('SELECT 1 FROM collab_bucket_members WHERE bucket_uid = :b AND tenant_id = :t');
|
||||
$stmt->execute(['b' => $bucketUid, 't' => $tenantId]);
|
||||
return (bool)$stmt->fetchColumn();
|
||||
}
|
||||
|
||||
// ── POST: upsert a card ──────────────────────────────────────────
|
||||
|
||||
if ($route === '/api/collab-cards' && $method === 'POST') {
|
||||
if (!$clientTenant) jsonResponse(['error' => 'unauthorized'], 401);
|
||||
if (isRateLimited($db, 'collab-cards-post', 240)) jsonResponse(['error' => 'rate limited'], 429);
|
||||
$input = json_decode(file_get_contents('php://input'), true) ?: [];
|
||||
$bucketUid = trim((string)($input['bucket_uid'] ?? ''));
|
||||
$cardUid = trim((string)($input['card_uid'] ?? ''));
|
||||
$encEnvelope = (string)($input['payload'] ?? '');
|
||||
if ($bucketUid === '' || $cardUid === '' || $encEnvelope === '') {
|
||||
jsonResponse(['error' => 'bucket_uid, card_uid, payload required'], 400);
|
||||
}
|
||||
if (!collabCardsIsMember($db, $bucketUid, (int)$clientTenant['id'])) {
|
||||
jsonResponse(['error' => 'not a member of this bucket'], 403);
|
||||
}
|
||||
if (empty($clientTenant['secret_encrypted'])) {
|
||||
jsonResponse(['error' => 'sender has no client secret set — log into the relay UI and configure one in your account'], 400);
|
||||
}
|
||||
$senderSecret = masterDecrypt($clientTenant['secret_encrypted'], $MASTER_KEY);
|
||||
if (!$senderSecret) jsonResponse(['error' => 'sender secret unavailable'], 500);
|
||||
$interKey = getInterTenantKey($db, $MASTER_KEY);
|
||||
if (!$interKey) jsonResponse(['error' => 'relay super-shared key not set — admin must complete setup'], 500);
|
||||
|
||||
$plain = clientDecrypt($encEnvelope, $senderSecret);
|
||||
if ($plain === '') jsonResponse(['error' => 'payload decrypt failed (sender secret mismatch?)'], 400);
|
||||
$stored = clientEncrypt($plain, $interKey);
|
||||
|
||||
// LWW: upsert with server-generated updated_at so clients all agree on
|
||||
// the authoritative order (client clocks drift, server clock is the tie-
|
||||
// breaker). Last writer wins.
|
||||
$db->prepare('
|
||||
INSERT INTO collab_cards (bucket_uid, card_uid, author_username, payload, updated_at, deleted)
|
||||
VALUES (:b, :c, :a, :p, datetime(\'now\'), 0)
|
||||
ON CONFLICT(bucket_uid, card_uid) DO UPDATE SET
|
||||
author_username = excluded.author_username,
|
||||
payload = excluded.payload,
|
||||
updated_at = excluded.updated_at,
|
||||
deleted = 0
|
||||
')->execute([
|
||||
'b' => $bucketUid,
|
||||
'c' => $cardUid,
|
||||
'a' => $clientTenant['username'],
|
||||
'p' => $stored,
|
||||
]);
|
||||
|
||||
// Return the row's updated_at so the client can track what it pushed
|
||||
$row = $db->prepare('SELECT updated_at FROM collab_cards WHERE bucket_uid = :b AND card_uid = :c');
|
||||
$row->execute(['b' => $bucketUid, 'c' => $cardUid]);
|
||||
jsonResponse(['ok' => true, 'updated_at' => $row->fetchColumn()]);
|
||||
}
|
||||
|
||||
// ── GET: pull deltas since a given timestamp ─────────────────────
|
||||
|
||||
if ($route === '/api/collab-cards' && $method === 'GET') {
|
||||
if (!$clientTenant) jsonResponse(['error' => 'unauthorized'], 401);
|
||||
if (isRateLimited($db, 'collab-cards-get', 120)) jsonResponse(['error' => 'rate limited'], 429);
|
||||
if (empty($clientTenant['secret_encrypted'])) {
|
||||
jsonResponse(['error' => 'no client secret set — log into the relay UI and configure one in your account'], 400);
|
||||
}
|
||||
$since = trim((string)($_GET['since'] ?? ''));
|
||||
|
||||
$recipientSecret = masterDecrypt($clientTenant['secret_encrypted'], $MASTER_KEY);
|
||||
if (!$recipientSecret) jsonResponse(['error' => 'recipient secret unavailable'], 500);
|
||||
$interKey = getInterTenantKey($db, $MASTER_KEY);
|
||||
if (!$interKey) jsonResponse(['error' => 'relay super-shared key not set'], 500);
|
||||
|
||||
// Join to membership so only buckets the caller is in right now are returned
|
||||
$sql = '
|
||||
SELECT c.bucket_uid, c.card_uid, c.author_username, c.payload, c.updated_at, c.deleted
|
||||
FROM collab_cards c
|
||||
INNER JOIN collab_bucket_members m ON m.bucket_uid = c.bucket_uid
|
||||
WHERE m.tenant_id = :tid
|
||||
';
|
||||
$params = ['tid' => $clientTenant['id']];
|
||||
if ($since !== '') {
|
||||
$sql .= ' AND c.updated_at > :since';
|
||||
$params['since'] = $since;
|
||||
}
|
||||
$sql .= ' ORDER BY c.updated_at ASC LIMIT 1000';
|
||||
$stmt = $db->prepare($sql);
|
||||
$stmt->execute($params);
|
||||
$rows = $stmt->fetchAll();
|
||||
|
||||
$out = [];
|
||||
$maxTs = $since;
|
||||
foreach ($rows as $row) {
|
||||
// Tombstones don't need payload — they just signal "delete locally"
|
||||
if ((int)$row['deleted'] === 1) {
|
||||
$out[] = [
|
||||
'bucket_uid' => $row['bucket_uid'],
|
||||
'card_uid' => $row['card_uid'],
|
||||
'author_username' => $row['author_username'],
|
||||
'updated_at' => $row['updated_at'],
|
||||
'deleted' => true,
|
||||
];
|
||||
} else {
|
||||
$plain = clientDecrypt($row['payload'] ?? '', $interKey);
|
||||
$reEncrypted = clientEncrypt($plain, $recipientSecret);
|
||||
$out[] = [
|
||||
'bucket_uid' => $row['bucket_uid'],
|
||||
'card_uid' => $row['card_uid'],
|
||||
'author_username' => $row['author_username'],
|
||||
'payload' => $reEncrypted,
|
||||
'updated_at' => $row['updated_at'],
|
||||
'deleted' => false,
|
||||
];
|
||||
}
|
||||
if ($row['updated_at'] > $maxTs) $maxTs = $row['updated_at'];
|
||||
}
|
||||
jsonResponse(['ok' => true, 'cards' => $out, 'max_updated_at' => $maxTs]);
|
||||
}
|
||||
|
||||
// ── DELETE: tombstone a card ─────────────────────────────────────
|
||||
|
||||
if (preg_match('#^/api/collab-cards/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$#', $route, $m) && $method === 'DELETE') {
|
||||
if (!$clientTenant) jsonResponse(['error' => 'unauthorized'], 401);
|
||||
$bucketUid = $m[1];
|
||||
$cardUid = $m[2];
|
||||
if (!collabCardsIsMember($db, $bucketUid, (int)$clientTenant['id'])) {
|
||||
jsonResponse(['error' => 'not a member of this bucket'], 403);
|
||||
}
|
||||
// Mark as tombstone rather than actually deleting. Late pollers see it,
|
||||
// bootstrap.php cleanup prunes after 7 days.
|
||||
$db->prepare('
|
||||
INSERT INTO collab_cards (bucket_uid, card_uid, author_username, payload, updated_at, deleted)
|
||||
VALUES (:b, :c, :a, \'\', datetime(\'now\'), 1)
|
||||
ON CONFLICT(bucket_uid, card_uid) DO UPDATE SET
|
||||
author_username = excluded.author_username,
|
||||
payload = \'\',
|
||||
updated_at = datetime(\'now\'),
|
||||
deleted = 1
|
||||
')->execute([
|
||||
'b' => $bucketUid,
|
||||
'c' => $cardUid,
|
||||
'a' => $clientTenant['username'],
|
||||
]);
|
||||
jsonResponse(['ok' => true]);
|
||||
}
|
||||
Reference in new issue
Block a user