The previous lock implementation was advisory only — the relay's lock table PK was (bucket_uid, card_uid, holder_id), so multiple users could "hold" the same card simultaneously and the plugin only used the locks to draw a small badge. Concurrent writers raced through LWW, and an unsaved editor on User A could be silently overwritten when User B saved (the symptom: cards appearing to "disappear" from User A's view once their version was clobbered by an LWW pull). Now an exclusive, server-enforced lock: * relay schema: collab_card_locks PK is (bucket_uid, card_uid). One lock per card. Migration drops the old 3-column-PK table on the next bootstrap (locks are 60s ephemeral, no data to preserve). * /api/collab-locks POST: returns 409 + holder info when another tenant already holds it. Same holder refreshes the TTL. * /api/collab-cards POST/DELETE: refuse with 423 + locked_by when a foreign tenant holds the lock. The plugin's local edit is preserved — the push just stays queued and retries on the next poll until the lock expires or is released. Tombstones are gated the same way so a card can't be deleted under the holder's editor. * Plugin push phase: tracks blocked count + holder names, surfaces them in the poll response so the frontend can toast the user. Frontend lock-on-first-keystroke flow: * The lock is no longer acquired on editor-open — opening for read doesn't lock anything. On the FIRST input event in #inp-title or #editor-body the plugin tries to acquire. On success, heartbeat every 30 s; on 409, immediately enter editor takeover. * Takeover mode: title + body inputs disabled, all three save buttons get a capture-phase click blocker (stopImmediatePropagation to defeat the editor's own listener), a window-level capture-phase keydown blocker swallows Ctrl/Cmd+S (app.js binds save directly to the shortcut, bypassing the buttons), and a banner inside the modal explains the situation. The user can still copy their unsaved text out before closing. * If a foreign lock arrives via the regular poll while the editor is already open on that card, the same takeover engages mid-session. * Opening the editor on a card whose lock is *already* known to be foreign starts in takeover mode without arming the input listeners at all. * Self-detection: poll response now carries `self` (the relay username), cached as window._collabSelf, so we don't take ourselves over and the board decoration ignores our own lock. Visual: * Board cards held by a foreign lock now get a frosted overlay + centered lock icon + holder name (replaces the small corner badge). * Editor takeover banner uses the danger accent. Save buttons get a .collab-save-blocked dim style. * New `.collab-lock-toast` variant of the existing conflict toast, used for both "your push is queued because X is editing" and "this card just got locked by X" notifications. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
202 lines
9.4 KiB
PHP
202 lines
9.4 KiB
PHP
<?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();
|
|
}
|
|
|
|
/** If a foreign tenant currently holds a non-expired lock on this card,
|
|
* return the lock row; otherwise null. Used to gate writes / deletes. */
|
|
function collabCardsForeignLock(PDO $db, string $bucketUid, string $cardUid, int $tenantId): ?array {
|
|
$stmt = $db->prepare("
|
|
SELECT holder_id, holder_username, expires_at
|
|
FROM collab_card_locks
|
|
WHERE bucket_uid = :b AND card_uid = :c
|
|
AND holder_id != :t
|
|
AND expires_at > datetime('now')
|
|
");
|
|
$stmt->execute(['b' => $bucketUid, 'c' => $cardUid, 't' => $tenantId]);
|
|
$row = $stmt->fetch();
|
|
return $row ?: null;
|
|
}
|
|
|
|
// ── 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);
|
|
}
|
|
// Exclusive lock enforcement: if another tenant holds the lock,
|
|
// refuse the write. Plugin retries on the next poll until the lock
|
|
// expires or is released. The local edit is preserved either way.
|
|
$foreign = collabCardsForeignLock($db, $bucketUid, $cardUid, (int)$clientTenant['id']);
|
|
if ($foreign) {
|
|
jsonResponse([
|
|
'error' => 'card is being edited by ' . $foreign['holder_username'],
|
|
'locked_by' => $foreign['holder_username'],
|
|
], 423);
|
|
}
|
|
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);
|
|
}
|
|
// Same lock enforcement on delete: if another user has the editor
|
|
// open on this card, deleting it under their feet would be rude.
|
|
$foreign = collabCardsForeignLock($db, $bucketUid, $cardUid, (int)$clientTenant['id']);
|
|
if ($foreign) {
|
|
jsonResponse([
|
|
'error' => 'card is being edited by ' . $foreign['holder_username'],
|
|
'locked_by' => $foreign['holder_username'],
|
|
], 423);
|
|
}
|
|
// 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]);
|
|
}
|