fix(dm): owner-only group DM ops accept federated target identification

Transferring ownership or kicking a member surfaced "Target user is not a
member of this DM channel" whenever the target was a federated user.

Root cause: the client passed `canonical.id` from `useCanonicalUserView`,
which returns the user's HOME id when the home view is in the userViews
cache. After owner-routing the request to the owner instance, that
instance's `dm_members.userId` (its own local replicated id) never
matched the home id, so `isDmMember` returned false. The same failure
mode applied across any cross-instance scenario where the
channel-serving instance and the owner-serving instance disagree on the
local replicated user id for the same federated user.

Fix: both endpoints now accept federated identification, mirroring the
existing pattern on `POST /api/dm/:id/members`:

- `POST /api/dm/:id/transfer` body: `{ newOwnerId? } | { homeUserId, homeInstance }`.
  Federated args win when both are supplied (strictly more specific).
- `DELETE /api/dm/:id/members/:targetUserId` reads optional
  `?homeInstance=<origin>` query; when present, the URL segment is
  treated as a homeUserId and resolved via `resolveOrCreateReplicatedUser`.

Client `api.dm.kickMember` and `api.dm.transferOwnership` gain an
optional `federated` argument; `DmRosterPanel` and `MobileGroupDmInfo`
pass it whenever the target has `homeUserId` + `homeInstance` populated.

Adds 5 server tests (3 transfer + 2 kick) covering federated targets,
the federated-wins-over-local precedence rule, and federated-non-member
rejection. Updates 2 client routing tests and 2 DmRosterPanel test
assertions for the new signature. Updates `docs/systems/dm-system.md`
and `docs/systems/api.md`.

