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
@@ -181,6 +181,64 @@ $db->exec('CREATE TABLE IF NOT EXISTS chat_messages (
|
||||
)');
|
||||
$db->exec('CREATE INDEX IF NOT EXISTS idx_chat_recipient ON chat_messages(recipient_id, fetched, id)');
|
||||
|
||||
// Collaborative buckets: shared among multiple tenants. Each bucket has one
|
||||
// owner and a membership set. Buckets persist (not ephemeral) since they are
|
||||
// the container for ongoing collaboration — cleanup only when deleted.
|
||||
$db->exec('CREATE TABLE IF NOT EXISTS collab_buckets (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
uid TEXT UNIQUE NOT NULL,
|
||||
owner_id INTEGER NOT NULL,
|
||||
owner_username TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
color TEXT NOT NULL DEFAULT "#38bdf8",
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (owner_id) REFERENCES tenants(id) ON DELETE CASCADE
|
||||
)');
|
||||
$db->exec('CREATE TABLE IF NOT EXISTS collab_bucket_members (
|
||||
bucket_uid TEXT NOT NULL,
|
||||
tenant_id INTEGER NOT NULL,
|
||||
username TEXT NOT NULL,
|
||||
added_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (bucket_uid, tenant_id),
|
||||
FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE
|
||||
)');
|
||||
$db->exec('CREATE INDEX IF NOT EXISTS idx_collab_member_tenant ON collab_bucket_members(tenant_id, bucket_uid)');
|
||||
$db->exec('CREATE INDEX IF NOT EXISTS idx_collab_bucket_updated ON collab_buckets(updated_at)');
|
||||
|
||||
// Collab cards: the actual synced content, stored at-rest under the
|
||||
// inter-tenant key. Payload is an encrypted JSON blob containing title,
|
||||
// body, color, tags, due_date, position. Tombstoned rows (deleted=1)
|
||||
// survive for 7 days so late pollers see the deletion.
|
||||
$db->exec('CREATE TABLE IF NOT EXISTS collab_cards (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
bucket_uid TEXT NOT NULL,
|
||||
card_uid TEXT NOT NULL,
|
||||
author_username TEXT NOT NULL,
|
||||
payload TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
deleted INTEGER NOT NULL DEFAULT 0,
|
||||
UNIQUE (bucket_uid, card_uid)
|
||||
)');
|
||||
$db->exec('CREATE INDEX IF NOT EXISTS idx_collab_cards_bucket_updated ON collab_cards(bucket_uid, updated_at)');
|
||||
|
||||
// Phase 4: advisory edit locks on collab cards. A client that opens the
|
||||
// editor for a collab card heartbeats into this table every 30s with a
|
||||
// 60s TTL. Other clients poll the list and show a lock indicator on the
|
||||
// card. The lock is purely advisory — force-editing is still allowed and
|
||||
// LWW remains the authoritative conflict resolver.
|
||||
$db->exec('CREATE TABLE IF NOT EXISTS collab_card_locks (
|
||||
bucket_uid TEXT NOT NULL,
|
||||
card_uid TEXT NOT NULL,
|
||||
holder_id INTEGER NOT NULL,
|
||||
holder_username TEXT NOT NULL,
|
||||
acquired_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
expires_at TEXT NOT NULL,
|
||||
PRIMARY KEY (bucket_uid, card_uid, holder_id),
|
||||
FOREIGN KEY (holder_id) REFERENCES tenants(id) ON DELETE CASCADE
|
||||
)');
|
||||
$db->exec('CREATE INDEX IF NOT EXISTS idx_collab_card_locks_expires ON collab_card_locks(expires_at)');
|
||||
|
||||
$db->exec('CREATE TABLE IF NOT EXISTS sessions (
|
||||
id TEXT PRIMARY KEY,
|
||||
tenant_id INTEGER NOT NULL,
|
||||
@@ -200,6 +258,10 @@ $db->exec("DELETE FROM messages WHERE created_at < datetime('now', '-24 hours')"
|
||||
$db->exec("DELETE FROM attachments WHERE created_at < datetime('now', '-24 hours')");
|
||||
// Chat: 7 days, longer than card sync but still ephemeral
|
||||
$db->exec("DELETE FROM chat_messages WHERE created_at < datetime('now', '-7 days')");
|
||||
// Collab-card tombstones: 7 days so late pollers still see the delete.
|
||||
$db->exec("DELETE FROM collab_cards WHERE deleted = 1 AND updated_at < datetime('now', '-7 days')");
|
||||
// Collab-card locks: drop everything past its TTL on every request.
|
||||
$db->exec("DELETE FROM collab_card_locks WHERE expires_at < datetime('now')");
|
||||
$db->exec("DELETE FROM sessions WHERE expires_at < datetime('now')");
|
||||
$db->exec("DELETE FROM rate_limits WHERE attempted_at < datetime('now', '-5 minutes')");
|
||||
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
<?php
|
||||
// Collab bucket routes:
|
||||
// POST /api/collab-buckets create {uid, name, color, members: [usernames]}
|
||||
// GET /api/collab-buckets list buckets where the caller is a member
|
||||
// PATCH /api/collab-buckets/{uid} owner-only: update name / color / members
|
||||
// DELETE /api/collab-buckets/{uid} owner: delete bucket; non-owner: leave
|
||||
//
|
||||
// No body encryption on buckets — bucket metadata (name, color) is lightweight
|
||||
// shared data. Cards inside the buckets (Phase 3) follow the chat decrypt-
|
||||
// reencrypt-per-recipient pattern so content stays private on the relay.
|
||||
|
||||
if (!defined('RELAY_BOOTSTRAPPED')) { http_response_code(404); exit; }
|
||||
|
||||
$clientTenant = $clientTenant ?? authClient($db);
|
||||
|
||||
// ── POST: create ──────────────────────────────────────────────────
|
||||
|
||||
if ($route === '/api/collab-buckets' && $method === 'POST') {
|
||||
if (!$clientTenant) jsonResponse(['error' => 'unauthorized'], 401);
|
||||
$input = json_decode(file_get_contents('php://input'), true) ?: [];
|
||||
$uid = trim((string)($input['uid'] ?? ''));
|
||||
$name = trim((string)($input['name'] ?? ''));
|
||||
$color = (string)($input['color'] ?? '#38bdf8');
|
||||
$memberUsernames = is_array($input['members'] ?? null) ? $input['members'] : [];
|
||||
if ($uid === '' || $name === '') jsonResponse(['error' => 'uid and name required'], 400);
|
||||
// Prevent collisions (clients generate UUIDs so this is paranoia)
|
||||
$exists = $db->prepare('SELECT 1 FROM collab_buckets WHERE uid = :u');
|
||||
$exists->execute(['u' => $uid]);
|
||||
if ($exists->fetchColumn()) jsonResponse(['error' => 'uid already exists'], 409);
|
||||
|
||||
// Resolve requested members; silently drop unknown usernames
|
||||
$resolved = [];
|
||||
foreach ($memberUsernames as $u) {
|
||||
$u = trim((string)$u);
|
||||
if ($u === '') continue;
|
||||
$t = getTenantByUsername($db, $u);
|
||||
if ($t) $resolved[(int)$t['id']] = $t['username'];
|
||||
}
|
||||
// Always include the owner
|
||||
$resolved[(int)$clientTenant['id']] = $clientTenant['username'];
|
||||
|
||||
try {
|
||||
$db->beginTransaction();
|
||||
$db->prepare('INSERT INTO collab_buckets (uid, owner_id, owner_username, name, color) VALUES (:uid, :oid, :ou, :n, :c)')
|
||||
->execute(['uid' => $uid, 'oid' => $clientTenant['id'], 'ou' => $clientTenant['username'], 'n' => $name, 'c' => $color]);
|
||||
$mstmt = $db->prepare('INSERT INTO collab_bucket_members (bucket_uid, tenant_id, username) VALUES (:b, :t, :u)');
|
||||
foreach ($resolved as $tid => $uname) {
|
||||
$mstmt->execute(['b' => $uid, 't' => $tid, 'u' => $uname]);
|
||||
}
|
||||
$db->commit();
|
||||
} catch (Throwable $e) {
|
||||
if ($db->inTransaction()) $db->rollBack();
|
||||
jsonResponse(['error' => 'create failed: ' . $e->getMessage()], 500);
|
||||
}
|
||||
jsonResponse(['ok' => true, 'uid' => $uid, 'members' => array_values($resolved)]);
|
||||
}
|
||||
|
||||
// ── GET: list buckets I'm a member of ─────────────────────────────
|
||||
|
||||
if ($route === '/api/collab-buckets' && $method === 'GET') {
|
||||
if (!$clientTenant) jsonResponse(['error' => 'unauthorized'], 401);
|
||||
if (isRateLimited($db, 'collab-buckets-get', 120)) jsonResponse(['error' => 'rate limited'], 429);
|
||||
$stmt = $db->prepare('
|
||||
SELECT b.uid, b.name, b.color, b.owner_username, b.created_at, b.updated_at
|
||||
FROM collab_buckets b
|
||||
INNER JOIN collab_bucket_members m ON m.bucket_uid = b.uid
|
||||
WHERE m.tenant_id = :tid
|
||||
ORDER BY b.updated_at DESC
|
||||
');
|
||||
$stmt->execute(['tid' => $clientTenant['id']]);
|
||||
$buckets = $stmt->fetchAll();
|
||||
// Attach member list to each bucket
|
||||
$mstmt = $db->prepare('SELECT username FROM collab_bucket_members WHERE bucket_uid = :uid ORDER BY username');
|
||||
foreach ($buckets as &$b) {
|
||||
$mstmt->execute(['uid' => $b['uid']]);
|
||||
$b['members'] = array_column($mstmt->fetchAll(), 'username');
|
||||
}
|
||||
jsonResponse(['ok' => true, 'buckets' => $buckets]);
|
||||
}
|
||||
|
||||
// ── PATCH: owner updates name / color / members ───────────────────
|
||||
|
||||
if (preg_match('#^/api/collab-buckets/([a-zA-Z0-9_-]+)$#', $route, $m) && $method === 'PATCH') {
|
||||
if (!$clientTenant) jsonResponse(['error' => 'unauthorized'], 401);
|
||||
$uid = $m[1];
|
||||
$row = $db->prepare('SELECT owner_id FROM collab_buckets WHERE uid = :u');
|
||||
$row->execute(['u' => $uid]);
|
||||
$bucket = $row->fetch();
|
||||
if (!$bucket) jsonResponse(['error' => 'bucket not found'], 404);
|
||||
if ((int)$bucket['owner_id'] !== (int)$clientTenant['id']) jsonResponse(['error' => 'only the owner can update'], 403);
|
||||
|
||||
$input = json_decode(file_get_contents('php://input'), true) ?: [];
|
||||
$sets = [];
|
||||
$params = ['u' => $uid];
|
||||
if (isset($input['name'])) { $sets[] = 'name = :n'; $params['n'] = trim((string)$input['name']); }
|
||||
if (isset($input['color'])) { $sets[] = 'color = :c'; $params['c'] = (string)$input['color']; }
|
||||
|
||||
// Ownership transfer: new owner must already be a member of the bucket.
|
||||
// We set owner_id/owner_username atomically and keep the current
|
||||
// caller in the member list (no implicit leave on transfer).
|
||||
if (isset($input['owner'])) {
|
||||
$newOwnerName = trim((string)$input['owner']);
|
||||
if ($newOwnerName === '') jsonResponse(['error' => 'owner cannot be empty'], 400);
|
||||
$newOwner = getTenantByUsername($db, $newOwnerName);
|
||||
if (!$newOwner) jsonResponse(['error' => "no such user: $newOwnerName"], 404);
|
||||
$memCheck = $db->prepare('SELECT 1 FROM collab_bucket_members WHERE bucket_uid = :b AND tenant_id = :t');
|
||||
$memCheck->execute(['b' => $uid, 't' => $newOwner['id']]);
|
||||
if (!$memCheck->fetchColumn()) {
|
||||
jsonResponse(['error' => 'new owner must already be a member of the bucket'], 400);
|
||||
}
|
||||
$sets[] = 'owner_id = :oid'; $params['oid'] = (int)$newOwner['id'];
|
||||
$sets[] = 'owner_username = :oun'; $params['oun'] = (string)$newOwner['username'];
|
||||
}
|
||||
|
||||
if ($sets) {
|
||||
$sets[] = "updated_at = datetime('now')";
|
||||
$db->prepare('UPDATE collab_buckets SET ' . implode(', ', $sets) . ' WHERE uid = :u')->execute($params);
|
||||
}
|
||||
|
||||
if (isset($input['members']) && is_array($input['members'])) {
|
||||
$resolved = [];
|
||||
foreach ($input['members'] as $u) {
|
||||
$u = trim((string)$u);
|
||||
if ($u === '') continue;
|
||||
$t = getTenantByUsername($db, $u);
|
||||
if ($t) $resolved[(int)$t['id']] = $t['username'];
|
||||
}
|
||||
// Caller is always kept (the user editing) + the current effective
|
||||
// owner (possibly just transferred in this same request).
|
||||
$resolved[(int)$clientTenant['id']] = $clientTenant['username'];
|
||||
if (isset($newOwner)) $resolved[(int)$newOwner['id']] = $newOwner['username'];
|
||||
$db->prepare('DELETE FROM collab_bucket_members WHERE bucket_uid = :u')->execute(['u' => $uid]);
|
||||
$ins = $db->prepare('INSERT INTO collab_bucket_members (bucket_uid, tenant_id, username) VALUES (:b, :t, :u)');
|
||||
foreach ($resolved as $tid => $uname) {
|
||||
$ins->execute(['b' => $uid, 't' => $tid, 'u' => $uname]);
|
||||
}
|
||||
$db->prepare("UPDATE collab_buckets SET updated_at = datetime('now') WHERE uid = :u")->execute(['u' => $uid]);
|
||||
}
|
||||
|
||||
jsonResponse(['ok' => true]);
|
||||
}
|
||||
|
||||
// ── DELETE: owner wipes; member leaves ────────────────────────────
|
||||
|
||||
if (preg_match('#^/api/collab-buckets/([a-zA-Z0-9_-]+)$#', $route, $m) && $method === 'DELETE') {
|
||||
if (!$clientTenant) jsonResponse(['error' => 'unauthorized'], 401);
|
||||
$uid = $m[1];
|
||||
$row = $db->prepare('SELECT owner_id FROM collab_buckets WHERE uid = :u');
|
||||
$row->execute(['u' => $uid]);
|
||||
$bucket = $row->fetch();
|
||||
if (!$bucket) jsonResponse(['error' => 'bucket not found'], 404);
|
||||
|
||||
if ((int)$bucket['owner_id'] === (int)$clientTenant['id']) {
|
||||
// Owner: destroy everything
|
||||
$db->prepare('DELETE FROM collab_bucket_members WHERE bucket_uid = :u')->execute(['u' => $uid]);
|
||||
$db->prepare('DELETE FROM collab_buckets WHERE uid = :u')->execute(['u' => $uid]);
|
||||
jsonResponse(['ok' => true, 'action' => 'deleted']);
|
||||
} else {
|
||||
// Member: remove own membership only
|
||||
$del = $db->prepare('DELETE FROM collab_bucket_members WHERE bucket_uid = :u AND tenant_id = :t');
|
||||
$del->execute(['u' => $uid, 't' => $clientTenant['id']]);
|
||||
// Bump updated_at so remaining members see the member-list change on next poll
|
||||
$db->prepare("UPDATE collab_buckets SET updated_at = datetime('now') WHERE uid = :u")->execute(['u' => $uid]);
|
||||
jsonResponse(['ok' => true, 'action' => 'left']);
|
||||
}
|
||||
}
|
||||
@@ -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]);
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
// Collab card lock routes (Phase 4 — advisory edit locks):
|
||||
// POST /api/collab-locks acquire/refresh a lock
|
||||
// DELETE /api/collab-locks/{bucket}/{card} release own lock
|
||||
// GET /api/collab-locks list locks visible to caller
|
||||
//
|
||||
// Membership is enforced on every operation. A lock refresh just extends
|
||||
// the TTL (60 seconds from now). Expired rows are pruned on every request
|
||||
// via bootstrap.php cleanup, so the GET list never contains stale locks.
|
||||
|
||||
if (!defined('RELAY_BOOTSTRAPPED')) { http_response_code(404); exit; }
|
||||
|
||||
$clientTenant = $clientTenant ?? authClient($db);
|
||||
|
||||
function collabLocksIsMember(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: acquire/refresh ────────────────────────────────────────
|
||||
|
||||
if ($route === '/api/collab-locks' && $method === 'POST') {
|
||||
if (!$clientTenant) jsonResponse(['error' => 'unauthorized'], 401);
|
||||
if (isRateLimited($db, 'collab-locks-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'] ?? ''));
|
||||
if ($bucketUid === '' || $cardUid === '') jsonResponse(['error' => 'bucket_uid and card_uid required'], 400);
|
||||
if (!collabLocksIsMember($db, $bucketUid, (int)$clientTenant['id'])) {
|
||||
jsonResponse(['error' => 'not a member of this bucket'], 403);
|
||||
}
|
||||
$db->prepare("
|
||||
INSERT INTO collab_card_locks (bucket_uid, card_uid, holder_id, holder_username, acquired_at, expires_at)
|
||||
VALUES (:b, :c, :hid, :hu, datetime('now'), datetime('now', '+60 seconds'))
|
||||
ON CONFLICT(bucket_uid, card_uid, holder_id) DO UPDATE SET
|
||||
expires_at = datetime('now', '+60 seconds')
|
||||
")->execute([
|
||||
'b' => $bucketUid,
|
||||
'c' => $cardUid,
|
||||
'hid' => $clientTenant['id'],
|
||||
'hu' => $clientTenant['username'],
|
||||
]);
|
||||
jsonResponse(['ok' => true, 'expires_at' => (string)$db->query("SELECT datetime('now', '+60 seconds')")->fetchColumn()]);
|
||||
}
|
||||
|
||||
// ── DELETE: release own lock ─────────────────────────────────────
|
||||
|
||||
if (preg_match('#^/api/collab-locks/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$#', $route, $m) && $method === 'DELETE') {
|
||||
if (!$clientTenant) jsonResponse(['error' => 'unauthorized'], 401);
|
||||
$bucketUid = $m[1];
|
||||
$cardUid = $m[2];
|
||||
$db->prepare('DELETE FROM collab_card_locks WHERE bucket_uid = :b AND card_uid = :c AND holder_id = :h')
|
||||
->execute(['b' => $bucketUid, 'c' => $cardUid, 'h' => $clientTenant['id']]);
|
||||
jsonResponse(['ok' => true]);
|
||||
}
|
||||
|
||||
// ── GET: list locks visible to caller ────────────────────────────
|
||||
|
||||
if ($route === '/api/collab-locks' && $method === 'GET') {
|
||||
if (!$clientTenant) jsonResponse(['error' => 'unauthorized'], 401);
|
||||
if (isRateLimited($db, 'collab-locks-get', 120)) jsonResponse(['error' => 'rate limited'], 429);
|
||||
// Only return locks in buckets the caller is currently a member of,
|
||||
// and only non-expired rows (bootstrap cleanup + defensive filter).
|
||||
$stmt = $db->prepare("
|
||||
SELECT l.bucket_uid, l.card_uid, l.holder_id, l.holder_username, l.acquired_at, l.expires_at
|
||||
FROM collab_card_locks l
|
||||
INNER JOIN collab_bucket_members m ON m.bucket_uid = l.bucket_uid
|
||||
WHERE m.tenant_id = :tid
|
||||
AND l.expires_at > datetime('now')
|
||||
ORDER BY l.acquired_at DESC
|
||||
");
|
||||
$stmt->execute(['tid' => $clientTenant['id']]);
|
||||
jsonResponse(['ok' => true, 'locks' => $stmt->fetchAll()]);
|
||||
}
|
||||
@@ -62,6 +62,9 @@ if (str_starts_with($route, '/api/')) {
|
||||
require __DIR__ . '/inc/routes/admin.php';
|
||||
require __DIR__ . '/inc/routes/messages.php';
|
||||
require __DIR__ . '/inc/routes/chat.php';
|
||||
require __DIR__ . '/inc/routes/collab-buckets.php';
|
||||
require __DIR__ . '/inc/routes/collab-cards.php';
|
||||
require __DIR__ . '/inc/routes/collab-locks.php';
|
||||
|
||||
jsonResponse(['error' => 'not found'], 404);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user