Compare commits
12 Commits
9670da400e
...
feat/triag
| Author | SHA1 | Date | |
|---|---|---|---|
| 7cb046d785 | |||
| e635faea9c | |||
| 30069377e7 | |||
| b1f7467161 | |||
| 7e944a08f6 | |||
| e45ad91340 | |||
| 3e96de730a | |||
| f54ed6abb5 | |||
| 8de5736a59 | |||
| 58badf328c | |||
| b3fcefb5ec | |||
| 8c41d23a9c |
75
README.md
75
README.md
@@ -1,22 +1,71 @@
|
|||||||
# Fabric.Backend.Guild
|
# Fabric.Backend.Guild
|
||||||
|
|
||||||
Guild Node service for Fabric.
|
A **guild node** for Fabric (NestJS, ES modules, MySQL/TypeORM,
|
||||||
|
socket.io). Default port `7002`, global prefix `/api`. Many independent
|
||||||
|
guild nodes can run; each registers with `Fabric.Backend.Center` and
|
||||||
|
introspects the user/guild tokens Center issues.
|
||||||
|
|
||||||
## Scope (MVP)
|
## Responsibilities
|
||||||
- Workspace/Guild/Channel/DM
|
|
||||||
- Message create/edit/delete/reply/@mention
|
|
||||||
- Per-channel/DM seq ordering + gap backfill API
|
|
||||||
- Webhook/Bot integration surface
|
|
||||||
- Guild-level audit logs
|
|
||||||
|
|
||||||
## Next
|
- **Guilds / channels / messaging** — per-channel `seq` ordering, edit
|
||||||
- API skeleton (NestJS)
|
window, soft delete, reply, `<@id>` mentions (backtick-aware) plus
|
||||||
- Chat domain models
|
`<@user.name:NAME>` → `<@userId>` translation via Center.
|
||||||
- Seq allocator and range query endpoints
|
- **Channel `x_type`** (required on create): `general`, `work`, `report`,
|
||||||
|
`discuss`, `triage`, `custom`. Plus `isPublic` and `closed` (closed →
|
||||||
|
history readable, posting returns `409`).
|
||||||
|
- **`wake_mapping`** — explicit wake list for `triage` (on-duty) and
|
||||||
|
`custom` (listeners) channels.
|
||||||
|
- **Per-recipient `wakeup`** — `message.created` is emitted per socket with
|
||||||
|
its own `wakeup` flag (author=false; general→all; report→none;
|
||||||
|
triage/custom→wake_mapping; discuss/work→the current speaker only). This
|
||||||
|
is **push-only metadata for the OpenClaw plugin**; UIs ignore it.
|
||||||
|
- **discuss/work turn engine** (`channel_turn_state`): speaking order and a
|
||||||
|
disjoint **bypass list** (bypass members aren't woken unless @-mentioned);
|
||||||
|
activation from idle, queue-jump, cross-round `/no-reply` pause,
|
||||||
|
`/force-proceed`, end-of-round shuffle, guild `/ack`, and a mention
|
||||||
|
sub-frame stack with a 5-level nesting cap (root + 4). `moveToBypass`
|
||||||
|
mid-rotation.
|
||||||
|
- **Files** — `POST /files` (multipart, configurable max size, default
|
||||||
|
100 MB), `GET /files/:id` (Bearer **or** `?access_token=` for browser
|
||||||
|
`<img>/<a>`), automatic retention sweep (default 7 days). Messages carry
|
||||||
|
`attachments[]`.
|
||||||
|
- **Channel canvas** — one pinned document per channel (`md`/`html`/`text`),
|
||||||
|
re-share replaces, only the original sharer may update/remove; emits
|
||||||
|
`canvas.updated` / `canvas.removed`.
|
||||||
|
- **Slash-command registry** — guild-global catalog: `PUT /api/commands`
|
||||||
|
(the OpenClaw plugin syncs OpenClaw's native-command specs here),
|
||||||
|
`GET /api/commands` (frontend `/` autocomplete). Stored verbatim;
|
||||||
|
execution is unchanged (a `/<cmd>` message flows normally to the plugin →
|
||||||
|
OpenClaw command system; only `/no-reply`,`/force-proceed` are
|
||||||
|
server-intercepted).
|
||||||
|
- **Realtime** — socket.io `/realtime`; `join_channel`/`leave_channel`,
|
||||||
|
`message.created/updated/deleted`, `canvas.*`, presence, typing.
|
||||||
|
|
||||||
|
## Required env (hard-checked at startup)
|
||||||
|
|
||||||
## Required env (startup hard checks)
|
|
||||||
- `FABRIC_BACKEND_GUILD_CENTER_BASE_URL`
|
- `FABRIC_BACKEND_GUILD_CENTER_BASE_URL`
|
||||||
- `FABRIC_BACKEND_GUILD_CENTER_API_KEY`
|
- `FABRIC_BACKEND_GUILD_CENTER_API_KEY`
|
||||||
- `FABRIC_BACKEND_GUILD_NODE_ID`
|
- `FABRIC_BACKEND_GUILD_NODE_ID`
|
||||||
|
|
||||||
If any of the above is missing, service startup fails immediately.
|
Missing any of these aborts startup.
|
||||||
|
|
||||||
|
## Other env
|
||||||
|
|
||||||
|
- `FABRIC_BACKEND_GUILD_PORT` (default 7002)
|
||||||
|
- `FABRIC_BACKEND_GUILD_DB_*`, `FABRIC_BACKEND_GUILD_DB_SYNC`
|
||||||
|
- `FABRIC_BACKEND_GUILD_FILE_DIR` (storage root),
|
||||||
|
`FABRIC_BACKEND_GUILD_FILE_MAX_BYTES` (default 100 MB),
|
||||||
|
`FABRIC_BACKEND_GUILD_FILE_TTL_DAYS` (default 7)
|
||||||
|
- `FABRIC_BACKEND_GUILD_CORS_ORIGINS` (empty = allow all; `null` origin —
|
||||||
|
`file://` desktop — is always allowed)
|
||||||
|
|
||||||
|
## Run
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install
|
||||||
|
npm run build && npm start # or: npm run start:dev
|
||||||
|
```
|
||||||
|
|
||||||
|
Usually run via the root `docker-compose.local.yml` (`backend-guild1`
|
||||||
|
`test-guild1` :7002, `backend-guild2` `test-guild2` :7003). Schema is
|
||||||
|
auto-managed (`DB_SYNC`). ES modules (`NodeNext`).
|
||||||
|
|||||||
@@ -2,10 +2,12 @@
|
|||||||
"name": "fabric-backend-guild",
|
"name": "fabric-backend-guild",
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
"description": "Fabric Guild Node service",
|
"description": "Fabric Guild Node service",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "tsc -p tsconfig.build.json",
|
"build": "tsc -p tsconfig.build.json",
|
||||||
"start": "node dist/main.js",
|
"start": "node dist/main.js",
|
||||||
|
"print:commands-key": "node dist/cli/print-commands-sync-key.js",
|
||||||
"start:dev": "ts-node src/main.ts",
|
"start:dev": "ts-node src/main.ts",
|
||||||
"lint": "eslint 'src/**/*.ts'",
|
"lint": "eslint 'src/**/*.ts'",
|
||||||
"lint:fix": "eslint 'src/**/*.ts' --fix",
|
"lint:fix": "eslint 'src/**/*.ts' --fix",
|
||||||
|
|||||||
@@ -1,18 +1,21 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
import { APP_GUARD } from '@nestjs/core';
|
import { APP_GUARD } from '@nestjs/core';
|
||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
import { buildTypeOrmConfig } from './database.config';
|
import { buildTypeOrmConfig } from './database.config.js';
|
||||||
import { HealthController } from './common/health.controller';
|
import { HealthController } from './common/health.controller.js';
|
||||||
import { MetricsController } from './common/metrics.controller';
|
import { MetricsController } from './common/metrics.controller.js';
|
||||||
import { MetricsService } from './common/metrics.service';
|
import { MetricsService } from './common/metrics.service.js';
|
||||||
import { ApiKeyGuard } from './common/api-key.guard';
|
import { ApiKeyGuard } from './common/api-key.guard.js';
|
||||||
import { GuildsModule } from './guilds/guilds.module';
|
import { GuildsModule } from './guilds/guilds.module.js';
|
||||||
import { ChannelsModule } from './channels/channels.module';
|
import { ChannelsModule } from './channels/channels.module.js';
|
||||||
import { TurnModule } from './channels/turn.module';
|
import { TurnModule } from './channels/turn.module.js';
|
||||||
import { MessagingModule } from './messaging/messaging.module';
|
import { MessagingModule } from './messaging/messaging.module.js';
|
||||||
import { EventsModule } from './events/events.module';
|
import { EventsModule } from './events/events.module.js';
|
||||||
import { RealtimeModule } from './realtime/realtime.module';
|
import { RealtimeModule } from './realtime/realtime.module.js';
|
||||||
import { MembersModule } from './members/members.module';
|
import { MembersModule } from './members/members.module.js';
|
||||||
|
import { FilesModule } from './files/files.module.js';
|
||||||
|
import { CanvasModule } from './canvas/canvas.module.js';
|
||||||
|
import { CommandsModule } from './commands/commands.module.js';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
@@ -24,6 +27,9 @@ import { MembersModule } from './members/members.module';
|
|||||||
ChannelsModule,
|
ChannelsModule,
|
||||||
MembersModule,
|
MembersModule,
|
||||||
MessagingModule,
|
MessagingModule,
|
||||||
|
FilesModule,
|
||||||
|
CanvasModule,
|
||||||
|
CommandsModule,
|
||||||
],
|
],
|
||||||
controllers: [HealthController, MetricsController],
|
controllers: [HealthController, MetricsController],
|
||||||
providers: [
|
providers: [
|
||||||
|
|||||||
58
src/canvas/canvas.controller.ts
Normal file
58
src/canvas/canvas.controller.ts
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Delete,
|
||||||
|
Get,
|
||||||
|
Param,
|
||||||
|
Post,
|
||||||
|
Put,
|
||||||
|
Patch,
|
||||||
|
Req,
|
||||||
|
UnauthorizedException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { CanvasService } from './canvas.service.js';
|
||||||
|
|
||||||
|
type AuthedRequest = { userId?: string };
|
||||||
|
type CanvasBody = { title?: string; format?: string; source?: string };
|
||||||
|
|
||||||
|
@Controller('channels/:id/canvas')
|
||||||
|
export class CanvasController {
|
||||||
|
constructor(private readonly canvas: CanvasService) {}
|
||||||
|
|
||||||
|
private uid(req: AuthedRequest): string {
|
||||||
|
const userId = req.userId ?? '';
|
||||||
|
if (!userId) throw new UnauthorizedException('missing user');
|
||||||
|
return userId;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get()
|
||||||
|
get(@Req() req: AuthedRequest, @Param('id') channelId: string) {
|
||||||
|
return this.canvas.get(channelId, this.uid(req));
|
||||||
|
}
|
||||||
|
|
||||||
|
// share / replace (caller becomes the sharer)
|
||||||
|
@Put()
|
||||||
|
@Post()
|
||||||
|
share(
|
||||||
|
@Req() req: AuthedRequest,
|
||||||
|
@Param('id') channelId: string,
|
||||||
|
@Body() body: CanvasBody,
|
||||||
|
) {
|
||||||
|
return this.canvas.share(channelId, this.uid(req), body ?? {});
|
||||||
|
}
|
||||||
|
|
||||||
|
// update in place (original sharer only)
|
||||||
|
@Patch()
|
||||||
|
update(
|
||||||
|
@Req() req: AuthedRequest,
|
||||||
|
@Param('id') channelId: string,
|
||||||
|
@Body() body: CanvasBody,
|
||||||
|
) {
|
||||||
|
return this.canvas.update(channelId, this.uid(req), body ?? {});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete()
|
||||||
|
remove(@Req() req: AuthedRequest, @Param('id') channelId: string) {
|
||||||
|
return this.canvas.remove(channelId, this.uid(req));
|
||||||
|
}
|
||||||
|
}
|
||||||
14
src/canvas/canvas.module.ts
Normal file
14
src/canvas/canvas.module.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { Channel } from '../entities/channel.entity.js';
|
||||||
|
import { ChannelMember } from '../entities/channel-member.entity.js';
|
||||||
|
import { ChannelCanvas } from '../entities/channel-canvas.entity.js';
|
||||||
|
import { CanvasController } from './canvas.controller.js';
|
||||||
|
import { CanvasService } from './canvas.service.js';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [TypeOrmModule.forFeature([Channel, ChannelMember, ChannelCanvas])],
|
||||||
|
controllers: [CanvasController],
|
||||||
|
providers: [CanvasService],
|
||||||
|
})
|
||||||
|
export class CanvasModule {}
|
||||||
147
src/canvas/canvas.service.ts
Normal file
147
src/canvas/canvas.service.ts
Normal file
@@ -0,0 +1,147 @@
|
|||||||
|
import {
|
||||||
|
BadRequestException,
|
||||||
|
ForbiddenException,
|
||||||
|
Injectable,
|
||||||
|
NotFoundException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
|
import { Repository } from 'typeorm';
|
||||||
|
import { Channel } from '../entities/channel.entity.js';
|
||||||
|
import { ChannelMember } from '../entities/channel-member.entity.js';
|
||||||
|
import {
|
||||||
|
ChannelCanvas,
|
||||||
|
type CanvasFormat,
|
||||||
|
} from '../entities/channel-canvas.entity.js';
|
||||||
|
import { RealtimeGateway } from '../realtime/realtime.gateway.js';
|
||||||
|
|
||||||
|
const FORMATS: CanvasFormat[] = ['md', 'html', 'text'];
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class CanvasService {
|
||||||
|
constructor(
|
||||||
|
@InjectRepository(Channel)
|
||||||
|
private readonly channelRepo: Repository<Channel>,
|
||||||
|
@InjectRepository(ChannelMember)
|
||||||
|
private readonly memberRepo: Repository<ChannelMember>,
|
||||||
|
@InjectRepository(ChannelCanvas)
|
||||||
|
private readonly canvasRepo: Repository<ChannelCanvas>,
|
||||||
|
private readonly realtime: RealtimeGateway,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
private view(c: ChannelCanvas) {
|
||||||
|
return {
|
||||||
|
channelId: c.channelId,
|
||||||
|
sharerUserId: c.sharerUserId,
|
||||||
|
title: c.title,
|
||||||
|
format: c.format,
|
||||||
|
source: c.source,
|
||||||
|
version: c.version,
|
||||||
|
createdAt: c.createdAt.toISOString(),
|
||||||
|
updatedAt: c.updatedAt.toISOString(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async assertChannel(channelId: string) {
|
||||||
|
const channel = await this.channelRepo.findOne({ where: { id: channelId } });
|
||||||
|
if (!channel) throw new NotFoundException('channel not found');
|
||||||
|
return channel;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async assertParticipant(channelId: string, userId: string) {
|
||||||
|
const channel = await this.assertChannel(channelId);
|
||||||
|
if (channel.isPublic) return channel;
|
||||||
|
const member = await this.memberRepo.findOne({ where: { channelId, userId } });
|
||||||
|
if (!member) throw new ForbiddenException('not a channel member');
|
||||||
|
return channel;
|
||||||
|
}
|
||||||
|
|
||||||
|
async get(channelId: string, userId: string) {
|
||||||
|
await this.assertParticipant(channelId, userId);
|
||||||
|
const c = await this.canvasRepo.findOne({ where: { channelId } });
|
||||||
|
return c ? this.view(c) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private normalize(input: {
|
||||||
|
title?: string;
|
||||||
|
format?: string;
|
||||||
|
source?: string;
|
||||||
|
}) {
|
||||||
|
const title = String(input.title ?? '').trim().slice(0, 200) || 'Untitled';
|
||||||
|
const format = String(input.format ?? 'md') as CanvasFormat;
|
||||||
|
if (!FORMATS.includes(format)) {
|
||||||
|
throw new BadRequestException(`format must be one of: ${FORMATS.join(', ')}`);
|
||||||
|
}
|
||||||
|
const source = String(input.source ?? '');
|
||||||
|
return { title, format, source };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Share / replace the channel's single active canvas (caller becomes sharer).
|
||||||
|
async share(
|
||||||
|
channelId: string,
|
||||||
|
userId: string,
|
||||||
|
input: { title?: string; format?: string; source?: string },
|
||||||
|
) {
|
||||||
|
await this.assertParticipant(channelId, userId);
|
||||||
|
const { title, format, source } = this.normalize(input);
|
||||||
|
let c = await this.canvasRepo.findOne({ where: { channelId } });
|
||||||
|
if (c) {
|
||||||
|
c.sharerUserId = userId;
|
||||||
|
c.title = title;
|
||||||
|
c.format = format;
|
||||||
|
c.source = source;
|
||||||
|
c.version = 1;
|
||||||
|
} else {
|
||||||
|
c = this.canvasRepo.create({
|
||||||
|
channelId,
|
||||||
|
sharerUserId: userId,
|
||||||
|
title,
|
||||||
|
format,
|
||||||
|
source,
|
||||||
|
version: 1,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
c = await this.canvasRepo.save(c);
|
||||||
|
const v = this.view(c);
|
||||||
|
this.realtime.emitChannelEvent(channelId, 'canvas.updated', v);
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update the existing canvas in place — only the original sharer.
|
||||||
|
async update(
|
||||||
|
channelId: string,
|
||||||
|
userId: string,
|
||||||
|
input: { title?: string; format?: string; source?: string },
|
||||||
|
) {
|
||||||
|
await this.assertParticipant(channelId, userId);
|
||||||
|
const c = await this.canvasRepo.findOne({ where: { channelId } });
|
||||||
|
if (!c) throw new NotFoundException('no canvas shared in this channel');
|
||||||
|
if (c.sharerUserId !== userId) {
|
||||||
|
throw new ForbiddenException('only the original sharer may update the canvas');
|
||||||
|
}
|
||||||
|
const { title, format, source } = this.normalize({
|
||||||
|
title: input.title ?? c.title,
|
||||||
|
format: input.format ?? c.format,
|
||||||
|
source: input.source ?? c.source,
|
||||||
|
});
|
||||||
|
c.title = title;
|
||||||
|
c.format = format;
|
||||||
|
c.source = source;
|
||||||
|
c.version += 1;
|
||||||
|
const saved = await this.canvasRepo.save(c);
|
||||||
|
const v = this.view(saved);
|
||||||
|
this.realtime.emitChannelEvent(channelId, 'canvas.updated', v);
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
async remove(channelId: string, userId: string) {
|
||||||
|
await this.assertParticipant(channelId, userId);
|
||||||
|
const c = await this.canvasRepo.findOne({ where: { channelId } });
|
||||||
|
if (!c) return { status: 'ok' };
|
||||||
|
if (c.sharerUserId !== userId) {
|
||||||
|
throw new ForbiddenException('only the original sharer may remove the canvas');
|
||||||
|
}
|
||||||
|
await this.canvasRepo.delete({ id: c.id });
|
||||||
|
this.realtime.emitChannelEvent(channelId, 'canvas.removed', { channelId });
|
||||||
|
return { status: 'ok' };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Body, Controller, Get, Param, Post, Query, Req, UnauthorizedException } from '@nestjs/common';
|
import { Body, Controller, Get, Param, Post, Query, Req, UnauthorizedException } from '@nestjs/common';
|
||||||
import { ChannelsService } from './channels.service';
|
import { ChannelsService } from './channels.service.js';
|
||||||
|
|
||||||
// ApiKeyGuard attaches the introspected Center user id onto the request.
|
// ApiKeyGuard attaches the introspected Center user id onto the request.
|
||||||
type AuthedRequest = { userId?: string };
|
type AuthedRequest = { userId?: string };
|
||||||
@@ -29,11 +29,30 @@ export class ChannelsController {
|
|||||||
memberUserIds: Array.isArray(body.memberUserIds) ? (body.memberUserIds as string[]) : [],
|
memberUserIds: Array.isArray(body.memberUserIds) ? (body.memberUserIds as string[]) : [],
|
||||||
onDuty: body.onDuty as string | undefined,
|
onDuty: body.onDuty as string | undefined,
|
||||||
listeners: Array.isArray(body.listeners) ? (body.listeners as string[]) : [],
|
listeners: Array.isArray(body.listeners) ? (body.listeners as string[]) : [],
|
||||||
|
bypassUserIds: Array.isArray(body.bypassUserIds)
|
||||||
|
? (body.bypassUserIds as string[])
|
||||||
|
: [],
|
||||||
},
|
},
|
||||||
userId,
|
userId,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Move an order member into the bypass list (discuss/work only).
|
||||||
|
@Post(':id/bypass')
|
||||||
|
bypass(
|
||||||
|
@Req() req: AuthedRequest,
|
||||||
|
@Param('id') channelId: string,
|
||||||
|
@Body() body: Record<string, unknown>,
|
||||||
|
) {
|
||||||
|
const userId = req.userId ?? '';
|
||||||
|
if (!userId) throw new UnauthorizedException('missing user');
|
||||||
|
return this.channelsService.moveToBypass(
|
||||||
|
channelId,
|
||||||
|
userId,
|
||||||
|
String(body.userId ?? ''),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@Get(':id/members')
|
@Get(':id/members')
|
||||||
members(@Req() req: AuthedRequest, @Param('id') channelId: string) {
|
members(@Req() req: AuthedRequest, @Param('id') channelId: string) {
|
||||||
const userId = req.userId ?? '';
|
const userId = req.userId ?? '';
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
import { ChannelsController } from './channels.controller';
|
import { ChannelsController } from './channels.controller.js';
|
||||||
import { Channel } from '../entities/channel.entity';
|
import { Channel } from '../entities/channel.entity.js';
|
||||||
import { ChannelMember } from '../entities/channel-member.entity';
|
import { ChannelMember } from '../entities/channel-member.entity.js';
|
||||||
import { WakeMapping } from '../entities/wake-mapping.entity';
|
import { WakeMapping } from '../entities/wake-mapping.entity.js';
|
||||||
import { ChannelsService } from './channels.service';
|
import { ChannelsService } from './channels.service.js';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [TypeOrmModule.forFeature([Channel, ChannelMember, WakeMapping])],
|
imports: [TypeOrmModule.forFeature([Channel, ChannelMember, WakeMapping])],
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
import { BadRequestException, ForbiddenException, Injectable, NotFoundException } from '@nestjs/common';
|
import { BadRequestException, ForbiddenException, Injectable, NotFoundException } from '@nestjs/common';
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
import { In, Repository } from 'typeorm';
|
import { In, Repository } from 'typeorm';
|
||||||
import { Channel } from '../entities/channel.entity';
|
import { Channel } from '../entities/channel.entity.js';
|
||||||
import { ChannelMember } from '../entities/channel-member.entity';
|
import { ChannelMember } from '../entities/channel-member.entity.js';
|
||||||
import { WakeMapping } from '../entities/wake-mapping.entity';
|
import { WakeMapping } from '../entities/wake-mapping.entity.js';
|
||||||
import { TurnService } from './turn.service';
|
import { TurnService } from './turn.service.js';
|
||||||
|
import { RealtimeGateway } from '../realtime/realtime.gateway.js';
|
||||||
|
|
||||||
const X_TYPES = ['general', 'work', 'report', 'discuss', 'triage', 'custom'] as const;
|
const X_TYPES = ['general', 'work', 'report', 'discuss', 'triage', 'custom', 'dm'] as const;
|
||||||
type XType = (typeof X_TYPES)[number];
|
type XType = (typeof X_TYPES)[number];
|
||||||
|
|
||||||
type CreateChannelInput = {
|
type CreateChannelInput = {
|
||||||
@@ -20,6 +21,9 @@ type CreateChannelInput = {
|
|||||||
onDuty?: string;
|
onDuty?: string;
|
||||||
// optional when xType === 'custom': users to wake on this channel
|
// optional when xType === 'custom': users to wake on this channel
|
||||||
listeners?: string[];
|
listeners?: string[];
|
||||||
|
// discuss/work only: members excluded from rotation (no wakeup unless
|
||||||
|
// @-mentioned). order and bypass partition the members disjointly.
|
||||||
|
bypassUserIds?: string[];
|
||||||
};
|
};
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
@@ -32,8 +36,34 @@ export class ChannelsService {
|
|||||||
@InjectRepository(WakeMapping)
|
@InjectRepository(WakeMapping)
|
||||||
private readonly wakeRepo: Repository<WakeMapping>,
|
private readonly wakeRepo: Repository<WakeMapping>,
|
||||||
private readonly turnService: TurnService,
|
private readonly turnService: TurnService,
|
||||||
|
// RealtimeGateway is provided by the global RealtimeModule. Used to
|
||||||
|
// push channel.joined / channel.left so connected clients (e.g. the
|
||||||
|
// OpenClaw fabric plugin) can sub/unsub socket.io rooms immediately
|
||||||
|
// instead of waiting for the polling fallback.
|
||||||
|
private readonly realtime: RealtimeGateway,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
|
// Push a channel membership change to each affected user's socket-room.
|
||||||
|
// Best-effort: offline users see the new state on their next connect
|
||||||
|
// (the inbound runs an initial channel-list fetch on connect).
|
||||||
|
private notifyMembership(
|
||||||
|
kind: 'joined' | 'left',
|
||||||
|
channelId: string,
|
||||||
|
userIds: string[] | Set<string>,
|
||||||
|
extra: Record<string, unknown> = {},
|
||||||
|
): void {
|
||||||
|
const ids = userIds instanceof Set ? [...userIds] : userIds;
|
||||||
|
const payload = {
|
||||||
|
channelId,
|
||||||
|
...extra,
|
||||||
|
occurredAt: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
for (const u of ids) {
|
||||||
|
if (!u) continue;
|
||||||
|
this.realtime.emitToUser(u, `channel.${kind}`, { ...payload, userId: u });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Channels visible to a user within a guild:
|
// Channels visible to a user within a guild:
|
||||||
// - every public channel of the guild (incl. ones created before the user
|
// - every public channel of the guild (incl. ones created before the user
|
||||||
// joined the guild), OR
|
// joined the guild), OR
|
||||||
@@ -56,12 +86,13 @@ export class ChannelsService {
|
|||||||
.map((c) => ({ ...c, isMember: memberChannelIds.has(c.id) }));
|
.map((c) => ({ ...c, isMember: memberChannelIds.has(c.id) }));
|
||||||
}
|
}
|
||||||
|
|
||||||
async channelMembers(channelId: string): Promise<{ userId: string }[]> {
|
async channelMembers(channelId: string): Promise<{ userId: string; bypass: boolean }[]> {
|
||||||
const rows = await this.memberRepo.find({
|
const rows = await this.memberRepo.find({
|
||||||
where: { channelId },
|
where: { channelId },
|
||||||
order: { createdAt: 'ASC' },
|
order: { createdAt: 'ASC' },
|
||||||
});
|
});
|
||||||
return rows.map((r) => ({ userId: r.userId }));
|
const bypass = new Set(await this.turnService.getBypassUserIds(channelId));
|
||||||
|
return rows.map((r) => ({ userId: r.userId, bypass: bypass.has(r.userId) }));
|
||||||
}
|
}
|
||||||
|
|
||||||
async closeChannel(channelId: string, userId: string) {
|
async closeChannel(channelId: string, userId: string) {
|
||||||
@@ -89,6 +120,7 @@ export class ChannelsService {
|
|||||||
if (channel.xType === 'discuss' || channel.xType === 'work') {
|
if (channel.xType === 'discuss' || channel.xType === 'work') {
|
||||||
await this.turnService.onMemberAdded(channelId, userId);
|
await this.turnService.onMemberAdded(channelId, userId);
|
||||||
}
|
}
|
||||||
|
this.notifyMembership('joined', channelId, [userId], { xType: channel.xType });
|
||||||
}
|
}
|
||||||
return { status: 'ok', channelId, userId, member: true };
|
return { status: 'ok', channelId, userId, member: true };
|
||||||
}
|
}
|
||||||
@@ -98,11 +130,14 @@ export class ChannelsService {
|
|||||||
if (!channel) throw new NotFoundException('channel not found');
|
if (!channel) throw new NotFoundException('channel not found');
|
||||||
|
|
||||||
// remove every channel-scoped row that references this user
|
// remove every channel-scoped row that references this user
|
||||||
await this.memberRepo.delete({ channelId, userId });
|
const deleted = await this.memberRepo.delete({ channelId, userId });
|
||||||
await this.wakeRepo.delete({ channelId, userId });
|
await this.wakeRepo.delete({ channelId, userId });
|
||||||
if (channel.xType === 'discuss' || channel.xType === 'work') {
|
if (channel.xType === 'discuss' || channel.xType === 'work') {
|
||||||
await this.turnService.onMemberRemoved(channelId, userId);
|
await this.turnService.onMemberRemoved(channelId, userId);
|
||||||
}
|
}
|
||||||
|
if ((deleted.affected ?? 0) > 0) {
|
||||||
|
this.notifyMembership('left', channelId, [userId], { xType: channel.xType });
|
||||||
|
}
|
||||||
return { status: 'ok', channelId, userId, member: false };
|
return { status: 'ok', channelId, userId, member: false };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -126,14 +161,19 @@ export class ChannelsService {
|
|||||||
.map((x) => String(x ?? '').trim())
|
.map((x) => String(x ?? '').trim())
|
||||||
.filter(Boolean);
|
.filter(Boolean);
|
||||||
|
|
||||||
|
// dm channels are always private (a 1:1 conversation); never public.
|
||||||
|
// dm is not unique — multiple dm channels between the same users are
|
||||||
|
// allowed (create() always makes a fresh one, no dedup).
|
||||||
|
const isPublic = xType === 'dm' ? false : Boolean(input.isPublic);
|
||||||
|
|
||||||
const channel = await this.channelRepo.save(
|
const channel = await this.channelRepo.save(
|
||||||
this.channelRepo.create({
|
this.channelRepo.create({
|
||||||
guildId,
|
guildId,
|
||||||
name,
|
name,
|
||||||
xType,
|
xType,
|
||||||
kind: input.kind === 'announcement' ? 'announcement' : 'text',
|
kind: input.kind === 'announcement' ? 'announcement' : 'text',
|
||||||
isPrivate: !input.isPublic,
|
isPrivate: !isPublic,
|
||||||
isPublic: Boolean(input.isPublic),
|
isPublic,
|
||||||
lastSeq: 0,
|
lastSeq: 0,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -151,6 +191,12 @@ export class ChannelsService {
|
|||||||
[...memberIds].map((userId) => this.memberRepo.create({ channelId: channel.id, userId })),
|
[...memberIds].map((userId) => this.memberRepo.create({ channelId: channel.id, userId })),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Push channel.joined to every seeded member (creator + invitees +
|
||||||
|
// triage on-duty) so their connected sockets sub the new room
|
||||||
|
// immediately. Skips offline users — next connect's channel-list
|
||||||
|
// fetch covers them.
|
||||||
|
this.notifyMembership('joined', channel.id, memberIds, { xType });
|
||||||
|
|
||||||
// wake_mapping: triage -> the on-duty user; custom -> each listener
|
// wake_mapping: triage -> the on-duty user; custom -> each listener
|
||||||
const wakeUserIds = new Set<string>();
|
const wakeUserIds = new Set<string>();
|
||||||
if (xType === 'triage') wakeUserIds.add(onDuty);
|
if (xType === 'triage') wakeUserIds.add(onDuty);
|
||||||
@@ -164,9 +210,28 @@ export class ChannelsService {
|
|||||||
// discuss/work: initialize rotation state (order = members sorted by id,
|
// discuss/work: initialize rotation state (order = members sorted by id,
|
||||||
// currentSpeaker = null until someone proactively speaks)
|
// currentSpeaker = null until someone proactively speaks)
|
||||||
if (xType === 'discuss' || xType === 'work') {
|
if (xType === 'discuss' || xType === 'work') {
|
||||||
await this.turnService.initForChannel(channel.id, [...memberIds]);
|
const bypass = (input.bypassUserIds ?? [])
|
||||||
|
.map((x) => String(x ?? '').trim())
|
||||||
|
.filter((x) => x && memberIds.has(x));
|
||||||
|
await this.turnService.initForChannel(channel.id, [...memberIds], bypass);
|
||||||
}
|
}
|
||||||
|
|
||||||
return channel;
|
return channel;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Move an order member into the bypass list (discuss/work only).
|
||||||
|
// Any channel member may do this.
|
||||||
|
async moveToBypass(channelId: string, actorUserId: string, targetUserId: string) {
|
||||||
|
const channel = await this.channelRepo.findOne({ where: { id: channelId } });
|
||||||
|
if (!channel) throw new NotFoundException('channel not found');
|
||||||
|
if (channel.xType !== 'discuss' && channel.xType !== 'work') {
|
||||||
|
throw new BadRequestException('bypass only applies to discuss/work channels');
|
||||||
|
}
|
||||||
|
const actor = await this.memberRepo.findOne({ where: { channelId, userId: actorUserId } });
|
||||||
|
if (!actor && !channel.isPublic) throw new ForbiddenException('not a channel member');
|
||||||
|
const target = await this.memberRepo.findOne({ where: { channelId, userId: targetUserId } });
|
||||||
|
if (!target) throw new BadRequestException('target is not a channel member');
|
||||||
|
await this.turnService.moveToBypass(channelId, targetUserId);
|
||||||
|
return { status: 'ok', channelId, userId: targetUserId, bypass: true };
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { RoundEvent } from '../entities/channel-turn-state.entity';
|
import { RoundEvent } from '../entities/channel-turn-state.entity.js';
|
||||||
|
|
||||||
export type ShuffleResult = { paused: true } | { paused: false; newOrder: string[] };
|
export type ShuffleResult = { paused: true } | { paused: false; newOrder: string[] };
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Global, Module } from '@nestjs/common';
|
import { Global, Module } from '@nestjs/common';
|
||||||
import { TurnService } from './turn.service';
|
import { TurnService } from './turn.service.js';
|
||||||
|
|
||||||
@Global()
|
@Global()
|
||||||
@Module({
|
@Module({
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
import { DataSource, EntityManager } from 'typeorm';
|
import { DataSource, EntityManager } from 'typeorm';
|
||||||
import { ChannelTurnState, TurnFrame } from '../entities/channel-turn-state.entity';
|
import { ChannelTurnState, TurnFrame } from '../entities/channel-turn-state.entity.js';
|
||||||
import { ChannelMember } from '../entities/channel-member.entity';
|
import { ChannelMember } from '../entities/channel-member.entity.js';
|
||||||
import { computeShuffle } from './turn-shuffle';
|
import { computeShuffle } from './turn-shuffle.js';
|
||||||
|
|
||||||
// wakeupUserId: the single user who should receive wakeup=true on the
|
// wakeupUserId: the single user who should receive wakeup=true on the
|
||||||
// resulting push (null = nobody / paused). For commands, `ack` present means
|
// resulting push (null = nobody / paused). For commands, `ack` present means
|
||||||
@@ -43,6 +43,7 @@ export class TurnService {
|
|||||||
norepStreak: [],
|
norepStreak: [],
|
||||||
lastNormalSpeaker: null,
|
lastNormalSpeaker: null,
|
||||||
frames: [],
|
frames: [],
|
||||||
|
bypassUserIds: [],
|
||||||
});
|
});
|
||||||
return manager.save(ChannelTurnState, state);
|
return manager.save(ChannelTurnState, state);
|
||||||
}
|
}
|
||||||
@@ -52,6 +53,21 @@ export class TurnService {
|
|||||||
return state.frames;
|
return state.frames;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private bypass(state: ChannelTurnState): string[] {
|
||||||
|
if (!Array.isArray(state.bypassUserIds)) state.bypassUserIds = [];
|
||||||
|
return state.bypassUserIds;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Push a mention sub-frame, enforcing the nesting cap. Max 4 sub-frames
|
||||||
|
// (5 levels incl. root); a 5th push evicts the bottom-most sub-frame
|
||||||
|
// (the one directly above root) and shifts the rest down:
|
||||||
|
// root->A->B->C->D + E => root->B->C->D->E
|
||||||
|
private pushFrame(state: ChannelTurnState, order: string[]): void {
|
||||||
|
const fr = this.frames(state);
|
||||||
|
while (fr.length >= 4) fr.shift();
|
||||||
|
fr.push({ order, idx: 0 });
|
||||||
|
}
|
||||||
|
|
||||||
// effective current speaker = top sub-frame's pointer, else root speaker
|
// effective current speaker = top sub-frame's pointer, else root speaker
|
||||||
private effectiveCurrent(state: ChannelTurnState): string | null {
|
private effectiveCurrent(state: ChannelTurnState): string | null {
|
||||||
const fr = this.frames(state);
|
const fr = this.frames(state);
|
||||||
@@ -80,10 +96,17 @@ export class TurnService {
|
|||||||
return this.effectiveCurrent(state);
|
return this.effectiveCurrent(state);
|
||||||
}
|
}
|
||||||
|
|
||||||
async initForChannel(channelId: string, memberUserIds: string[]): Promise<void> {
|
async initForChannel(
|
||||||
|
channelId: string,
|
||||||
|
memberUserIds: string[],
|
||||||
|
bypassUserIds: string[] = [],
|
||||||
|
): Promise<void> {
|
||||||
await this.dataSource.transaction(async (manager) => {
|
await this.dataSource.transaction(async (manager) => {
|
||||||
const existing = await manager.findOne(ChannelTurnState, { where: { channelId } });
|
const existing = await manager.findOne(ChannelTurnState, { where: { channelId } });
|
||||||
const order = [...new Set(memberUserIds)].sort();
|
const members = [...new Set(memberUserIds)];
|
||||||
|
const bypassSet = new Set(bypassUserIds.filter((u) => members.includes(u)));
|
||||||
|
// order and bypass are a disjoint partition of members
|
||||||
|
const order = members.filter((u) => !bypassSet.has(u)).sort();
|
||||||
const base = {
|
const base = {
|
||||||
orderUserIds: order,
|
orderUserIds: order,
|
||||||
currentSpeaker: null,
|
currentSpeaker: null,
|
||||||
@@ -91,6 +114,7 @@ export class TurnService {
|
|||||||
norepStreak: [] as string[],
|
norepStreak: [] as string[],
|
||||||
lastNormalSpeaker: null,
|
lastNormalSpeaker: null,
|
||||||
frames: [] as TurnFrame[],
|
frames: [] as TurnFrame[],
|
||||||
|
bypassUserIds: [...bypassSet],
|
||||||
};
|
};
|
||||||
if (existing) {
|
if (existing) {
|
||||||
Object.assign(existing, base);
|
Object.assign(existing, base);
|
||||||
@@ -101,16 +125,53 @@ export class TurnService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Read-only: userIds currently in the bypass list (no rotation wakeup
|
||||||
|
// unless @-mentioned). Empty if no turn state / not discuss-work.
|
||||||
|
async getBypassUserIds(channelId: string): Promise<string[]> {
|
||||||
|
const state = await this.dataSource
|
||||||
|
.getRepository(ChannelTurnState)
|
||||||
|
.findOne({ where: { channelId } });
|
||||||
|
return state && Array.isArray(state.bypassUserIds) ? state.bypassUserIds : [];
|
||||||
|
}
|
||||||
|
|
||||||
async onMemberAdded(channelId: string, userId: string): Promise<void> {
|
async onMemberAdded(channelId: string, userId: string): Promise<void> {
|
||||||
await this.dataSource.transaction(async (manager) => {
|
await this.dataSource.transaction(async (manager) => {
|
||||||
const state = await this.ensureState(manager, channelId);
|
const state = await this.ensureState(manager, channelId);
|
||||||
if (!state.orderUserIds.includes(userId)) {
|
const inBypass = this.bypass(state).includes(userId);
|
||||||
|
if (!state.orderUserIds.includes(userId) && !inBypass) {
|
||||||
state.orderUserIds = [...state.orderUserIds, userId];
|
state.orderUserIds = [...state.orderUserIds, userId];
|
||||||
await manager.save(ChannelTurnState, state);
|
await manager.save(ChannelTurnState, state);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Move an order member into the bypass list (any channel member may do
|
||||||
|
// this). If they are the current speaker, the next one takes over.
|
||||||
|
async moveToBypass(channelId: string, userId: string): Promise<void> {
|
||||||
|
await this.dataSource.transaction(async (manager) => {
|
||||||
|
const state = await this.ensureState(manager, channelId);
|
||||||
|
const order = state.orderUserIds;
|
||||||
|
const idx = order.indexOf(userId);
|
||||||
|
if (idx === -1) return; // not in rotation (already bypass / unknown)
|
||||||
|
|
||||||
|
if (state.currentSpeaker === userId) {
|
||||||
|
const next = order.length > 1 ? order[(idx + 1) % order.length] : null;
|
||||||
|
state.currentSpeaker = next === userId ? null : next;
|
||||||
|
}
|
||||||
|
state.orderUserIds = order.filter((u) => u !== userId);
|
||||||
|
if (!state.orderUserIds.length) state.currentSpeaker = null;
|
||||||
|
state.norepStreak = state.norepStreak.filter((u) => u !== userId);
|
||||||
|
// remove from active sub-frames (re-enters only via a future mention)
|
||||||
|
state.frames = this.frames(state)
|
||||||
|
.map((f) => ({ order: f.order.filter((u) => u !== userId), idx: f.idx }))
|
||||||
|
.filter((f) => f.order.length > 0)
|
||||||
|
.map((f) => ({ order: f.order, idx: Math.min(f.idx, f.order.length - 1) }));
|
||||||
|
const bp = this.bypass(state);
|
||||||
|
if (!bp.includes(userId)) bp.push(userId);
|
||||||
|
await manager.save(ChannelTurnState, state);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
async onMemberRemoved(channelId: string, userId: string): Promise<void> {
|
async onMemberRemoved(channelId: string, userId: string): Promise<void> {
|
||||||
await this.dataSource.transaction(async (manager) => {
|
await this.dataSource.transaction(async (manager) => {
|
||||||
const state = await this.loadLocked(manager, channelId);
|
const state = await this.loadLocked(manager, channelId);
|
||||||
@@ -128,6 +189,7 @@ export class TurnService {
|
|||||||
state.currentSpeaker = state.orderUserIds.length ? nextCurrent : null;
|
state.currentSpeaker = state.orderUserIds.length ? nextCurrent : null;
|
||||||
}
|
}
|
||||||
state.norepStreak = state.norepStreak.filter((u) => u !== userId);
|
state.norepStreak = state.norepStreak.filter((u) => u !== userId);
|
||||||
|
state.bypassUserIds = this.bypass(state).filter((u) => u !== userId);
|
||||||
|
|
||||||
// strip the leaver from every sub-frame; drop emptied frames; clamp idx
|
// strip the leaver from every sub-frame; drop emptied frames; clamp idx
|
||||||
const fr = this.frames(state)
|
const fr = this.frames(state)
|
||||||
@@ -165,7 +227,7 @@ export class TurnService {
|
|||||||
const cur = top.order[Math.min(top.idx, top.order.length - 1)];
|
const cur = top.order[Math.min(top.idx, top.order.length - 1)];
|
||||||
if (authorUserId === cur) {
|
if (authorUserId === cur) {
|
||||||
if (atList.length) {
|
if (atList.length) {
|
||||||
fr.push({ order: atList, idx: 0 });
|
this.pushFrame(state, atList);
|
||||||
await manager.save(ChannelTurnState, state);
|
await manager.save(ChannelTurnState, state);
|
||||||
return { wakeupUserId: atList[0] };
|
return { wakeupUserId: atList[0] };
|
||||||
}
|
}
|
||||||
@@ -202,7 +264,7 @@ export class TurnService {
|
|||||||
// current speaker mentioning -> push a sub-frame; root pointer (this
|
// current speaker mentioning -> push a sub-frame; root pointer (this
|
||||||
// speaker) is left as-is and resumes after the sub-frame pops
|
// speaker) is left as-is and resumes after the sub-frame pops
|
||||||
if (atList.length) {
|
if (atList.length) {
|
||||||
fr.push({ order: atList, idx: 0 });
|
this.pushFrame(state, atList);
|
||||||
await manager.save(ChannelTurnState, state);
|
await manager.save(ChannelTurnState, state);
|
||||||
return { wakeupUserId: atList[0] };
|
return { wakeupUserId: atList[0] };
|
||||||
}
|
}
|
||||||
|
|||||||
39
src/cli/admin-refresh.ts
Normal file
39
src/cli/admin-refresh.ts
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
// Operator convenience: force-refresh the in-memory Center admin cache
|
||||||
|
// without waiting for the 1-day TTL. Used after `center user set-admin`
|
||||||
|
// to make new admin visible immediately to triage delivery.
|
||||||
|
//
|
||||||
|
// Usage (inside the deployed container):
|
||||||
|
// docker exec fabric-backend-guild node dist/cli/admin-refresh.js
|
||||||
|
//
|
||||||
|
// Prints the (possibly null) result as JSON. Exit 0 always — a "no
|
||||||
|
// admin" outcome is a valid state, not an error.
|
||||||
|
|
||||||
|
import 'reflect-metadata';
|
||||||
|
import { NestFactory } from '@nestjs/core';
|
||||||
|
import { AppModule } from '../app.module.js';
|
||||||
|
import { AdminCacheService } from '../common/admin-cache.service.js';
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const app = await NestFactory.createApplicationContext(AppModule, { logger: ['error', 'warn'] });
|
||||||
|
try {
|
||||||
|
const cache = app.get(AdminCacheService);
|
||||||
|
const before = cache.snapshot();
|
||||||
|
const after = await cache.get(true);
|
||||||
|
process.stdout.write(
|
||||||
|
JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
before,
|
||||||
|
after,
|
||||||
|
changed: JSON.stringify(before) !== JSON.stringify(after),
|
||||||
|
}) + '\n',
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
await app.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void main().catch((error: unknown) => {
|
||||||
|
const message = error instanceof Error ? error.message : 'unknown error';
|
||||||
|
process.stderr.write(JSON.stringify({ ok: false, error: message }) + '\n');
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
37
src/cli/print-commands-sync-key.ts
Normal file
37
src/cli/print-commands-sync-key.ts
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
// Operator convenience (Guild C-2): print the commands-sync key that this
|
||||||
|
// guild process actually has in its environment, so it can be copied into
|
||||||
|
// the OpenClaw plugin's FABRIC_COMMANDS_SYNC_KEY.
|
||||||
|
//
|
||||||
|
// Usage (inside the deployed container — authoritative, reflects compose):
|
||||||
|
// docker exec fabric-backend-guild node dist/cli/print-commands-sync-key.js
|
||||||
|
// docker exec fabric-backend-guild node dist/cli/print-commands-sync-key.js --export
|
||||||
|
//
|
||||||
|
// Default: prints the raw value only (so KEY=$(... ) works).
|
||||||
|
// --export: prints `FABRIC_COMMANDS_SYNC_KEY=<value>` for pasting.
|
||||||
|
// Exit 1 (no stdout) when unset — guild is then in the weaker
|
||||||
|
// "any authenticated user" fallback for PUT /commands.
|
||||||
|
|
||||||
|
const args = new Set(process.argv.slice(2));
|
||||||
|
|
||||||
|
if (args.has('--help') || args.has('-h')) {
|
||||||
|
process.stderr.write(
|
||||||
|
'print-commands-sync-key: outputs FABRIC_BACKEND_GUILD_COMMANDS_SYNC_KEY\n' +
|
||||||
|
' (no flag) print the raw key value\n' +
|
||||||
|
' --export print FABRIC_COMMANDS_SYNC_KEY=<value>\n',
|
||||||
|
);
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
const key = (process.env.FABRIC_BACKEND_GUILD_COMMANDS_SYNC_KEY ?? '').trim();
|
||||||
|
|
||||||
|
if (!key) {
|
||||||
|
process.stderr.write(
|
||||||
|
'FABRIC_BACKEND_GUILD_COMMANDS_SYNC_KEY is not set — PUT /commands is in ' +
|
||||||
|
'the fallback mode (any authenticated user). Set it to harden (Guild C-2).\n',
|
||||||
|
);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
process.stdout.write(
|
||||||
|
(args.has('--export') ? `FABRIC_COMMANDS_SYNC_KEY=${key}` : key) + '\n',
|
||||||
|
);
|
||||||
57
src/commands/commands.controller.ts
Normal file
57
src/commands/commands.controller.ts
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
ForbiddenException,
|
||||||
|
Get,
|
||||||
|
Headers,
|
||||||
|
Put,
|
||||||
|
Req,
|
||||||
|
UnauthorizedException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { timingSafeEqual } from 'node:crypto';
|
||||||
|
import { CommandsService } from './commands.service.js';
|
||||||
|
import { SyncCommandsDto } from './dto.sync-commands.dto.js';
|
||||||
|
|
||||||
|
type AuthedRequest = { userId?: string };
|
||||||
|
|
||||||
|
function safeEqual(a: string, b: string): boolean {
|
||||||
|
const ab = Buffer.from(a);
|
||||||
|
const bb = Buffer.from(b);
|
||||||
|
if (ab.length !== bb.length) return false;
|
||||||
|
return timingSafeEqual(ab, bb);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Controller('commands')
|
||||||
|
export class CommandsController {
|
||||||
|
constructor(private readonly commands: CommandsService) {}
|
||||||
|
|
||||||
|
// Guild C-2: catalog write is privileged. When
|
||||||
|
// FABRIC_BACKEND_GUILD_COMMANDS_SYNC_KEY is configured (recommended in
|
||||||
|
// production), the caller must present a matching x-commands-sync-key
|
||||||
|
// header — this restricts writes to the OpenClaw plugin. When unset, we
|
||||||
|
// fall back to "any authenticated agent/user" (never weaker than before).
|
||||||
|
// The body is always strictly validated + size-capped via SyncCommandsDto.
|
||||||
|
@Put()
|
||||||
|
sync(
|
||||||
|
@Req() req: AuthedRequest,
|
||||||
|
@Body() body: SyncCommandsDto,
|
||||||
|
@Headers('x-commands-sync-key') syncKey?: string,
|
||||||
|
) {
|
||||||
|
const configured = process.env.FABRIC_BACKEND_GUILD_COMMANDS_SYNC_KEY ?? '';
|
||||||
|
if (configured) {
|
||||||
|
if (!syncKey || !safeEqual(syncKey, configured)) {
|
||||||
|
throw new ForbiddenException('invalid commands sync key');
|
||||||
|
}
|
||||||
|
} else if (!req.userId) {
|
||||||
|
throw new UnauthorizedException('missing user');
|
||||||
|
}
|
||||||
|
return this.commands.sync(body.commands as unknown[]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Frontend reads the catalog to drive `/` autocomplete.
|
||||||
|
@Get()
|
||||||
|
list(@Req() req: AuthedRequest) {
|
||||||
|
if (!req.userId) throw new UnauthorizedException('missing user');
|
||||||
|
return this.commands.list();
|
||||||
|
}
|
||||||
|
}
|
||||||
12
src/commands/commands.module.ts
Normal file
12
src/commands/commands.module.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { GuildCommand } from '../entities/guild-command.entity.js';
|
||||||
|
import { CommandsController } from './commands.controller.js';
|
||||||
|
import { CommandsService } from './commands.service.js';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [TypeOrmModule.forFeature([GuildCommand])],
|
||||||
|
controllers: [CommandsController],
|
||||||
|
providers: [CommandsService],
|
||||||
|
})
|
||||||
|
export class CommandsModule {}
|
||||||
39
src/commands/commands.service.ts
Normal file
39
src/commands/commands.service.ts
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
|
import { Repository } from 'typeorm';
|
||||||
|
import { GuildCommand } from '../entities/guild-command.entity.js';
|
||||||
|
|
||||||
|
// This node's guild id (one guild per node).
|
||||||
|
function guildId(): string {
|
||||||
|
return process.env.FABRIC_BACKEND_GUILD_NODE_ID ?? 'guild';
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class CommandsService {
|
||||||
|
constructor(
|
||||||
|
@InjectRepository(GuildCommand)
|
||||||
|
private readonly repo: Repository<GuildCommand>,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
// Replace the whole guild-global slash-command catalog (idempotent;
|
||||||
|
// the plugin re-PUTs the full set on every gateway start).
|
||||||
|
async sync(commands: unknown[]): Promise<{ status: string; count: number }> {
|
||||||
|
const gid = guildId();
|
||||||
|
let row = await this.repo.findOne({ where: { guildId: gid } });
|
||||||
|
if (row) {
|
||||||
|
row.commands = commands;
|
||||||
|
} else {
|
||||||
|
row = this.repo.create({ guildId: gid, commands });
|
||||||
|
}
|
||||||
|
await this.repo.save(row);
|
||||||
|
return { status: 'ok', count: commands.length };
|
||||||
|
}
|
||||||
|
|
||||||
|
async list(): Promise<{ commands: unknown[]; updatedAt: string | null }> {
|
||||||
|
const row = await this.repo.findOne({ where: { guildId: guildId() } });
|
||||||
|
return {
|
||||||
|
commands: row?.commands ?? [],
|
||||||
|
updatedAt: row?.updatedAt ? row.updatedAt.toISOString() : null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
102
src/commands/dto.sync-commands.dto.ts
Normal file
102
src/commands/dto.sync-commands.dto.ts
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
import {
|
||||||
|
ArrayMaxSize,
|
||||||
|
IsArray,
|
||||||
|
IsBoolean,
|
||||||
|
IsOptional,
|
||||||
|
IsString,
|
||||||
|
MaxLength,
|
||||||
|
ValidateNested,
|
||||||
|
} from 'class-validator';
|
||||||
|
import { Type } from 'class-transformer';
|
||||||
|
|
||||||
|
// Guild C-2: the slash-command catalog is guild-global and rendered by the
|
||||||
|
// frontend `/` autocomplete. Without a strict schema + caps a single
|
||||||
|
// authenticated caller could poison it or blow up the DB / clients.
|
||||||
|
// The global ValidationPipe runs with { whitelist, forbidNonWhitelisted },
|
||||||
|
// so any unknown field is rejected.
|
||||||
|
|
||||||
|
class CommandChoiceDto {
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(200)
|
||||||
|
value!: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(200)
|
||||||
|
label!: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
class CommandArgDto {
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(100)
|
||||||
|
name!: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(500)
|
||||||
|
description?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(40)
|
||||||
|
type?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
required?: boolean;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
captureRemaining?: boolean;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
preferAutocomplete?: boolean;
|
||||||
|
|
||||||
|
// null when there are no choices (plugin sends explicit null).
|
||||||
|
@IsOptional()
|
||||||
|
@IsArray()
|
||||||
|
@ArrayMaxSize(100)
|
||||||
|
@ValidateNested({ each: true })
|
||||||
|
@Type(() => CommandChoiceDto)
|
||||||
|
choices?: CommandChoiceDto[] | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
class CommandSpecDto {
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(100)
|
||||||
|
name!: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(100)
|
||||||
|
nativeName?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(500)
|
||||||
|
description?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
acceptsArgs?: boolean;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsArray()
|
||||||
|
@ArrayMaxSize(50)
|
||||||
|
@ValidateNested({ each: true })
|
||||||
|
@Type(() => CommandArgDto)
|
||||||
|
args?: CommandArgDto[];
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(20)
|
||||||
|
argsParsing?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class SyncCommandsDto {
|
||||||
|
@IsArray()
|
||||||
|
@ArrayMaxSize(200)
|
||||||
|
@ValidateNested({ each: true })
|
||||||
|
@Type(() => CommandSpecDto)
|
||||||
|
commands!: CommandSpecDto[];
|
||||||
|
}
|
||||||
73
src/common/admin-cache.service.ts
Normal file
73
src/common/admin-cache.service.ts
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
/**
|
||||||
|
* Center-scoped admin cache.
|
||||||
|
*
|
||||||
|
* Holds the at-most-one admin user (email + userId) fetched from Center.
|
||||||
|
* Used to decide who to deliver triage messages to as a silent observer
|
||||||
|
* (wake=false), regardless of on-duty / mention status.
|
||||||
|
*
|
||||||
|
* Refresh policy (per spec, 2026-05-22):
|
||||||
|
* • TTL = 1 day. Center admin changes are rare; agents tolerate a
|
||||||
|
* day's stale cache without surprises
|
||||||
|
* • on first lookup the cache lazy-fetches
|
||||||
|
* • cli `admin refresh` forces an out-of-band refresh without waiting
|
||||||
|
* for TTL expiry
|
||||||
|
*
|
||||||
|
* Failure mode: a Center fetch error is treated identically to "no
|
||||||
|
* admin" — guild keeps operating without an observer. The cache holds
|
||||||
|
* the failed-fetch decision for the same TTL so we don't hammer Center.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
|
import { fetchAdminEmail } from './center-auth.js';
|
||||||
|
|
||||||
|
const ADMIN_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
|
||||||
|
|
||||||
|
export interface CachedAdmin {
|
||||||
|
email: string;
|
||||||
|
userId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AdminCacheService {
|
||||||
|
private readonly logger = new Logger(AdminCacheService.name);
|
||||||
|
private cached: CachedAdmin | null = null;
|
||||||
|
private cachedAt = 0;
|
||||||
|
private inflight: Promise<CachedAdmin | null> | null = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return the cached admin, fetching from Center if the cache is empty
|
||||||
|
* or older than the TTL. Returns null if no admin is set.
|
||||||
|
*
|
||||||
|
* `force=true` bypasses the cache and refreshes immediately — used by
|
||||||
|
* the cli refresh command.
|
||||||
|
*/
|
||||||
|
async get(force = false): Promise<CachedAdmin | null> {
|
||||||
|
const fresh = Date.now() - this.cachedAt < ADMIN_CACHE_TTL_MS;
|
||||||
|
if (!force && this.cachedAt > 0 && fresh) {
|
||||||
|
return this.cached;
|
||||||
|
}
|
||||||
|
if (this.inflight) return this.inflight;
|
||||||
|
|
||||||
|
this.inflight = (async () => {
|
||||||
|
try {
|
||||||
|
const result = await fetchAdminEmail();
|
||||||
|
this.cached = result;
|
||||||
|
this.cachedAt = Date.now();
|
||||||
|
this.logger.log(
|
||||||
|
`admin cache refreshed: ${result ? `${result.email} (${result.userId})` : 'no admin set'}`,
|
||||||
|
);
|
||||||
|
return result;
|
||||||
|
} finally {
|
||||||
|
this.inflight = null;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
return this.inflight;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Snapshot of the cached admin (no fetch). Returns null if not yet
|
||||||
|
* populated. Used by the hot delivery path which doesn't want to
|
||||||
|
* block on a Center round-trip. */
|
||||||
|
snapshot(): CachedAdmin | null {
|
||||||
|
return this.cached;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,12 +4,16 @@ import {
|
|||||||
Injectable,
|
Injectable,
|
||||||
UnauthorizedException,
|
UnauthorizedException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { introspectGuildToken } from './center-auth';
|
import { introspectGuildToken } from './center-auth.js';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class ApiKeyGuard implements CanActivate {
|
export class ApiKeyGuard implements CanActivate {
|
||||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||||
const req = context.switchToHttp().getRequest<{ path?: string; headers: Record<string, string | string[] | undefined> }>();
|
const req = context.switchToHttp().getRequest<{
|
||||||
|
path?: string;
|
||||||
|
headers: Record<string, string | string[] | undefined>;
|
||||||
|
query?: Record<string, string | string[] | undefined>;
|
||||||
|
}>();
|
||||||
const path = req.path ?? '';
|
const path = req.path ?? '';
|
||||||
|
|
||||||
// allow health check without auth
|
// allow health check without auth
|
||||||
@@ -19,7 +23,13 @@ export class ApiKeyGuard implements CanActivate {
|
|||||||
|
|
||||||
const auth = req.headers['authorization'];
|
const auth = req.headers['authorization'];
|
||||||
const authValue = Array.isArray(auth) ? auth[0] : auth;
|
const authValue = Array.isArray(auth) ? auth[0] : auth;
|
||||||
const token = authValue?.startsWith('Bearer ') ? authValue.slice(7) : '';
|
let token = authValue?.startsWith('Bearer ') ? authValue.slice(7) : '';
|
||||||
|
// Browsers can't set Authorization on <img>/<a> (file downloads); accept
|
||||||
|
// the guild token via ?access_token= as a fallback. Still introspected.
|
||||||
|
if (!token) {
|
||||||
|
const qt = req.query?.['access_token'];
|
||||||
|
token = (Array.isArray(qt) ? qt[0] : qt) ?? '';
|
||||||
|
}
|
||||||
if (!token) throw new UnauthorizedException('missing bearer token');
|
if (!token) throw new UnauthorizedException('missing bearer token');
|
||||||
|
|
||||||
const result = await introspectGuildToken(token);
|
const result = await introspectGuildToken(token);
|
||||||
|
|||||||
@@ -26,6 +26,31 @@ export async function introspectGuildToken(token: string): Promise<{ active: boo
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch the single Center-scoped admin user (if any).
|
||||||
|
* Same x-api-key auth as introspect / resolve-names.
|
||||||
|
* Returns `null` when no admin is set OR the request fails (treated
|
||||||
|
* identically — the guild simply falls back to "no admin observer").
|
||||||
|
*/
|
||||||
|
export async function fetchAdminEmail(): Promise<{ email: string; userId: string } | null> {
|
||||||
|
const centerBaseUrl = process.env.FABRIC_BACKEND_GUILD_CENTER_BASE_URL;
|
||||||
|
const centerApiKey = process.env.FABRIC_BACKEND_GUILD_CENTER_API_KEY;
|
||||||
|
if (!centerBaseUrl || !centerApiKey) return null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${centerBaseUrl}/api/auth/admin-email`, {
|
||||||
|
method: 'GET',
|
||||||
|
headers: { 'x-api-key': centerApiKey },
|
||||||
|
});
|
||||||
|
if (!res.ok) return null;
|
||||||
|
const data = (await res.json()) as { email?: string; userId?: string } | null;
|
||||||
|
if (!data || !data.email || !data.userId) return null;
|
||||||
|
return { email: data.email, userId: data.userId };
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Resolve <@user.name:NAME> names to userIds within this guild node via
|
// Resolve <@user.name:NAME> names to userIds within this guild node via
|
||||||
// Center. Unresolved names are simply absent from the returned map.
|
// Center. Unresolved names are simply absent from the returned map.
|
||||||
export async function resolveUserNames(names: string[]): Promise<Record<string, string>> {
|
export async function resolveUserNames(names: string[]): Promise<Record<string, string>> {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Controller, Get } from '@nestjs/common';
|
import { Controller, Get } from '@nestjs/common';
|
||||||
import { MetricsService } from './metrics.service';
|
import { MetricsService } from './metrics.service.js';
|
||||||
|
|
||||||
@Controller('metrics')
|
@Controller('metrics')
|
||||||
export class MetricsController {
|
export class MetricsController {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { randomUUID } from 'crypto';
|
import { randomUUID } from 'crypto';
|
||||||
import { NextFunction, Request, Response } from 'express';
|
import { NextFunction, Request, Response } from 'express';
|
||||||
import { MetricsService } from './metrics.service';
|
import { MetricsService } from './metrics.service.js';
|
||||||
|
|
||||||
type ReqWithId = Request & { requestId?: string };
|
type ReqWithId = Request & { requestId?: string };
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import 'reflect-metadata';
|
import 'reflect-metadata';
|
||||||
import { DataSource, DataSourceOptions } from 'typeorm';
|
import { DataSource, DataSourceOptions } from 'typeorm';
|
||||||
import { buildTypeOrmConfig } from './database.config';
|
import { buildTypeOrmConfig } from './database.config.js';
|
||||||
|
|
||||||
const cfg = buildTypeOrmConfig();
|
const cfg = buildTypeOrmConfig();
|
||||||
|
|
||||||
|
|||||||
@@ -1,16 +1,19 @@
|
|||||||
import { TypeOrmModuleOptions } from '@nestjs/typeorm';
|
import { TypeOrmModuleOptions } from '@nestjs/typeorm';
|
||||||
import { Guild } from './entities/guild.entity';
|
import { Guild } from './entities/guild.entity.js';
|
||||||
import { Channel } from './entities/channel.entity';
|
import { Channel } from './entities/channel.entity.js';
|
||||||
import { ChannelMember } from './entities/channel-member.entity';
|
import { ChannelMember } from './entities/channel-member.entity.js';
|
||||||
import { WakeMapping } from './entities/wake-mapping.entity';
|
import { WakeMapping } from './entities/wake-mapping.entity.js';
|
||||||
import { ChannelTurnState } from './entities/channel-turn-state.entity';
|
import { ChannelTurnState } from './entities/channel-turn-state.entity.js';
|
||||||
import { Message } from './entities/message.entity';
|
import { Message } from './entities/message.entity.js';
|
||||||
import { DmConversation } from './entities/dm-conversation.entity';
|
import { DmConversation } from './entities/dm-conversation.entity.js';
|
||||||
import { DmParticipant } from './entities/dm-participant.entity';
|
import { DmParticipant } from './entities/dm-participant.entity.js';
|
||||||
import { GuildRole } from './entities/guild-role.entity';
|
import { GuildRole } from './entities/guild-role.entity.js';
|
||||||
import { GuildMember } from './entities/guild-member.entity';
|
import { GuildMember } from './entities/guild-member.entity.js';
|
||||||
import { GuildMemberRole } from './entities/guild-member-role.entity';
|
import { GuildMemberRole } from './entities/guild-member-role.entity.js';
|
||||||
import { IdempotencyRecord } from './entities/idempotency-record.entity';
|
import { IdempotencyRecord } from './entities/idempotency-record.entity.js';
|
||||||
|
import { StoredFile } from './entities/stored-file.entity.js';
|
||||||
|
import { ChannelCanvas } from './entities/channel-canvas.entity.js';
|
||||||
|
import { GuildCommand } from './entities/guild-command.entity.js';
|
||||||
|
|
||||||
export const buildTypeOrmConfig = (): TypeOrmModuleOptions => ({
|
export const buildTypeOrmConfig = (): TypeOrmModuleOptions => ({
|
||||||
type: 'mysql',
|
type: 'mysql',
|
||||||
@@ -32,6 +35,9 @@ export const buildTypeOrmConfig = (): TypeOrmModuleOptions => ({
|
|||||||
GuildMember,
|
GuildMember,
|
||||||
GuildMemberRole,
|
GuildMemberRole,
|
||||||
IdempotencyRecord,
|
IdempotencyRecord,
|
||||||
|
StoredFile,
|
||||||
|
ChannelCanvas,
|
||||||
|
GuildCommand,
|
||||||
],
|
],
|
||||||
synchronize: (process.env.FABRIC_BACKEND_GUILD_DB_SYNC ?? 'true') === 'true',
|
synchronize: (process.env.FABRIC_BACKEND_GUILD_DB_SYNC ?? 'true') === 'true',
|
||||||
logging: (process.env.FABRIC_BACKEND_GUILD_DB_LOGGING ?? 'false') === 'true',
|
logging: (process.env.FABRIC_BACKEND_GUILD_DB_LOGGING ?? 'false') === 'true',
|
||||||
|
|||||||
46
src/entities/channel-canvas.entity.ts
Normal file
46
src/entities/channel-canvas.entity.ts
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
import {
|
||||||
|
Column,
|
||||||
|
CreateDateColumn,
|
||||||
|
Entity,
|
||||||
|
Index,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
UpdateDateColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
|
||||||
|
export type CanvasFormat = 'md' | 'html' | 'text';
|
||||||
|
|
||||||
|
// One active shared document per channel (ChatGPT-canvas-like). Re-sharing
|
||||||
|
// replaces it; only the original sharer may update it in place. Pinned in
|
||||||
|
// the channel UI, independent of the message scroll.
|
||||||
|
@Entity('channel_canvas')
|
||||||
|
export class ChannelCanvas {
|
||||||
|
@PrimaryGeneratedColumn('uuid')
|
||||||
|
id!: string;
|
||||||
|
|
||||||
|
@Index({ unique: true })
|
||||||
|
@Column({ name: 'channel_id', type: 'char', length: 36 })
|
||||||
|
channelId!: string;
|
||||||
|
|
||||||
|
// who shared it; only this user may PATCH/DELETE
|
||||||
|
@Column({ name: 'sharer_user_id', type: 'varchar', length: 64 })
|
||||||
|
sharerUserId!: string;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', length: 200 })
|
||||||
|
title!: string;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', length: 8 })
|
||||||
|
format!: CanvasFormat;
|
||||||
|
|
||||||
|
// raw document source (rendered client-side per format)
|
||||||
|
@Column({ type: 'mediumtext' })
|
||||||
|
source!: string;
|
||||||
|
|
||||||
|
@Column({ type: 'int', default: 1 })
|
||||||
|
version!: number;
|
||||||
|
|
||||||
|
@CreateDateColumn()
|
||||||
|
createdAt!: Date;
|
||||||
|
|
||||||
|
@UpdateDateColumn()
|
||||||
|
updatedAt!: Date;
|
||||||
|
}
|
||||||
@@ -18,10 +18,17 @@ export class ChannelTurnState {
|
|||||||
@Column({ name: 'channel_id', type: 'char', length: 36 })
|
@Column({ name: 'channel_id', type: 'char', length: 36 })
|
||||||
channelId!: string;
|
channelId!: string;
|
||||||
|
|
||||||
// speaking order; userIds
|
// speaking order; userIds. order and bypass are a DISJOINT partition of
|
||||||
|
// the channel's members.
|
||||||
@Column({ name: 'order_user_ids', type: 'json' })
|
@Column({ name: 'order_user_ids', type: 'json' })
|
||||||
orderUserIds!: string[];
|
orderUserIds!: string[];
|
||||||
|
|
||||||
|
// members excluded from rotation: never woken by normal rotation, only when
|
||||||
|
// @-mentioned (then transiently pulled into a sub-frame; back to bypass on
|
||||||
|
// pop). discuss/work only.
|
||||||
|
@Column({ name: 'bypass_user_ids', type: 'json', nullable: true })
|
||||||
|
bypassUserIds!: string[] | null;
|
||||||
|
|
||||||
// null = paused (created, or all-members-consecutively-/no-reply)
|
// null = paused (created, or all-members-consecutively-/no-reply)
|
||||||
@Column({ name: 'current_speaker', type: 'varchar', length: 64, nullable: true })
|
@Column({ name: 'current_speaker', type: 'varchar', length: 64, nullable: true })
|
||||||
currentSpeaker!: string | null;
|
currentSpeaker!: string | null;
|
||||||
|
|||||||
@@ -16,9 +16,9 @@ export class Channel {
|
|||||||
@Column({
|
@Column({
|
||||||
name: 'x_type',
|
name: 'x_type',
|
||||||
type: 'enum',
|
type: 'enum',
|
||||||
enum: ['general', 'work', 'report', 'discuss', 'triage', 'custom'],
|
enum: ['general', 'work', 'report', 'discuss', 'triage', 'custom', 'dm'],
|
||||||
})
|
})
|
||||||
xType!: 'general' | 'work' | 'report' | 'discuss' | 'triage' | 'custom';
|
xType!: 'general' | 'work' | 'report' | 'discuss' | 'triage' | 'custom' | 'dm';
|
||||||
|
|
||||||
@Column({ type: 'varchar', length: 16, default: 'text' })
|
@Column({ type: 'varchar', length: 16, default: 'text' })
|
||||||
kind!: 'text' | 'announcement';
|
kind!: 'text' | 'announcement';
|
||||||
|
|||||||
25
src/entities/guild-command.entity.ts
Normal file
25
src/entities/guild-command.entity.ts
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
import { Column, Entity, Index, PrimaryGeneratedColumn, UpdateDateColumn } from 'typeorm';
|
||||||
|
|
||||||
|
// Guild-global slash-command catalog. One row per guild (this node's
|
||||||
|
// FABRIC_BACKEND_GUILD_NODE_ID). The OpenClaw plugin PUTs the OpenClaw
|
||||||
|
// native-command specs here (the same data Discord registers as slash
|
||||||
|
// commands); the frontend GETs it to drive `/` autocomplete. The guild
|
||||||
|
// node stores the catalog opaquely — it does not interpret command bodies.
|
||||||
|
@Entity('guild_commands')
|
||||||
|
export class GuildCommand {
|
||||||
|
@PrimaryGeneratedColumn('uuid')
|
||||||
|
id!: string;
|
||||||
|
|
||||||
|
@Index({ unique: true })
|
||||||
|
@Column({ name: 'guild_id', type: 'varchar', length: 80 })
|
||||||
|
guildId!: string;
|
||||||
|
|
||||||
|
// NativeCommandSpec[]-shaped (name, nativeName, description, acceptsArgs,
|
||||||
|
// args[{name,description,type,required,choices:[{value,label}],
|
||||||
|
// captureRemaining,preferAutocomplete}], argsParsing). Stored verbatim.
|
||||||
|
@Column({ type: 'json' })
|
||||||
|
commands!: unknown[];
|
||||||
|
|
||||||
|
@UpdateDateColumn()
|
||||||
|
updatedAt!: Date;
|
||||||
|
}
|
||||||
43
src/entities/stored-file.entity.ts
Normal file
43
src/entities/stored-file.entity.ts
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn } from 'typeorm';
|
||||||
|
|
||||||
|
// An uploaded or canvas-shared file held on the guild node. Retained for a
|
||||||
|
// configurable window (default 7 days) then purged by FilesService.
|
||||||
|
@Entity('stored_files')
|
||||||
|
export class StoredFile {
|
||||||
|
@PrimaryGeneratedColumn('uuid')
|
||||||
|
id!: string;
|
||||||
|
|
||||||
|
// public, URL-safe id used in /api/files/:fileId
|
||||||
|
@Index({ unique: true })
|
||||||
|
@Column({ name: 'file_id', type: 'varchar', length: 64 })
|
||||||
|
fileId!: string;
|
||||||
|
|
||||||
|
// owning channel (best-effort context; null = not channel-scoped)
|
||||||
|
@Index()
|
||||||
|
@Column({ name: 'channel_id', type: 'char', length: 36, nullable: true })
|
||||||
|
channelId!: string | null;
|
||||||
|
|
||||||
|
@Column({ name: 'uploader_user_id', type: 'varchar', length: 64 })
|
||||||
|
uploaderUserId!: string;
|
||||||
|
|
||||||
|
@Column({ name: 'original_name', type: 'varchar', length: 255 })
|
||||||
|
originalName!: string;
|
||||||
|
|
||||||
|
@Column({ name: 'mime_type', type: 'varchar', length: 150 })
|
||||||
|
mimeType!: string;
|
||||||
|
|
||||||
|
@Column({ name: 'size_bytes', type: 'bigint' })
|
||||||
|
sizeBytes!: number;
|
||||||
|
|
||||||
|
// path on disk relative to the storage root
|
||||||
|
@Column({ name: 'storage_path', type: 'varchar', length: 300 })
|
||||||
|
storagePath!: string;
|
||||||
|
|
||||||
|
@CreateDateColumn()
|
||||||
|
createdAt!: Date;
|
||||||
|
|
||||||
|
// hard-delete deadline; rows past this are purged with their blob
|
||||||
|
@Index()
|
||||||
|
@Column({ name: 'expires_at', type: 'datetime' })
|
||||||
|
expiresAt!: Date;
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Global, Module } from '@nestjs/common';
|
import { Global, Module } from '@nestjs/common';
|
||||||
import { EventsService } from './events.service';
|
import { EventsService } from './events.service.js';
|
||||||
|
|
||||||
@Global()
|
@Global()
|
||||||
@Module({
|
@Module({
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Injectable, Logger } from '@nestjs/common';
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
import { createHmac, randomUUID } from 'crypto';
|
import { createHmac, randomUUID } from 'crypto';
|
||||||
import { FabricEventEnvelope } from './event-envelope';
|
import { FabricEventEnvelope } from './event-envelope.js';
|
||||||
|
|
||||||
type RetryTask = {
|
type RetryTask = {
|
||||||
envelope: FabricEventEnvelope;
|
envelope: FabricEventEnvelope;
|
||||||
|
|||||||
84
src/files/files.controller.ts
Normal file
84
src/files/files.controller.ts
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
import {
|
||||||
|
BadRequestException,
|
||||||
|
Controller,
|
||||||
|
Get,
|
||||||
|
Param,
|
||||||
|
Post,
|
||||||
|
Query,
|
||||||
|
Req,
|
||||||
|
Res,
|
||||||
|
UnauthorizedException,
|
||||||
|
UploadedFile,
|
||||||
|
UseInterceptors,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { FileInterceptor } from '@nestjs/platform-express';
|
||||||
|
import type { Response } from 'express';
|
||||||
|
import { FilesService } from './files.service.js';
|
||||||
|
|
||||||
|
type AuthedRequest = { userId?: string };
|
||||||
|
type UploadedMulterFile = {
|
||||||
|
originalname: string;
|
||||||
|
mimetype: string;
|
||||||
|
size: number;
|
||||||
|
buffer: Buffer;
|
||||||
|
};
|
||||||
|
|
||||||
|
@Controller('files')
|
||||||
|
export class FilesController {
|
||||||
|
constructor(private readonly files: FilesService) {}
|
||||||
|
|
||||||
|
@Post()
|
||||||
|
@UseInterceptors(FileInterceptor('file'))
|
||||||
|
async upload(
|
||||||
|
@Req() req: AuthedRequest,
|
||||||
|
@UploadedFile() file: UploadedMulterFile | undefined,
|
||||||
|
@Query('channelId') channelId?: string,
|
||||||
|
) {
|
||||||
|
const userId = req.userId ?? '';
|
||||||
|
if (!userId) throw new UnauthorizedException('missing user');
|
||||||
|
if (!file || !file.buffer?.length) throw new BadRequestException('no file');
|
||||||
|
if (this.files.maxBytes > 0 && file.size > this.files.maxBytes) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
`file exceeds limit of ${this.files.maxBytes} bytes`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const row = await this.files.store({
|
||||||
|
channelId: channelId ? String(channelId) : null,
|
||||||
|
uploaderUserId: userId,
|
||||||
|
originalName: file.originalname || 'file',
|
||||||
|
mimeType: file.mimetype,
|
||||||
|
buffer: file.buffer,
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
fileId: row.fileId,
|
||||||
|
url: `/api/files/${row.fileId}`,
|
||||||
|
name: row.originalName,
|
||||||
|
mimeType: row.mimeType,
|
||||||
|
size: Number(row.sizeBytes),
|
||||||
|
expiresAt: row.expiresAt.toISOString(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get(':fileId')
|
||||||
|
async download(
|
||||||
|
@Param('fileId') fileId: string,
|
||||||
|
@Res() res: Response,
|
||||||
|
): Promise<void> {
|
||||||
|
const row = await this.files.find(fileId);
|
||||||
|
if (!row) {
|
||||||
|
res.status(404).json({ error: 'file_not_found' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const blob = await this.files.readBlob(row);
|
||||||
|
const inline = /^(image|audio|video)\//.test(row.mimeType) || row.mimeType === 'application/pdf';
|
||||||
|
const safeName = row.originalName.replace(/["\r\n]/g, '_');
|
||||||
|
res.setHeader('Content-Type', row.mimeType);
|
||||||
|
res.setHeader('Content-Length', String(blob.length));
|
||||||
|
res.setHeader(
|
||||||
|
'Content-Disposition',
|
||||||
|
`${inline ? 'inline' : 'attachment'}; filename="${safeName}"`,
|
||||||
|
);
|
||||||
|
res.setHeader('Cache-Control', 'private, max-age=3600');
|
||||||
|
res.end(blob);
|
||||||
|
}
|
||||||
|
}
|
||||||
13
src/files/files.module.ts
Normal file
13
src/files/files.module.ts
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { StoredFile } from '../entities/stored-file.entity.js';
|
||||||
|
import { FilesController } from './files.controller.js';
|
||||||
|
import { FilesService } from './files.service.js';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [TypeOrmModule.forFeature([StoredFile])],
|
||||||
|
controllers: [FilesController],
|
||||||
|
providers: [FilesService],
|
||||||
|
exports: [FilesService],
|
||||||
|
})
|
||||||
|
export class FilesModule {}
|
||||||
98
src/files/files.service.ts
Normal file
98
src/files/files.service.ts
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
import { randomBytes } from 'node:crypto';
|
||||||
|
import { promises as fs } from 'node:fs';
|
||||||
|
import { join, resolve } from 'node:path';
|
||||||
|
import { Injectable, Logger, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||||
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
|
import { LessThan, Repository } from 'typeorm';
|
||||||
|
import { StoredFile } from '../entities/stored-file.entity.js';
|
||||||
|
|
||||||
|
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||||
|
const CLEANUP_INTERVAL_MS = 60 * 60 * 1000; // hourly
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class FilesService implements OnModuleInit, OnModuleDestroy {
|
||||||
|
private readonly log = new Logger('FilesService');
|
||||||
|
private timer: NodeJS.Timeout | null = null;
|
||||||
|
|
||||||
|
// Storage root; the guild operator may relocate / resize this freely.
|
||||||
|
readonly dir = resolve(
|
||||||
|
process.env.FABRIC_BACKEND_GUILD_FILE_DIR ?? join(process.cwd(), '.data', 'files'),
|
||||||
|
);
|
||||||
|
// 0 / unset => no cap (default per product: 100MB, operator-configurable).
|
||||||
|
readonly maxBytes = Number(
|
||||||
|
process.env.FABRIC_BACKEND_GUILD_FILE_MAX_BYTES ?? 100 * 1024 * 1024,
|
||||||
|
);
|
||||||
|
readonly ttlDays = Number(process.env.FABRIC_BACKEND_GUILD_FILE_TTL_DAYS ?? 7);
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
@InjectRepository(StoredFile)
|
||||||
|
private readonly repo: Repository<StoredFile>,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async onModuleInit(): Promise<void> {
|
||||||
|
await fs.mkdir(this.dir, { recursive: true });
|
||||||
|
this.log.log(
|
||||||
|
`files dir=${this.dir} maxBytes=${this.maxBytes} ttlDays=${this.ttlDays}`,
|
||||||
|
);
|
||||||
|
// sweep on boot, then hourly
|
||||||
|
void this.cleanup();
|
||||||
|
this.timer = setInterval(() => void this.cleanup(), CLEANUP_INTERVAL_MS);
|
||||||
|
this.timer.unref?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
onModuleDestroy(): void {
|
||||||
|
if (this.timer) clearInterval(this.timer);
|
||||||
|
this.timer = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async store(input: {
|
||||||
|
channelId: string | null;
|
||||||
|
uploaderUserId: string;
|
||||||
|
originalName: string;
|
||||||
|
mimeType: string;
|
||||||
|
buffer: Buffer;
|
||||||
|
}): Promise<StoredFile> {
|
||||||
|
const fileId = randomBytes(18).toString('base64url');
|
||||||
|
const storagePath = fileId; // flat layout, opaque name
|
||||||
|
await fs.writeFile(join(this.dir, storagePath), input.buffer);
|
||||||
|
const row = this.repo.create({
|
||||||
|
fileId,
|
||||||
|
channelId: input.channelId,
|
||||||
|
uploaderUserId: input.uploaderUserId,
|
||||||
|
originalName: input.originalName.slice(0, 255),
|
||||||
|
mimeType: (input.mimeType || 'application/octet-stream').slice(0, 150),
|
||||||
|
sizeBytes: input.buffer.length,
|
||||||
|
storagePath,
|
||||||
|
expiresAt: new Date(Date.now() + this.ttlDays * DAY_MS),
|
||||||
|
});
|
||||||
|
return this.repo.save(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
async find(fileId: string): Promise<StoredFile | null> {
|
||||||
|
const row = await this.repo.findOne({ where: { fileId } });
|
||||||
|
if (!row) return null;
|
||||||
|
if (row.expiresAt.getTime() <= Date.now()) return null; // treat as gone
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
|
||||||
|
async readBlob(row: StoredFile): Promise<Buffer> {
|
||||||
|
return fs.readFile(join(this.dir, row.storagePath));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Purge every row past its retention deadline together with its blob.
|
||||||
|
async cleanup(): Promise<number> {
|
||||||
|
const expired = await this.repo.find({ where: { expiresAt: LessThan(new Date()) } });
|
||||||
|
let removed = 0;
|
||||||
|
for (const row of expired) {
|
||||||
|
try {
|
||||||
|
await fs.rm(join(this.dir, row.storagePath), { force: true });
|
||||||
|
} catch {
|
||||||
|
/* best effort: drop the row regardless */
|
||||||
|
}
|
||||||
|
await this.repo.delete({ id: row.id });
|
||||||
|
removed++;
|
||||||
|
}
|
||||||
|
if (removed) this.log.log(`retention sweep removed ${removed} expired file(s)`);
|
||||||
|
return removed;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Body, Controller, Get, Post } from '@nestjs/common';
|
import { Body, Controller, Get, Post } from '@nestjs/common';
|
||||||
import { GuildsService } from './guilds.service';
|
import { GuildsService } from './guilds.service.js';
|
||||||
|
|
||||||
@Controller('guilds')
|
@Controller('guilds')
|
||||||
export class GuildsController {
|
export class GuildsController {
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
import { GuildsController } from './guilds.controller';
|
import { GuildsController } from './guilds.controller.js';
|
||||||
import { Guild } from '../entities/guild.entity';
|
import { Guild } from '../entities/guild.entity.js';
|
||||||
import { GuildsService } from './guilds.service';
|
import { GuildsService } from './guilds.service.js';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [TypeOrmModule.forFeature([Guild])],
|
imports: [TypeOrmModule.forFeature([Guild])],
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
import { Repository } from 'typeorm';
|
import { Repository } from 'typeorm';
|
||||||
import { Guild } from '../entities/guild.entity';
|
import { Guild } from '../entities/guild.entity.js';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class GuildsService {
|
export class GuildsService {
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { Test } from '@nestjs/testing';
|
|||||||
import request from 'supertest';
|
import request from 'supertest';
|
||||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||||
import { DataSource } from 'typeorm';
|
import { DataSource } from 'typeorm';
|
||||||
import { Channel } from './entities/channel.entity';
|
import { Channel } from './entities/channel.entity.js';
|
||||||
|
|
||||||
process.env.DB_HOST = '127.0.0.1';
|
process.env.DB_HOST = '127.0.0.1';
|
||||||
process.env.DB_PORT = '3308';
|
process.env.DB_PORT = '3308';
|
||||||
@@ -18,7 +18,7 @@ describe('guild integration (mysql + api)', () => {
|
|||||||
let dataSource: DataSource;
|
let dataSource: DataSource;
|
||||||
|
|
||||||
beforeAll(async () => {
|
beforeAll(async () => {
|
||||||
const { AppModule } = await import('./app.module');
|
const { AppModule } = await import('./app.module.js');
|
||||||
const moduleRef = await Test.createTestingModule({
|
const moduleRef = await Test.createTestingModule({
|
||||||
imports: [AppModule],
|
imports: [AppModule],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|||||||
@@ -2,9 +2,9 @@ import 'reflect-metadata';
|
|||||||
import { ValidationPipe } from '@nestjs/common';
|
import { ValidationPipe } from '@nestjs/common';
|
||||||
import { NestFactory } from '@nestjs/core';
|
import { NestFactory } from '@nestjs/core';
|
||||||
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
||||||
import { AppModule } from './app.module';
|
import { AppModule } from './app.module.js';
|
||||||
import { createRequestContextMiddleware } from './common/request-context.middleware';
|
import { createRequestContextMiddleware } from './common/request-context.middleware.js';
|
||||||
import { MetricsService } from './common/metrics.service';
|
import { MetricsService } from './common/metrics.service.js';
|
||||||
|
|
||||||
function requireEnv(name: string): string {
|
function requireEnv(name: string): string {
|
||||||
const value = process.env[name];
|
const value = process.env[name];
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Controller, Get, Query } from '@nestjs/common';
|
import { Controller, Get, Query } from '@nestjs/common';
|
||||||
import { MembersService } from './members.service';
|
import { MembersService } from './members.service.js';
|
||||||
|
|
||||||
@Controller('members')
|
@Controller('members')
|
||||||
export class MembersController {
|
export class MembersController {
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
import { GuildMember } from '../entities/guild-member.entity';
|
import { GuildMember } from '../entities/guild-member.entity.js';
|
||||||
import { MembersController } from './members.controller';
|
import { MembersController } from './members.controller.js';
|
||||||
import { MembersService } from './members.service';
|
import { MembersService } from './members.service.js';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [TypeOrmModule.forFeature([GuildMember])],
|
imports: [TypeOrmModule.forFeature([GuildMember])],
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
import { Repository } from 'typeorm';
|
import { Repository } from 'typeorm';
|
||||||
import { GuildMember } from '../entities/guild-member.entity';
|
import { GuildMember } from '../entities/guild-member.entity.js';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class MembersService {
|
export class MembersService {
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import {
|
|||||||
ConflictException,
|
ConflictException,
|
||||||
Controller,
|
Controller,
|
||||||
Delete,
|
Delete,
|
||||||
|
ForbiddenException,
|
||||||
Get,
|
Get,
|
||||||
Headers,
|
Headers,
|
||||||
NotFoundException,
|
NotFoundException,
|
||||||
@@ -10,21 +11,24 @@ import {
|
|||||||
Patch,
|
Patch,
|
||||||
Post,
|
Post,
|
||||||
Query,
|
Query,
|
||||||
|
Req,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
import { DataSource, Repository } from 'typeorm';
|
import { DataSource, Repository } from 'typeorm';
|
||||||
import { CreateMessageDto } from './dto.create-message.dto';
|
import { CreateMessageDto } from './dto.create-message.dto.js';
|
||||||
import { Channel } from '../entities/channel.entity';
|
import { Channel } from '../entities/channel.entity.js';
|
||||||
import { Message } from '../entities/message.entity';
|
import { ChannelMember } from '../entities/channel-member.entity.js';
|
||||||
import { IdempotencyRecord } from '../entities/idempotency-record.entity';
|
import { Message } from '../entities/message.entity.js';
|
||||||
import { WakeMapping } from '../entities/wake-mapping.entity';
|
import { IdempotencyRecord } from '../entities/idempotency-record.entity.js';
|
||||||
import { parseSlashCommand } from '../channels/slash-commands';
|
import { WakeMapping } from '../entities/wake-mapping.entity.js';
|
||||||
import { parseMentions, extractNameMentions, replaceNameMentions } from '../channels/mentions';
|
import { AdminCacheService } from '../common/admin-cache.service.js';
|
||||||
import { resolveUserNames } from '../common/center-auth';
|
import { parseSlashCommand } from '../channels/slash-commands.js';
|
||||||
import { TurnService } from '../channels/turn.service';
|
import { parseMentions, extractNameMentions, replaceNameMentions } from '../channels/mentions.js';
|
||||||
import { EventsService } from '../events/events.service';
|
import { resolveUserNames } from '../common/center-auth.js';
|
||||||
import { clampLimit, computeNextExpectedSeq } from './pagination.util';
|
import { TurnService } from '../channels/turn.service.js';
|
||||||
import { RealtimeGateway } from '../realtime/realtime.gateway';
|
import { EventsService } from '../events/events.service.js';
|
||||||
|
import { clampLimit, computeNextExpectedSeq } from './pagination.util.js';
|
||||||
|
import { RealtimeGateway } from '../realtime/realtime.gateway.js';
|
||||||
|
|
||||||
const EDIT_WINDOW_MS = 15 * 60 * 1000;
|
const EDIT_WINDOW_MS = 15 * 60 * 1000;
|
||||||
const DEFAULT_PAGE_LIMIT = 50;
|
const DEFAULT_PAGE_LIMIT = 50;
|
||||||
@@ -36,6 +40,8 @@ export class MessagingController {
|
|||||||
private readonly dataSource: DataSource,
|
private readonly dataSource: DataSource,
|
||||||
@InjectRepository(Channel)
|
@InjectRepository(Channel)
|
||||||
private readonly channelRepo: Repository<Channel>,
|
private readonly channelRepo: Repository<Channel>,
|
||||||
|
@InjectRepository(ChannelMember)
|
||||||
|
private readonly memberRepo: Repository<ChannelMember>,
|
||||||
@InjectRepository(Message)
|
@InjectRepository(Message)
|
||||||
private readonly messageRepo: Repository<Message>,
|
private readonly messageRepo: Repository<Message>,
|
||||||
@InjectRepository(IdempotencyRecord)
|
@InjectRepository(IdempotencyRecord)
|
||||||
@@ -45,6 +51,7 @@ export class MessagingController {
|
|||||||
private readonly turn: TurnService,
|
private readonly turn: TurnService,
|
||||||
private readonly events: EventsService,
|
private readonly events: EventsService,
|
||||||
private readonly realtime: RealtimeGateway,
|
private readonly realtime: RealtimeGateway,
|
||||||
|
private readonly adminCache: AdminCacheService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
private async getIdempotentResponse(
|
private async getIdempotentResponse(
|
||||||
@@ -86,6 +93,19 @@ export class MessagingController {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Channel-participant gate (Guild C-1): public channels are readable/
|
||||||
|
// writable by any authenticated user; private channels require explicit
|
||||||
|
// channel_members membership. Returns the channel so callers can reuse it.
|
||||||
|
private async assertParticipant(channelId: string, userId: string): Promise<Channel> {
|
||||||
|
const channel = await this.channelRepo.findOne({ where: { id: channelId } });
|
||||||
|
if (!channel) throw new NotFoundException('channel not found');
|
||||||
|
if (channel.isPublic) return channel;
|
||||||
|
if (!userId) throw new ForbiddenException('not a channel member');
|
||||||
|
const member = await this.memberRepo.findOne({ where: { channelId, userId } });
|
||||||
|
if (!member) throw new ForbiddenException('not a channel member');
|
||||||
|
return channel;
|
||||||
|
}
|
||||||
|
|
||||||
// Persists one message (allocates a seq under a channel row lock) and
|
// Persists one message (allocates a seq under a channel row lock) and
|
||||||
// returns its view. Used for normal messages and for guild /ack messages.
|
// returns its view. Used for normal messages and for guild /ack messages.
|
||||||
private async persistMessage(
|
private async persistMessage(
|
||||||
@@ -136,20 +156,25 @@ export class MessagingController {
|
|||||||
async create(
|
async create(
|
||||||
@Param('id') channelId: string,
|
@Param('id') channelId: string,
|
||||||
@Body() body: CreateMessageDto,
|
@Body() body: CreateMessageDto,
|
||||||
|
@Req() req: { userId?: string },
|
||||||
@Headers('idempotency-key') idempotencyKey?: string,
|
@Headers('idempotency-key') idempotencyKey?: string,
|
||||||
) {
|
) {
|
||||||
const scope = `POST:/channels/${channelId}/messages`;
|
const scope = `POST:/channels/${channelId}/messages`;
|
||||||
const existed = await this.getIdempotentResponse(scope, idempotencyKey);
|
const existed = await this.getIdempotentResponse(scope, idempotencyKey);
|
||||||
if (existed) return existed;
|
if (existed) return existed;
|
||||||
|
|
||||||
const channel = await this.channelRepo.findOne({ where: { id: channelId } });
|
// Guild C-1: caller must be a participant of the channel, and the
|
||||||
if (!channel) throw new NotFoundException('channel not found');
|
// author is always the authenticated user — body.authorUserId is
|
||||||
|
// ignored so a caller can never post as someone else.
|
||||||
|
const userId = String(req.userId ?? '');
|
||||||
|
if (!userId) throw new ForbiddenException('missing user');
|
||||||
|
const channel = await this.assertParticipant(channelId, userId);
|
||||||
if (channel.closed) {
|
if (channel.closed) {
|
||||||
throw new ConflictException({ error: 'channel_closed', message: 'channel is closed' });
|
throw new ConflictException({ error: 'channel_closed', message: 'channel is closed' });
|
||||||
}
|
}
|
||||||
const xType = channel.xType ?? 'general';
|
const xType = channel.xType ?? 'general';
|
||||||
const isRotating = xType === 'discuss' || xType === 'work';
|
const isRotating = xType === 'discuss' || xType === 'work';
|
||||||
const authorUserId = String(body.authorUserId ?? 'anonymous');
|
const authorUserId = userId;
|
||||||
|
|
||||||
// ---- translate <@user.name:NAME> -> <@userId> (outside backticks) via
|
// ---- translate <@user.name:NAME> -> <@userId> (outside backticks) via
|
||||||
// Center before anything else persists/parses the content
|
// Center before anything else persists/parses the content
|
||||||
@@ -202,16 +227,19 @@ export class MessagingController {
|
|||||||
const decision = await this.turn.onNormalMessage(channelId, authorUserId, mentionIds);
|
const decision = await this.turn.onNormalMessage(channelId, authorUserId, mentionIds);
|
||||||
await this.realtime.emitMessageTargeted(channelId, responseBody, decision.wakeupUserId);
|
await this.realtime.emitMessageTargeted(channelId, responseBody, decision.wakeupUserId);
|
||||||
} else {
|
} else {
|
||||||
// general/report/triage/custom: wakeup from x_type + wake_mapping;
|
// general/report/triage/custom: 3-state delivery
|
||||||
// general also honors the message's at-list
|
// (wake / observer / skip) — see realtime.gateway.computeDelivery.
|
||||||
|
// Center-scoped admin (cached, 1d TTL) gets `observer` on triage.
|
||||||
const wakeRows = await this.wakeRepo.find({ where: { channelId } });
|
const wakeRows = await this.wakeRepo.find({ where: { channelId } });
|
||||||
const wakeUserIds = new Set(wakeRows.map((w) => w.userId));
|
const wakeUserIds = new Set(wakeRows.map((w) => w.userId));
|
||||||
const mentionUserIds = new Set(mentionIds.filter((id) => id !== authorUserId));
|
const mentionUserIds = new Set(mentionIds.filter((id) => id !== authorUserId));
|
||||||
|
const admin = await this.adminCache.get();
|
||||||
await this.realtime.emitMessageCreated(channelId, responseBody, {
|
await this.realtime.emitMessageCreated(channelId, responseBody, {
|
||||||
xType,
|
xType,
|
||||||
authorUserId,
|
authorUserId,
|
||||||
wakeUserIds,
|
wakeUserIds,
|
||||||
mentionUserIds,
|
mentionUserIds,
|
||||||
|
adminUserId: admin?.userId ?? null,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -223,14 +251,23 @@ export class MessagingController {
|
|||||||
@Param('id') channelId: string,
|
@Param('id') channelId: string,
|
||||||
@Param('messageId') messageId: string,
|
@Param('messageId') messageId: string,
|
||||||
@Body() body: { content?: string },
|
@Body() body: { content?: string },
|
||||||
|
@Req() req: { userId?: string },
|
||||||
@Headers('idempotency-key') idempotencyKey?: string,
|
@Headers('idempotency-key') idempotencyKey?: string,
|
||||||
) {
|
) {
|
||||||
const scope = `PATCH:/channels/${channelId}/messages/${messageId}`;
|
const scope = `PATCH:/channels/${channelId}/messages/${messageId}`;
|
||||||
const existed = await this.getIdempotentResponse(scope, idempotencyKey);
|
const existed = await this.getIdempotentResponse(scope, idempotencyKey);
|
||||||
if (existed) return existed;
|
if (existed) return existed;
|
||||||
|
|
||||||
|
// Guild C-1: participant + author-ownership.
|
||||||
|
const userId = String(req.userId ?? '');
|
||||||
|
if (!userId) throw new ForbiddenException('missing user');
|
||||||
|
await this.assertParticipant(channelId, userId);
|
||||||
|
|
||||||
const item = await this.messageRepo.findOne({ where: { channelId, messageId } });
|
const item = await this.messageRepo.findOne({ where: { channelId, messageId } });
|
||||||
if (!item) return { status: 'not_found' };
|
if (!item) return { status: 'not_found' };
|
||||||
|
if (item.authorUserId !== userId) {
|
||||||
|
throw new ForbiddenException('not the message author');
|
||||||
|
}
|
||||||
|
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
const createdAt = new Date(item.createdAt).getTime();
|
const createdAt = new Date(item.createdAt).getTime();
|
||||||
@@ -259,14 +296,23 @@ export class MessagingController {
|
|||||||
async remove(
|
async remove(
|
||||||
@Param('id') channelId: string,
|
@Param('id') channelId: string,
|
||||||
@Param('messageId') messageId: string,
|
@Param('messageId') messageId: string,
|
||||||
|
@Req() req: { userId?: string },
|
||||||
@Headers('idempotency-key') idempotencyKey?: string,
|
@Headers('idempotency-key') idempotencyKey?: string,
|
||||||
) {
|
) {
|
||||||
const scope = `DELETE:/channels/${channelId}/messages/${messageId}`;
|
const scope = `DELETE:/channels/${channelId}/messages/${messageId}`;
|
||||||
const existed = await this.getIdempotentResponse(scope, idempotencyKey);
|
const existed = await this.getIdempotentResponse(scope, idempotencyKey);
|
||||||
if (existed) return existed;
|
if (existed) return existed;
|
||||||
|
|
||||||
|
// Guild C-1: participant + author-ownership.
|
||||||
|
const userId = String(req.userId ?? '');
|
||||||
|
if (!userId) throw new ForbiddenException('missing user');
|
||||||
|
await this.assertParticipant(channelId, userId);
|
||||||
|
|
||||||
const item = await this.messageRepo.findOne({ where: { channelId, messageId } });
|
const item = await this.messageRepo.findOne({ where: { channelId, messageId } });
|
||||||
if (!item) return { status: 'not_found' };
|
if (!item) return { status: 'not_found' };
|
||||||
|
if (item.authorUserId !== userId) {
|
||||||
|
throw new ForbiddenException('not the message author');
|
||||||
|
}
|
||||||
|
|
||||||
item.isDeleted = true;
|
item.isDeleted = true;
|
||||||
item.deletedAt = new Date();
|
item.deletedAt = new Date();
|
||||||
@@ -304,10 +350,14 @@ export class MessagingController {
|
|||||||
@Get()
|
@Get()
|
||||||
async listBySeq(
|
async listBySeq(
|
||||||
@Param('id') channelId: string,
|
@Param('id') channelId: string,
|
||||||
|
@Req() req: { userId?: string },
|
||||||
@Query('seq_from') seqFrom?: string,
|
@Query('seq_from') seqFrom?: string,
|
||||||
@Query('seq_to') seqTo?: string,
|
@Query('seq_to') seqTo?: string,
|
||||||
@Query('limit') limit?: string,
|
@Query('limit') limit?: string,
|
||||||
) {
|
) {
|
||||||
|
// Guild C-1: only participants may read channel history.
|
||||||
|
const userId = String(req.userId ?? '');
|
||||||
|
if (!userId) throw new ForbiddenException('missing user');
|
||||||
const from = seqFrom ? Number(seqFrom) : 1;
|
const from = seqFrom ? Number(seqFrom) : 1;
|
||||||
const to = seqTo ? Number(seqTo) : Number.MAX_SAFE_INTEGER;
|
const to = seqTo ? Number(seqTo) : Number.MAX_SAFE_INTEGER;
|
||||||
const safeLimit = clampLimit(limit, DEFAULT_PAGE_LIMIT, MAX_PAGE_LIMIT);
|
const safeLimit = clampLimit(limit, DEFAULT_PAGE_LIMIT, MAX_PAGE_LIMIT);
|
||||||
@@ -327,10 +377,7 @@ export class MessagingController {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const channel = await this.channelRepo.findOne({ where: { id: channelId } });
|
const channel = await this.assertParticipant(channelId, userId);
|
||||||
if (!channel) {
|
|
||||||
throw new NotFoundException('channel not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
const qb = this.messageRepo
|
const qb = this.messageRepo
|
||||||
.createQueryBuilder('m')
|
.createQueryBuilder('m')
|
||||||
|
|||||||
@@ -1,13 +1,17 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
import { MessagingController } from './messaging.controller';
|
import { MessagingController } from './messaging.controller.js';
|
||||||
import { Channel } from '../entities/channel.entity';
|
import { Channel } from '../entities/channel.entity.js';
|
||||||
import { Message } from '../entities/message.entity';
|
import { ChannelMember } from '../entities/channel-member.entity.js';
|
||||||
import { IdempotencyRecord } from '../entities/idempotency-record.entity';
|
import { Message } from '../entities/message.entity.js';
|
||||||
import { WakeMapping } from '../entities/wake-mapping.entity';
|
import { IdempotencyRecord } from '../entities/idempotency-record.entity.js';
|
||||||
|
import { WakeMapping } from '../entities/wake-mapping.entity.js';
|
||||||
|
import { AdminCacheService } from '../common/admin-cache.service.js';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [TypeOrmModule.forFeature([Channel, Message, IdempotencyRecord, WakeMapping])],
|
imports: [TypeOrmModule.forFeature([Channel, ChannelMember, Message, IdempotencyRecord, WakeMapping])],
|
||||||
controllers: [MessagingController],
|
controllers: [MessagingController],
|
||||||
|
providers: [AdminCacheService],
|
||||||
|
exports: [AdminCacheService],
|
||||||
})
|
})
|
||||||
export class MessagingModule {}
|
export class MessagingModule {}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
import { clampLimit, computeNextExpectedSeq } from './pagination.util';
|
import { clampLimit, computeNextExpectedSeq } from './pagination.util.js';
|
||||||
|
|
||||||
describe('pagination utils', () => {
|
describe('pagination utils', () => {
|
||||||
it('clamps limit safely', () => {
|
it('clamps limit safely', () => {
|
||||||
|
|||||||
@@ -9,19 +9,74 @@ import {
|
|||||||
} from '@nestjs/websockets';
|
} from '@nestjs/websockets';
|
||||||
import { Logger } from '@nestjs/common';
|
import { Logger } from '@nestjs/common';
|
||||||
import { Server, Socket } from 'socket.io';
|
import { Server, Socket } from 'socket.io';
|
||||||
import { introspectGuildToken } from '../common/center-auth';
|
import { introspectGuildToken } from '../common/center-auth.js';
|
||||||
|
|
||||||
type XType = 'general' | 'work' | 'report' | 'discuss' | 'triage' | 'custom';
|
type XType = 'general' | 'work' | 'report' | 'discuss' | 'triage' | 'custom' | 'dm';
|
||||||
|
|
||||||
// Wakeup for non-rotating channels only (general/report/triage/custom).
|
/**
|
||||||
// discuss/work go through TurnService + emitMessageTargeted, never here.
|
* Per-recipient delivery decision for a non-rotating channel message.
|
||||||
// Precedence:
|
*
|
||||||
// 1. the author never gets woken by their own message
|
* • `wake` — push the event AND wake the recipient (model turn fires)
|
||||||
// 2. triage/custom: only wake users in the channel's wake_mapping
|
* • `observer` — push the event with wakeup=false (silent; UI displays
|
||||||
// (mentions change nothing here)
|
* but the openclaw plugin records-only without dispatch). Currently
|
||||||
// 3. general: if the message has an at-list, wake only the at'd users;
|
* used for the Center admin observing triage traffic
|
||||||
// otherwise wake everyone
|
* • `skip` — don't even emit the event to this recipient
|
||||||
// 4. report (and anything else): wake nobody
|
*
|
||||||
|
* Wakeup-only channels (general/report/dm/custom) never return
|
||||||
|
* 'observer'; the legacy behaviour is preserved end-to-end.
|
||||||
|
*
|
||||||
|
* Precedence for triage (the only place 'skip' / 'observer' fire):
|
||||||
|
* 1. author never gets back their own message
|
||||||
|
* 2. wake_mapping (on-duty) → wake
|
||||||
|
* 3. mention → wake (NEW: was 'skip' before — see Fabric PR 'triage
|
||||||
|
* mention exception')
|
||||||
|
* 4. admin (Center-scoped, at most one) → observer
|
||||||
|
* 5. everyone else → skip (was 'deliver, wakeup=false' before)
|
||||||
|
*/
|
||||||
|
export type DeliveryDecision = 'wake' | 'observer' | 'skip';
|
||||||
|
|
||||||
|
export interface ComputeDeliveryArgs {
|
||||||
|
xType: XType;
|
||||||
|
recipientUserId: string;
|
||||||
|
authorUserId: string;
|
||||||
|
wakeUserIds: Set<string>;
|
||||||
|
mentionUserIds?: Set<string>;
|
||||||
|
/** Single Center-scoped admin userId, or null. */
|
||||||
|
adminUserId?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function computeDelivery(args: ComputeDeliveryArgs): DeliveryDecision {
|
||||||
|
const { xType, recipientUserId, authorUserId, wakeUserIds, mentionUserIds, adminUserId } = args;
|
||||||
|
if (recipientUserId === authorUserId) return 'skip';
|
||||||
|
|
||||||
|
switch (xType) {
|
||||||
|
case 'triage':
|
||||||
|
if (wakeUserIds.has(recipientUserId)) return 'wake';
|
||||||
|
if (mentionUserIds?.has(recipientUserId)) return 'wake';
|
||||||
|
if (adminUserId && recipientUserId === adminUserId) return 'observer';
|
||||||
|
return 'skip';
|
||||||
|
case 'general':
|
||||||
|
if (mentionUserIds && mentionUserIds.size > 0) {
|
||||||
|
return mentionUserIds.has(recipientUserId) ? 'wake' : 'observer';
|
||||||
|
}
|
||||||
|
return 'wake';
|
||||||
|
case 'custom':
|
||||||
|
// wake_mapping decides who wakes; everyone else still sees the
|
||||||
|
// message (observer) — preserves the legacy "deliver to all, wake
|
||||||
|
// some" contract for custom channels.
|
||||||
|
return wakeUserIds.has(recipientUserId) ? 'wake' : 'observer';
|
||||||
|
case 'dm':
|
||||||
|
return 'wake';
|
||||||
|
default:
|
||||||
|
// report (and anything else): deliver as observer, no wake
|
||||||
|
return 'observer';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @deprecated Use computeDelivery (returns 3-state). Kept for any
|
||||||
|
* external callers; treats 'observer' and 'skip' both as `false`.
|
||||||
|
*/
|
||||||
export function computeWakeup(args: {
|
export function computeWakeup(args: {
|
||||||
xType: XType;
|
xType: XType;
|
||||||
recipientUserId: string;
|
recipientUserId: string;
|
||||||
@@ -29,20 +84,7 @@ export function computeWakeup(args: {
|
|||||||
wakeUserIds: Set<string>;
|
wakeUserIds: Set<string>;
|
||||||
mentionUserIds?: Set<string>;
|
mentionUserIds?: Set<string>;
|
||||||
}): boolean {
|
}): boolean {
|
||||||
const { xType, recipientUserId, authorUserId, wakeUserIds, mentionUserIds } = args;
|
return computeDelivery(args) === 'wake';
|
||||||
if (recipientUserId === authorUserId) return false;
|
|
||||||
switch (xType) {
|
|
||||||
case 'general':
|
|
||||||
if (mentionUserIds && mentionUserIds.size > 0) {
|
|
||||||
return mentionUserIds.has(recipientUserId);
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
case 'triage':
|
|
||||||
case 'custom':
|
|
||||||
return wakeUserIds.has(recipientUserId);
|
|
||||||
default:
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@WebSocketGateway({
|
@WebSocketGateway({
|
||||||
@@ -93,6 +135,10 @@ export class RealtimeGateway implements OnGatewayConnection, OnGatewayDisconnect
|
|||||||
const userId = result.user.id || this.userIdFromClient(client);
|
const userId = result.user.id || this.userIdFromClient(client);
|
||||||
client.data.userId = userId;
|
client.data.userId = userId;
|
||||||
this.onlineUsers.add(userId);
|
this.onlineUsers.add(userId);
|
||||||
|
// Per-user room: lets server code emit user-scoped events (e.g.
|
||||||
|
// channel.joined when membership changes) without bookkeeping a
|
||||||
|
// userId→sockets map. All of this user's sockets receive the event.
|
||||||
|
client.join(`user:${userId}`);
|
||||||
this.server.emit('presence.online', {
|
this.server.emit('presence.online', {
|
||||||
userId,
|
userId,
|
||||||
onlineCount: this.onlineUsers.size,
|
onlineCount: this.onlineUsers.size,
|
||||||
@@ -168,7 +214,18 @@ export class RealtimeGateway implements OnGatewayConnection, OnGatewayDisconnect
|
|||||||
this.server.to(`channel:${channelId}`).emit(event, data);
|
this.server.to(`channel:${channelId}`).emit(event, data);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Emits message.created per-recipient so each carries its own `wakeup` flag.
|
// Emit a user-scoped event to all sockets currently connected for `userId`
|
||||||
|
// (via the `user:<userId>` room joined in handleConnection). No-op for
|
||||||
|
// offline users — the next connect's initial channel-list fetch covers it.
|
||||||
|
emitToUser(userId: string, event: string, data: Record<string, unknown>): void {
|
||||||
|
if (!userId) return;
|
||||||
|
this.server.to(`user:${userId}`).emit(event, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Emits message.created per-recipient using the 3-state delivery
|
||||||
|
// decision (wake / observer / skip). Skipped recipients receive
|
||||||
|
// nothing — used by triage channels to keep non-on-duty / non-mention
|
||||||
|
// / non-admin users completely out of the loop.
|
||||||
async emitMessageCreated(
|
async emitMessageCreated(
|
||||||
channelId: string,
|
channelId: string,
|
||||||
data: Record<string, unknown>,
|
data: Record<string, unknown>,
|
||||||
@@ -177,19 +234,28 @@ export class RealtimeGateway implements OnGatewayConnection, OnGatewayDisconnect
|
|||||||
authorUserId: string;
|
authorUserId: string;
|
||||||
wakeUserIds: Set<string>;
|
wakeUserIds: Set<string>;
|
||||||
mentionUserIds?: Set<string>;
|
mentionUserIds?: Set<string>;
|
||||||
|
/** Single Center-scoped admin userId (or null). */
|
||||||
|
adminUserId?: string | null;
|
||||||
},
|
},
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const sockets = await this.server.in(`channel:${channelId}`).fetchSockets();
|
const sockets = await this.server.in(`channel:${channelId}`).fetchSockets();
|
||||||
for (const s of sockets) {
|
for (const s of sockets) {
|
||||||
const recipientUserId = typeof s.data.userId === 'string' ? s.data.userId : `anon:${s.id}`;
|
const recipientUserId = typeof s.data.userId === 'string' ? s.data.userId : `anon:${s.id}`;
|
||||||
const wakeup = computeWakeup({
|
const decision = computeDelivery({
|
||||||
xType: ctx.xType,
|
xType: ctx.xType,
|
||||||
recipientUserId,
|
recipientUserId,
|
||||||
authorUserId: ctx.authorUserId,
|
authorUserId: ctx.authorUserId,
|
||||||
wakeUserIds: ctx.wakeUserIds,
|
wakeUserIds: ctx.wakeUserIds,
|
||||||
mentionUserIds: ctx.mentionUserIds,
|
mentionUserIds: ctx.mentionUserIds,
|
||||||
|
adminUserId: ctx.adminUserId,
|
||||||
|
});
|
||||||
|
if (decision === 'skip') continue;
|
||||||
|
s.emit('message.created', {
|
||||||
|
...data,
|
||||||
|
channelId,
|
||||||
|
wakeup: decision === 'wake',
|
||||||
|
xType: ctx.xType,
|
||||||
});
|
});
|
||||||
s.emit('message.created', { ...data, wakeup });
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -204,7 +270,7 @@ export class RealtimeGateway implements OnGatewayConnection, OnGatewayDisconnect
|
|||||||
for (const s of sockets) {
|
for (const s of sockets) {
|
||||||
const recipientUserId = typeof s.data.userId === 'string' ? s.data.userId : `anon:${s.id}`;
|
const recipientUserId = typeof s.data.userId === 'string' ? s.data.userId : `anon:${s.id}`;
|
||||||
const wakeup = wakeupUserId !== null && recipientUserId === wakeupUserId;
|
const wakeup = wakeupUserId !== null && recipientUserId === wakeupUserId;
|
||||||
s.emit('message.created', { ...data, wakeup });
|
s.emit('message.created', { ...data, channelId, wakeup });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Global, Module } from '@nestjs/common';
|
import { Global, Module } from '@nestjs/common';
|
||||||
import { RealtimeGateway } from './realtime.gateway';
|
import { RealtimeGateway } from './realtime.gateway.js';
|
||||||
|
|
||||||
@Global()
|
@Global()
|
||||||
@Module({
|
@Module({
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
{
|
{
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"module": "commonjs",
|
"module": "NodeNext",
|
||||||
"target": "es2020",
|
"moduleResolution": "NodeNext",
|
||||||
|
"target": "es2022",
|
||||||
"strict": true,
|
"strict": true,
|
||||||
"esModuleInterop": true,
|
"esModuleInterop": true,
|
||||||
"experimentalDecorators": true,
|
"experimentalDecorators": true,
|
||||||
|
|||||||
Reference in New Issue
Block a user