Server: 965 tests pass (was 960). Web: 362 tests pass (was 360).
This commit is contained in:
Jannis Braun
2026-05-10 22:09:14 +02:00
parent 9279ac78e5
commit b6842c5590
11 changed files with 442 additions and 35 deletions
+4 -4
View File
@@ -126,8 +126,8 @@ PATCH /dm/:id { name?, icon? } → { id, na
DELETE /dm/:id → { success } (soft-close)
POST /dm/:id/members { userIds[] } → { dmChannel } [owner, max 10]
DELETE /dm/:id/members → { success } (leave)
DELETE /dm/:id/members/:targetUserId → { success } [owner kick; cannot self-kick; group only]
POST /dm/:id/transfer { newOwnerId } → { success } [owner; member must be in channel; not self]
DELETE /dm/:id/members/:targetUserId ?homeInstance= → { success } [owner kick; cannot self-kick; group only; segment is homeUserId when ?homeInstance is set]
POST /dm/:id/transfer { newOwnerId? | (homeUserId+homeInstance) } → { success } [owner; resolved member must be in channel; not self]
GET /dm/:id/messages ?before=&limit=50 → { messages[] }
POST /dm/:id/messages { content, attachments?, replyToId? } → { message }
PATCH /dm/messages/:id { content } → { message } [author]
@@ -136,9 +136,9 @@ DELETE /dm/messages/:id → { succes
**`PATCH /dm/:id`** — Owner-only update of a group DM's `name` and `icon`. Either field may be omitted (no-op), null (clear), or set. Empty/whitespace name collapses to null. `icon` accepts a bare attachment filename owned by the caller (image/*, ≤ `GROUP_DM_ICON_MAX_BYTES`) or an absolute http(s) URL. No-op short-circuit when nothing actually changes — emits no system message and no federation relay. See `docs/systems/dm-system.md` "Group Metadata Update" for the full transaction, federation relay, and icon URL round-trip rules.
**`DELETE /dm/:id/members/:targetUserId`** — Owner kicks a member from a group DM. Reuses the leave path with `reason: 'kick'`; evicts the target from the DM voice room first. Sends `dm_channel_closed` to the kicked user. Receivers enforce `sourceInstance === ownerHomeInstance`; non-owner kicks reject as `unauthorized_source`.
**`DELETE /dm/:id/members/:targetUserId`** — Owner kicks a member from a group DM. The `:targetUserId` segment carries either a local user id on the owner's instance OR a federated home user id when the `?homeInstance=<origin>` query string is present (server resolves via `resolveOrCreateReplicatedUser` — same pattern as `POST /dm/:id/members`). Federated form is required for federated targets, because the client's cached user view returns the user's home id, not the owner instance's local replicated id. Reuses the leave path with `reason: 'kick'`; evicts the target from the DM voice room first. Sends `dm_channel_closed` to the kicked user. Receivers enforce `sourceInstance === ownerHomeInstance`; non-owner kicks reject as `unauthorized_source`.
**`POST /dm/:id/transfer`** — Owner transfers ownership to another current member without leaving. Updates `ownerId`, `ownerHomeUserId`, `ownerHomeInstance`; inserts an `owner_changed` system message; broadcasts `dm_owner_updated`; queues an `ownership_transfer` outbox event. Reuses the existing receiver path (`processOwnershipTransferEvent`) with no protocol changes.
**`POST /dm/:id/transfer`** — Owner transfers ownership to another current member without leaving. Body accepts either a local id (`newOwnerId`) or a federated identity (`homeUserId` + `homeInstance`). When both forms are supplied, federated args take precedence. Server resolves via `resolveOrCreateReplicatedUser` before checking membership — mirrors `POST /dm/:id/members`. Updates `ownerId`, `ownerHomeUserId`, `ownerHomeInstance`; inserts an `owner_changed` system message; broadcasts `dm_owner_updated`; queues an `ownership_transfer` outbox event. Reuses the existing receiver path (`processOwnershipTransferEvent`) with no protocol changes.
## Social (`routes/social.ts`) — auth required
```
+58 -3
View File
@@ -248,11 +248,32 @@ Either field may be omitted (no-op for that field), null (clear), or a value. Em
Owner-only removal of a single member from a group DM.
**Target identification (local vs federated):**
The `:targetUserId` path segment carries either a local user id on the
owner's instance OR a federated home user id. Optional query string
`?homeInstance=<origin>` signals federated resolution: when present, the
server treats the segment as a homeUserId and resolves it via
`resolveOrCreateReplicatedUser(targetUserId, homeInstance)`. Without the
query parameter, the segment is treated as a local id (legacy form). This
mirrors the federated path on `POST /api/dm/:id/transfer` and is required
for any federated target, because:
- The channel-serving instance and the owner-serving instance can disagree
on the local replicated user id for the same federated user.
- The client's `useCanonicalUserView` cache may surface the user's HOME
view, whose `id` is the home id (not this instance's local replicated id).
The client passes the federated query when the target has `homeUserId` +
`homeInstance` populated. See `api.dm.kickMember`'s `federated` parameter.
**Validation:**
- 1-on-1 DM (`ownerId` is NULL) -> 400
- Caller must be the owner -> else 403
- Cannot kick self (use leave instead) -> 400
- Target must be a current member -> else 404
- Unresolvable target (federated id with no replicated row, or unknown
local id) -> 404
**Sequence:** evict target from any active DM voice room (`evictUserFromDmVoiceRoom`), then reuse the leave path with `reason: 'kick'` -- emits `member_removed` system message (with `reason: 'kick'`), deletes `dm_members` row + `read_states`, broadcasts `dm_member_removed`, sends `dm_channel_closed` to the kicked user, queues `member_remove` outbox event with `reason: 'kick'`. Receiver authority for kicks is `sourceInstance === ownerHomeInstance`; non-owner kicks reject as `unauthorized_source`.
@@ -262,15 +283,48 @@ Owner-only removal of a single member from a group DM.
Owner-only transfer of ownership without leaving the channel.
**Request:** `{ newOwnerId: string }`
**Request:** `TransferOwnershipRequest`
```typescript
interface TransferOwnershipRequest {
newOwnerId?: string; // local user id on the owner's instance
homeUserId?: string; // federated identifier (paired with homeInstance)
homeInstance?: string; // federated identifier (paired with homeUserId)
}
```
**Target identification (local vs federated):**
The endpoint accepts either a local id (`newOwnerId`) OR a federated
identity (`homeUserId` + `homeInstance`). Federated identification mirrors
`AddDmMemberRequest` and is required when the client only knows the
target's home identity — the common case for federated members surfaced
through `useCanonicalUserView`, whose `id` field is the home id, NOT this
instance's local replicated id. The server resolves via
`resolveOrCreateReplicatedUser(homeUserId, homeInstance)` before
validating membership.
When both forms are supplied, the **federated args win** — they're
strictly more specific (homeUserId + homeInstance disambiguates across
instances), and explicit federation arguments should override a stale
local id that may have come from a cached user view.
Historical context: without the federated path, the membership check
`isDmMember(id, newOwnerId)` always failed for federated targets because
`dm_members.userId` on the owner instance is the LOCAL replicated id, not
the federated home id passed by the client. Symptom was a 400 toast on
the client: "Target user is not a member of this DM channel".
**Validation:**
- Body must include `newOwnerId` OR (`homeUserId` + `homeInstance`) -> else 400
- Unresolvable target (federated id with no replicated row, or unknown
local id) -> 404
- 1-on-1 DM (`ownerId` is NULL) -> 400
- Caller must be the current owner -> else 403
- `newOwnerId !== ownerId` (reject self-transfer) -> 400
- Resolved `newOwnerId !== ownerId` (reject self-transfer) -> 400
- Target must be a current member -> else 400
**Transaction (`transferGroupDmOwnership`):** updates `ownerId`, `ownerHomeUserId`, `ownerHomeInstance`; inserts `owner_changed` system message; broadcasts `dm_owner_updated`; queues `ownership_transfer` outbox event. The receiver path is the existing `processOwnershipTransferEvent` -- this endpoint reuses it without modification.
**Transaction (`transferGroupDmOwnership`):** updates `ownerId`, `ownerHomeUserId`, `ownerHomeInstance`; inserts `owner_changed` system message; broadcasts `dm_owner_updated`; queues `ownership_transfer` outbox event. The receiver path is the existing `processOwnershipTransferEvent` -- this endpoint reuses it without modification. The outbox event's `ownership.newOwner` carries the resolved user's home identity, so peers see the correct homeUserId/homeInstance regardless of which form the client used.
---
@@ -840,3 +894,4 @@ For full wire formats, see `docs/systems/websocket.md`.
| Duplicated membership system messages across restarts | 4× "Jannis added youruser" in group DM, channel keeps flipping to unread after each deploy | Membership event processors inserted system messages unconditionally. Each approval-flow re-peering reset peer `last_synced_at = 0`, so initial sync replayed every historical `member_add` / `member_remove` / `ownership_transfer` on next boot. Each replay's new snowflake ID exceeded the user's `read_states.last_read_message_id`, flipping unread. | Dedup by `(sourceInstance, event.messageId)` on the inserted system message. Both bootstrap and incremental paths in `processMemberAddEvent` now persist these fields so replay is a no-op. |
| Raw JSON in DM sidebar previews | DM sidebar showed `{"event":"space_invite",...}` / `{"event":"member_added",...}` as the last-message preview | `DmLastMessagePreview` shape omitted `type`, so the client could not distinguish system from user messages and rendered `lastMessage.content` verbatim. | Added `type` to `DmLastMessagePreview`, populated it from `dm_messages.type` in every server emission site, and routed the sidebar through a single `formatDmSidebarPreview` helper that renders human-readable text for each system event. |
| Owner-only requests routed to wrong instance after manual transfer (latent) | After `POST /api/dm/:id/transfer` moved ownership to a member whose `homeInstance` differed from the channel's pinned serving origin, owner-only client calls (`updateMetadata`, `kickMember`, `transferOwnership`) routed via `getChannelOrigin` would emit outbox events with `sourceInstance !== ownerHomeInstance`, and all peers would reject them as `attribution_mismatch`. Latent only because pre-polish there was no kick endpoint and no metadata edit; auto-transfer-on-leave masked the issue (the leaver IS the actor, and `member_remove reason='leave'` accepts any source). | Added `getOwnerInstanceForDm(channelId)` exported next to `getChannelOrigin`. All four owner-only API client methods (`updateMetadata`, `kickMember`, `transferOwnership` — and any future owner-only routes) call `getApiForOrigin(getOwnerInstanceForDm(channelId))` instead of channel origin. Non-owner operations are unchanged. |
| Kick / transfer to federated member always failed with "user not a member" | `DELETE /api/dm/:id/members/:targetUserId` and `POST /api/dm/:id/transfer` accepted only a local user id. The client passed `canonical.id` from `useCanonicalUserView`, which returns the user's HOME id when the home view is cached. After owner-routing the request to the owner instance, the owner instance's `dm_members.userId` (its own local replicated id) never matched the home id, so `isDmMember` returned false. | Both endpoints now accept federated identification (`homeUserId` + `homeInstance`) — the transfer endpoint takes them in the body, the kick endpoint reads `homeInstance` from a query string and treats the URL segment as a homeUserId. Server resolves via `resolveOrCreateReplicatedUser` before membership check. Mirrors the `addDmMember` pattern. Client `kickMember` / `transferOwnership` accept an optional `federated` arg and pass it when the target has `homeUserId` + `homeInstance` populated. |
@@ -355,4 +355,56 @@ describe('DELETE /api/dm/:id/members/:targetUserId — owner kick', () => {
expect(res.statusCode).toBe(404);
expect(res.json().error).toMatch(/not found/i);
});
// Federated-identification path — mirrors POST /api/dm/:id/transfer. The
// client cannot reliably know the OWNER instance's local user id for a
// federated member (the home view surfaced through `useCanonicalUserView`
// carries the home id). The `?homeInstance=...` query string signals the
// path segment is a homeUserId; the server resolves via
// `resolveOrCreateReplicatedUser` before checking membership.
it('kick with federated identity (?homeInstance=...) → resolves to local replicated user and succeeds', async () => {
seedGroupDm({
id: 'dm-kick-fed-1',
ownerId: 'owner-A',
members: ['owner-A', 'member-B', 'remote-D'],
federatedId: 'fed-kick-fed-1',
});
const res = await app.inject({
method: 'DELETE',
url: '/api/dm/dm-kick-fed-1/members/remote-dan?homeInstance=' + encodeURIComponent('https://remote.test'),
});
expect(res.statusCode).toBe(200);
// Federated member's local replicated row is gone from this channel
const remaining = testDb.select().from(schema.dmMembers)
.where(eq(schema.dmMembers.dmChannelId, 'dm-kick-fed-1'))
.all();
expect(remaining.map((m) => m.userId).sort()).toEqual(['member-B', 'owner-A']);
// Outbox event carries the federated user's home identity with reason=kick
const outboxRows = testDb.select().from(schema.federationOutbox).all();
const removeRows = outboxRows.filter((r) => r.eventType === 'member_remove');
expect(removeRows.length).toBe(1);
const wire = JSON.parse(removeRows[0]!.payload);
expect(wire.membership.reason).toBe('kick');
expect(wire.membership.user.homeUserId).toBe('remote-dan');
expect(wire.membership.user.homeInstance).toBe('https://remote.test');
});
// Negative case: federated identity for a user who is NOT a member.
it('kick with federated identity for non-member → 404', async () => {
seedGroupDm({
id: 'dm-kick-fed-2',
ownerId: 'owner-A',
members: ['owner-A', 'member-B'], // remote-D is NOT a member here
});
const res = await app.inject({
method: 'DELETE',
url: '/api/dm/dm-kick-fed-2/members/remote-dan?homeInstance=' + encodeURIComponent('https://remote.test'),
});
expect(res.statusCode).toBe(404);
expect(res.json().error).toMatch(/not a member/i);
});
});
@@ -406,4 +406,95 @@ describe('POST /api/dm/:id/transfer — manual ownership transfer', () => {
expect(res.statusCode).toBe(400);
expect(res.json().error).toMatch(/newOwnerId/i);
});
// The federated-identification path is the bug-fix surface for the
// "cannot transfer to a federated user" report. The client sends
// `{ homeUserId, homeInstance }` from the cached user view; the owner
// instance must resolve that to its own local replicated row (different
// id) before checking membership and recording ownership.
it('transfer with federated identity ({ homeUserId, homeInstance }) → resolves to local replicated user and succeeds', async () => {
seedGroupDm({
id: 'dm-fed-1',
ownerId: 'owner-A',
members: ['owner-A', 'member-B', 'remote-D'],
federatedId: 'fed-transfer-fed-1',
});
// The client only knows the home identity of the federated target.
// On THIS instance the local replicated id is `remote-D` but the
// request body intentionally omits it — only home identifiers travel.
const res = await app.inject({
method: 'POST',
url: '/api/dm/dm-fed-1/transfer',
payload: { homeUserId: 'remote-dan', homeInstance: 'https://remote.test' },
});
expect(res.statusCode).toBe(200);
// Channel ownership row points to the local replicated user row,
// and ownerHomeUserId / ownerHomeInstance match the target's home.
const channel = testDb.select().from(schema.dmChannels).where(eq(schema.dmChannels.id, 'dm-fed-1')).get();
expect(channel?.ownerId).toBe('remote-D');
expect(channel?.ownerHomeUserId).toBe('remote-dan');
expect(channel?.ownerHomeInstance).toBe('https://remote.test');
// Outbox event carries the new owner's home identity.
const outboxRows = testDb.select().from(schema.federationOutbox).all();
const transferRows = outboxRows.filter((r) => r.eventType === 'ownership_transfer');
expect(transferRows.length).toBe(1);
const wire = JSON.parse(transferRows[0]!.payload);
expect(wire.ownership.newOwner.homeUserId).toBe('remote-dan');
expect(wire.ownership.newOwner.homeInstance).toBe('https://remote.test');
});
// When both forms are supplied, the federated args take precedence —
// they're strictly more specific. A stale `newOwnerId` from the client's
// cached view (could be the home id from `useCanonicalUserView`) should
// not override the explicit federated identifier.
it('transfer with BOTH newOwnerId and federated identity → federated args win', async () => {
seedGroupDm({
id: 'dm-fed-2',
ownerId: 'owner-A',
members: ['owner-A', 'member-B', 'remote-D'],
federatedId: 'fed-transfer-fed-2',
});
// newOwnerId references a different member (member-B). Federated args
// point to remote-D. The federated path must win.
const res = await app.inject({
method: 'POST',
url: '/api/dm/dm-fed-2/transfer',
payload: {
newOwnerId: 'member-B',
homeUserId: 'remote-dan',
homeInstance: 'https://remote.test',
},
});
expect(res.statusCode).toBe(200);
const channel = testDb.select().from(schema.dmChannels).where(eq(schema.dmChannels.id, 'dm-fed-2')).get();
expect(channel?.ownerId).toBe('remote-D');
expect(channel?.ownerHomeUserId).toBe('remote-dan');
});
// Negative case: federated identity for a user who is not a member of
// this DM channel must still 400, matching the existing local-id path.
it('transfer with federated identity for a non-member → 400', async () => {
seedGroupDm({
id: 'dm-fed-3',
ownerId: 'owner-A',
members: ['owner-A', 'member-B'], // remote-D is NOT a member here
});
const res = await app.inject({
method: 'POST',
url: '/api/dm/dm-fed-3/transfer',
payload: { homeUserId: 'remote-dan', homeInstance: 'https://remote.test' },
});
expect(res.statusCode).toBe(400);
expect(res.json().error).toMatch(/not a member/i);
// Ownership row unchanged
const channel = testDb.select().from(schema.dmChannels).where(eq(schema.dmChannels.id, 'dm-fed-3')).get();
expect(channel?.ownerId).toBe('owner-A');
});
});
+95 -8
View File
@@ -1976,11 +1976,43 @@ export async function dmRoutes(app: FastifyInstance): Promise<void> {
return reply.code(200).send({ success: true });
});
// DELETE /api/dm/:id/members/:targetUserId - Owner kicks a member from a group DM
app.delete<{ Params: { id: string; targetUserId: string } }>('/api/dm/:id/members/:targetUserId', async (request, reply) => {
const { id, targetUserId } = request.params;
// DELETE /api/dm/:id/members/:targetUserId - Owner kicks a member from a group DM.
//
// The `:targetUserId` URL segment carries either a local user id OR a
// federated home user id. When the optional `homeInstance` query string is
// present, the segment is interpreted as a home id and resolved via
// `resolveOrCreateReplicatedUser(targetUserId, homeInstance)` — same pattern
// as POST /api/dm/:id/transfer and POST /api/dm/:id/members. This is
// necessary when the client only knows the target's home identity (the
// common case for federated members rendered through `useCanonicalUserView`,
// whose `id` is the home id, not this instance's local replicated id).
// Without this path, the membership check `isDmMember(id, targetUserId)`
// fails because `dm_members.userId` on the owner instance is its local
// replicated id, not the federated home id.
app.delete<{
Params: { id: string; targetUserId: string };
Querystring: { homeInstance?: string };
}>('/api/dm/:id/members/:targetUserId', async (request, reply) => {
const { id, targetUserId: rawTargetSegment } = request.params;
const homeInstanceQuery = request.query?.homeInstance;
const db = getDb();
// Resolve the target to a local user row. When `homeInstance` is supplied,
// treat the URL segment as a homeUserId. Otherwise, treat it as a local
// user id and look it up directly.
let targetUserRow: typeof schema.users.$inferSelect | undefined;
if (typeof homeInstanceQuery === 'string' && homeInstanceQuery.length > 0) {
targetUserRow = resolveOrCreateReplicatedUser(rawTargetSegment, homeInstanceQuery, db) ?? undefined;
} else {
targetUserRow = db.select().from(schema.users).where(eq(schema.users.id, rawTargetSegment)).get();
}
if (!targetUserRow) {
return reply.code(404).send({ error: 'User not found', statusCode: 404 });
}
const targetUserId = targetUserRow.id;
// Channel must exist (and not be soft-deleted)
const dmChannel = db.select().from(schema.dmChannels).where(and(eq(schema.dmChannels.id, id), isNull(schema.dmChannels.deletedAt))).get();
if (!dmChannel) {
@@ -2021,17 +2053,72 @@ export async function dmRoutes(app: FastifyInstance): Promise<void> {
return reply.code(200).send({ success: true });
});
// POST /api/dm/:id/transfer - Owner transfers ownership to another group member without leaving
app.post<{ Params: { id: string }; Body: { newOwnerId?: unknown } }>('/api/dm/:id/transfer', async (request, reply) => {
// POST /api/dm/:id/transfer - Owner transfers ownership to another group member without leaving.
//
// Body accepts either a local id (`newOwnerId`) or a federated identity
// (`homeUserId` + `homeInstance`). Federated identification mirrors the
// `addDmMember` pattern (see `POST /api/dm/:id/members` above) and is
// required when the client only knows the target's home identity — for
// example when the channel-serving instance and the owner-serving instance
// disagree on the local replicated user id, or when `useCanonicalUserView`
// surfaces the user's home view (whose `id` is the home id, NOT this
// instance's local replicated id). Without this path, transferring ownership
// to a federated member always failed with "user is not part of the DM"
// because the owner instance's `dm_members.userId` is its OWN local id, not
// the federated home id.
app.post<{
Params: { id: string };
Body: {
newOwnerId?: unknown;
homeUserId?: unknown;
homeInstance?: unknown;
};
}>('/api/dm/:id/transfer', async (request, reply) => {
const { id } = request.params;
const newOwnerId = (request.body as { newOwnerId?: unknown } | null)?.newOwnerId;
const body = (request.body ?? {}) as {
newOwnerId?: unknown;
homeUserId?: unknown;
homeInstance?: unknown;
};
const rawNewOwnerId = body.newOwnerId;
const rawHomeUserId = body.homeUserId;
const rawHomeInstance = body.homeInstance;
if (typeof newOwnerId !== 'string' || newOwnerId.length === 0) {
return reply.code(400).send({ error: 'newOwnerId is required', statusCode: 400 });
const hasFederatedArgs =
typeof rawHomeUserId === 'string' && rawHomeUserId.length > 0 &&
typeof rawHomeInstance === 'string' && rawHomeInstance.length > 0;
const hasLocalArg = typeof rawNewOwnerId === 'string' && rawNewOwnerId.length > 0;
if (!hasFederatedArgs && !hasLocalArg) {
return reply.code(400).send({
error: 'newOwnerId or (homeUserId + homeInstance) is required',
statusCode: 400,
});
}
const db = getDb();
// Resolve the new owner to a local user row. Federated identification
// takes precedence when both forms are supplied — it's strictly more
// specific (homeUserId + homeInstance disambiguates across instances),
// so the explicit federated args wins over a possibly-stale local id.
let newOwnerRow: typeof schema.users.$inferSelect | undefined;
if (hasFederatedArgs) {
newOwnerRow = resolveOrCreateReplicatedUser(
rawHomeUserId as string,
rawHomeInstance as string,
db,
) ?? undefined;
} else {
newOwnerRow = db.select().from(schema.users).where(eq(schema.users.id, rawNewOwnerId as string)).get();
}
if (!newOwnerRow) {
return reply.code(404).send({ error: 'User not found', statusCode: 404 });
}
const newOwnerId = newOwnerRow.id;
// Channel must exist (and not be soft-deleted)
const dmChannel = db.select().from(schema.dmChannels).where(and(eq(schema.dmChannels.id, id), isNull(schema.dmChannels.deletedAt))).get();
if (!dmChannel) {
+17
View File
@@ -594,6 +594,23 @@ export interface AddDmMemberRequest {
homeInstance?: string;
}
/**
* Body of POST /api/dm/:id/transfer.
*
* Accepts either a local user id (`newOwnerId`) or a federated identity
* (`homeUserId` + `homeInstance`). Federated identification mirrors
* `AddDmMemberRequest` and is required when the caller only knows the
* target's home identity — typical for federated members surfaced through
* the client's `userViews` cache, where `id` is the home id and not the
* owner instance's local replicated id. When both are supplied, the
* federated args take precedence (strictly more specific).
*/
export interface TransferOwnershipRequest {
newOwnerId?: string;
homeUserId?: string;
homeInstance?: string;
}
export interface GroupDmUserIdentity {
id: string;
homeUserId?: string | null;
+48 -9
View File
@@ -24,6 +24,7 @@ import type {
CreateDmRequest,
AddDmMemberRequest,
CreateGroupDmRequest,
TransferOwnershipRequest,
CreateDmMessageRequest,
Friend,
FriendRequest,
@@ -184,14 +185,36 @@ export class BackspaceApiClient {
updateMetadata: (channelId: string, body: { name?: string | null; icon?: string | null }) => Promise<DmChannel>;
/**
* Owner-only: kick a member from a group DM.
* Routes via getApiForOrigin(getOwnerInstanceForDm(channelId)) — see updateMetadata.
*
* Routes via getApiForOrigin(getOwnerInstanceForDm(channelId)) — see
* updateMetadata. The optional `federated` arg is required when the
* target is a federated user: the channel-serving instance and the
* owner-serving instance disagree on the local replicated user id, and
* the home view surfaced through `userViews` carries the home id, not
* the owner instance's local id. When `federated` is supplied, the
* server resolves it via `resolveOrCreateReplicatedUser`. Without it,
* `targetUserId` is treated as a local id on the owner instance.
*/
kickMember: (channelId: string, targetUserId: string) => Promise<{ success: boolean }>;
kickMember: (
channelId: string,
targetUserId: string,
federated?: { homeUserId: string; homeInstance: string },
) => Promise<{ success: boolean }>;
/**
* Owner-only: transfer group DM ownership to another member without leaving.
* Routes via getApiForOrigin(getOwnerInstanceForDm(channelId)) — see updateMetadata.
*
* Routes via getApiForOrigin(getOwnerInstanceForDm(channelId)) — see
* updateMetadata. The optional `federated` arg is required for
* federated targets, mirroring `kickMember`. When supplied, the server
* uses `resolveOrCreateReplicatedUser(homeUserId, homeInstance)` to
* find the local user row. Without it, `newOwnerId` is treated as a
* local id on the owner instance.
*/
transferOwnership: (channelId: string, newOwnerId: string) => Promise<DmChannel>;
transferOwnership: (
channelId: string,
newOwnerId: string,
federated?: { homeUserId: string; homeInstance: string },
) => Promise<DmChannel>;
spaceInvite: (body: SpaceInviteRequest) => Promise<SpaceInviteResponse>;
};
@@ -518,15 +541,31 @@ export class BackspaceApiClient {
if (target !== this) return target.dm.updateMetadata(channelId, body);
return request<DmChannel>('PATCH', `/dm/${channelId}`, body);
},
kickMember: (channelId, targetUserId) => {
kickMember: (channelId, targetUserId, federated) => {
const target = getApiForOrigin(getOwnerInstanceForDm(channelId));
if (target !== this) return target.dm.kickMember(channelId, targetUserId);
if (target !== this) return target.dm.kickMember(channelId, targetUserId, federated);
// For federated targets, the URL segment carries the homeUserId and
// the `homeInstance` query string signals federated resolution. The
// server route resolves via `resolveOrCreateReplicatedUser`. For
// local targets, the URL segment is the local user id (legacy form)
// and no query is appended.
if (federated) {
const homeId = encodeURIComponent(federated.homeUserId);
const homeInst = encodeURIComponent(federated.homeInstance);
return request<{ success: boolean }>(
'DELETE',
`/dm/${channelId}/members/${homeId}?homeInstance=${homeInst}`,
);
}
return request<{ success: boolean }>('DELETE', `/dm/${channelId}/members/${targetUserId}`);
},
transferOwnership: (channelId, newOwnerId) => {
transferOwnership: (channelId, newOwnerId, federated) => {
const target = getApiForOrigin(getOwnerInstanceForDm(channelId));
if (target !== this) return target.dm.transferOwnership(channelId, newOwnerId);
return request<DmChannel>('POST', `/dm/${channelId}/transfer`, { newOwnerId });
if (target !== this) return target.dm.transferOwnership(channelId, newOwnerId, federated);
const body: TransferOwnershipRequest = federated
? { homeUserId: federated.homeUserId, homeInstance: federated.homeInstance }
: { newOwnerId };
return request<DmChannel>('POST', `/dm/${channelId}/transfer`, body);
},
spaceInvite: (body) =>
request<SpaceInviteResponse>('POST', '/dm/space-invite', body),
@@ -106,9 +106,16 @@ const apiTransferOwnership = vi.fn().mockResolvedValue({});
vi.mock('../../api/client', () => ({
api: {
dm: {
kickMember: (channelId: string, userId: string) => apiKickMember(channelId, userId),
transferOwnership: (channelId: string, userId: string) =>
apiTransferOwnership(channelId, userId),
kickMember: (
channelId: string,
userId: string,
federated?: { homeUserId: string; homeInstance: string },
) => apiKickMember(channelId, userId, federated),
transferOwnership: (
channelId: string,
userId: string,
federated?: { homeUserId: string; homeInstance: string },
) => apiTransferOwnership(channelId, userId, federated),
},
},
}));
@@ -343,7 +350,8 @@ describe('DmRosterPanel — action wiring', () => {
await waitFor(() => {
expect(apiKickMember).toHaveBeenCalledTimes(1);
});
expect(apiKickMember).toHaveBeenCalledWith('dm-1', 'tgt');
// Local target → federated arg is undefined.
expect(apiKickMember).toHaveBeenCalledWith('dm-1', 'tgt', undefined);
});
it('transfer action: opens confirm dialog, then calls api.dm.transferOwnership on confirm', async () => {
@@ -367,7 +375,8 @@ describe('DmRosterPanel — action wiring', () => {
await waitFor(() => {
expect(apiTransferOwnership).toHaveBeenCalledTimes(1);
});
expect(apiTransferOwnership).toHaveBeenCalledWith('dm-1', 'tgt');
// Local target → federated arg is undefined.
expect(apiTransferOwnership).toHaveBeenCalledWith('dm-1', 'tgt', undefined);
});
it('remove-friend action: calls socialStore.removeFriend with the row user id', async () => {
@@ -121,7 +121,17 @@ export function DmRosterPanel() {
if (!pendingKick) return;
setSubmitting(true);
try {
await api.dm.kickMember(dmChannel.id, pendingKick.id);
// Pass federated identity when the target is a federated user.
// `pendingKick.id` may be the home id (when the home view is in the
// userViews cache) OR a local id from any instance — neither is
// guaranteed to match the OWNER instance's local replicated id. The
// owner instance resolves home id + home instance via
// `resolveOrCreateReplicatedUser`, which is the only deterministic
// way to find the right `dm_members.userId` row across instances.
const federated = pendingKick.homeUserId && pendingKick.homeInstance
? { homeUserId: pendingKick.homeUserId, homeInstance: pendingKick.homeInstance }
: undefined;
await api.dm.kickMember(dmChannel.id, pendingKick.id, federated);
addToast(
`Removed ${pendingKick.displayName ?? parseFederatedUsername(pendingKick.username).baseName} from the group`,
'success',
@@ -143,7 +153,11 @@ export function DmRosterPanel() {
if (!pendingTransfer) return;
setSubmitting(true);
try {
await api.dm.transferOwnership(dmChannel.id, pendingTransfer.id);
// See confirmKick for the rationale on federated identity.
const federated = pendingTransfer.homeUserId && pendingTransfer.homeInstance
? { homeUserId: pendingTransfer.homeUserId, homeInstance: pendingTransfer.homeInstance }
: undefined;
await api.dm.transferOwnership(dmChannel.id, pendingTransfer.id, federated);
addToast(
`Ownership transferred to ${pendingTransfer.displayName ?? parseFederatedUsername(pendingTransfer.username).baseName}`,
'success',
@@ -332,7 +332,11 @@ export function MobileGroupDmInfo({ params }: MobileGroupDmInfoProps) {
if (!pendingKick || !channelId) return;
setSubmittingMemberAction(true);
try {
await api.dm.kickMember(channelId, pendingKick.id);
// See DmRosterPanel.confirmKick for federated identity rationale.
const federated = pendingKick.homeUserId && pendingKick.homeInstance
? { homeUserId: pendingKick.homeUserId, homeInstance: pendingKick.homeInstance }
: undefined;
await api.dm.kickMember(channelId, pendingKick.id, federated);
addToast(
`Removed ${pendingKick.displayName ?? parseFederatedUsername(pendingKick.username).baseName} from the group`,
'success',
@@ -354,7 +358,11 @@ export function MobileGroupDmInfo({ params }: MobileGroupDmInfoProps) {
if (!pendingTransfer || !channelId) return;
setSubmittingMemberAction(true);
try {
await api.dm.transferOwnership(channelId, pendingTransfer.id);
// See DmRosterPanel.confirmKick for federated identity rationale.
const federated = pendingTransfer.homeUserId && pendingTransfer.homeInstance
? { homeUserId: pendingTransfer.homeUserId, homeInstance: pendingTransfer.homeInstance }
: undefined;
await api.dm.transferOwnership(channelId, pendingTransfer.id, federated);
addToast(
`Ownership transferred to ${pendingTransfer.displayName ?? parseFederatedUsername(pendingTransfer.username).baseName}`,
'success',
@@ -160,7 +160,25 @@ describe('group DM owner routing — api.dm.* (Task 5.2)', () => {
await api.dm.kickMember('dm-1', 'target-user');
expect(mockGetApiForOrigin).toHaveBeenCalledWith('https://orbit.test');
expect(remoteClient.dm.kickMember).toHaveBeenCalledWith('dm-1', 'target-user');
// Third arg is the optional federated identity (undefined when target is local)
expect(remoteClient.dm.kickMember).toHaveBeenCalledWith('dm-1', 'target-user', undefined);
});
it('after transfer: api.dm.kickMember forwards federated identity when supplied', async () => {
useSpaceStore.setState({
dmChannels: [{ ...baseDm, ownerHomeInstance: 'https://orbit.test' }],
});
await api.dm.kickMember('dm-1', 'target-user', {
homeUserId: 'target-home-id',
homeInstance: 'https://orbit.test',
});
expect(mockGetApiForOrigin).toHaveBeenCalledWith('https://orbit.test');
expect(remoteClient.dm.kickMember).toHaveBeenCalledWith('dm-1', 'target-user', {
homeUserId: 'target-home-id',
homeInstance: 'https://orbit.test',
});
});
it('after transfer: api.dm.transferOwnership routes to new owner instance', async () => {
@@ -171,7 +189,24 @@ describe('group DM owner routing — api.dm.* (Task 5.2)', () => {
await api.dm.transferOwnership('dm-1', 'next-owner');
expect(mockGetApiForOrigin).toHaveBeenCalledWith('https://orbit.test');
expect(remoteClient.dm.transferOwnership).toHaveBeenCalledWith('dm-1', 'next-owner');
expect(remoteClient.dm.transferOwnership).toHaveBeenCalledWith('dm-1', 'next-owner', undefined);
});
it('after transfer: api.dm.transferOwnership forwards federated identity when supplied', async () => {
useSpaceStore.setState({
dmChannels: [{ ...baseDm, ownerHomeInstance: 'https://orbit.test' }],
});
await api.dm.transferOwnership('dm-1', 'next-owner', {
homeUserId: 'next-owner-home-id',
homeInstance: 'https://orbit.test',
});
expect(mockGetApiForOrigin).toHaveBeenCalledWith('https://orbit.test');
expect(remoteClient.dm.transferOwnership).toHaveBeenCalledWith('dm-1', 'next-owner', {
homeUserId: 'next-owner-home-id',
homeInstance: 'https://orbit.test',
});
});
it('non-owner-only op (sendMessage) is unaffected by ownerHomeInstance', async () => {