Mark comments (and, via existing page provenance, pages) created under an is_agent service account as authored by AI, derived from the SIGNED server identity rather than any client field, and render the existing AI badge in the comments sidebar. Backend (B1): - Add additive users.is_agent boolean (default false) migration; reflect in the Users Kysely type, the user repo baseFields, and (via Selectable) the User entity. - jwt.strategy: derive req.raw.actor from user.isAgent (an is_agent account stamps every write 'agent'); external MCP has no internal ai_chats row so aiChatId stays null. Non-spoofable: a plain user cannot obtain created_source='agent'. - Loosen the provenance aiChatId type to string|null across token.service and the JwtPayload/JwtCollabPayload claims (type-level only; the internal AI-chat path still passes a real aiChatId). Frontend (B2): - Extend IComment with createdSource/aiChatId/resolvedSource (backend already returns them via selectAll). - Extract the local AiAgentBadge from history-item into a shared components/ui/ai-agent-badge.tsx (clickable deep-link when aiChatId present, plain label when null/absent); reuse it in history-item and render it in comment-list-item next to the author name when createdSource==='agent'. Tests: comment.service agent/null-aiChatId provenance, jwt.strategy provenance derivation + anti-spoof, AiAgentBadge clickable/non-clickable branches, and comment-list-item badge render/no-render. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
234 lines
6.6 KiB
TypeScript
234 lines
6.6 KiB
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import { InjectKysely } from 'nestjs-kysely';
|
|
import { KyselyDB, KyselyTransaction } from '@docmost/db/types/kysely.types';
|
|
import { DB, Users } from '@docmost/db/types/db';
|
|
import { hashPassword } from '../../../common/helpers';
|
|
import { dbOrTx } from '@docmost/db/utils';
|
|
import {
|
|
InsertableUser,
|
|
UpdatableUser,
|
|
User,
|
|
} from '@docmost/db/types/entity.types';
|
|
import { PaginationOptions } from '../../pagination/pagination-options';
|
|
import { executeWithCursorPagination } from '@docmost/db/pagination/cursor-pagination';
|
|
import { ExpressionBuilder, sql } from 'kysely';
|
|
import { jsonObjectFrom } from 'kysely/helpers/postgres';
|
|
import { NotificationSettingKey } from '../../../core/notification/notification.constants';
|
|
|
|
@Injectable()
|
|
export class UserRepo {
|
|
constructor(@InjectKysely() private readonly db: KyselyDB) {}
|
|
|
|
public baseFields: Array<keyof Users> = [
|
|
'id',
|
|
'email',
|
|
'name',
|
|
'emailVerifiedAt',
|
|
'avatarUrl',
|
|
'role',
|
|
'workspaceId',
|
|
'locale',
|
|
'timezone',
|
|
'settings',
|
|
'lastLoginAt',
|
|
'deactivatedAt',
|
|
'createdAt',
|
|
'updatedAt',
|
|
'deletedAt',
|
|
'hasGeneratedPassword',
|
|
// AI agent identity flag — needed by the JWT strategy to derive a
|
|
// non-spoofable 'agent' provenance from the signed server-side identity.
|
|
'isAgent',
|
|
];
|
|
|
|
async findById(
|
|
userId: string,
|
|
workspaceId: string,
|
|
opts?: {
|
|
includePassword?: boolean;
|
|
includeUserMfa?: boolean;
|
|
includeScimExternalId?: boolean;
|
|
trx?: KyselyTransaction;
|
|
},
|
|
): Promise<User> {
|
|
const db = dbOrTx(this.db, opts?.trx);
|
|
return db
|
|
.selectFrom('users')
|
|
.select(this.baseFields)
|
|
.$if(opts?.includePassword, (qb) => qb.select('password'))
|
|
.$if(opts?.includeUserMfa, (qb) => qb.select(this.withUserMfa))
|
|
.$if(opts?.includeScimExternalId, (qb) => qb.select('scimExternalId'))
|
|
.where('id', '=', userId)
|
|
.where('workspaceId', '=', workspaceId)
|
|
.executeTakeFirst();
|
|
}
|
|
|
|
async findByEmail(
|
|
email: string,
|
|
workspaceId: string,
|
|
opts?: {
|
|
includePassword?: boolean;
|
|
includeUserMfa?: boolean;
|
|
includeScimExternalId?: boolean;
|
|
trx?: KyselyTransaction;
|
|
},
|
|
): Promise<User> {
|
|
const db = dbOrTx(this.db, opts?.trx);
|
|
return db
|
|
.selectFrom('users')
|
|
.select(this.baseFields)
|
|
.$if(opts?.includePassword, (qb) => qb.select('password'))
|
|
.$if(opts?.includeUserMfa, (qb) => qb.select(this.withUserMfa))
|
|
.$if(opts?.includeScimExternalId, (qb) => qb.select('scimExternalId'))
|
|
.where(sql`LOWER(email)`, '=', sql`LOWER(${email})`)
|
|
.where('workspaceId', '=', workspaceId)
|
|
.executeTakeFirst();
|
|
}
|
|
|
|
async updateUser(
|
|
updatableUser: UpdatableUser,
|
|
userId: string,
|
|
workspaceId: string,
|
|
trx?: KyselyTransaction,
|
|
) {
|
|
const db = dbOrTx(this.db, trx);
|
|
|
|
return await db
|
|
.updateTable('users')
|
|
.set({ ...updatableUser, updatedAt: new Date() })
|
|
.where('id', '=', userId)
|
|
.where('workspaceId', '=', workspaceId)
|
|
.execute();
|
|
}
|
|
|
|
async updateLastLogin(userId: string, workspaceId: string) {
|
|
return await this.db
|
|
.updateTable('users')
|
|
.set({
|
|
lastLoginAt: new Date(),
|
|
})
|
|
.where('id', '=', userId)
|
|
.where('workspaceId', '=', workspaceId)
|
|
.execute();
|
|
}
|
|
|
|
async insertUser(
|
|
insertableUser: InsertableUser,
|
|
trx?: KyselyTransaction,
|
|
): Promise<User> {
|
|
const user: InsertableUser = {
|
|
name:
|
|
insertableUser.name || insertableUser.email.split('@')[0].toLowerCase(),
|
|
email: insertableUser.email.toLowerCase(),
|
|
password: await hashPassword(insertableUser.password),
|
|
locale: 'en-US',
|
|
role: insertableUser?.role,
|
|
lastLoginAt: new Date(),
|
|
};
|
|
|
|
const db = dbOrTx(this.db, trx);
|
|
return db
|
|
.insertInto('users')
|
|
.values({ ...insertableUser, ...user })
|
|
.returning(this.baseFields)
|
|
.executeTakeFirst();
|
|
}
|
|
|
|
async roleCountByWorkspaceId(
|
|
role: string,
|
|
workspaceId: string,
|
|
): Promise<number> {
|
|
const { count } = await this.db
|
|
.selectFrom('users')
|
|
.select((eb) => eb.fn.count('role').as('count'))
|
|
.where('role', '=', role)
|
|
.where('workspaceId', '=', workspaceId)
|
|
.executeTakeFirst();
|
|
|
|
return count as number;
|
|
}
|
|
|
|
async getUsersPaginated(workspaceId: string, pagination: PaginationOptions) {
|
|
let query = this.db
|
|
.selectFrom('users')
|
|
.select(this.baseFields)
|
|
.where('workspaceId', '=', workspaceId)
|
|
.where('deletedAt', 'is', null);
|
|
|
|
if (pagination.query) {
|
|
query = query.where((eb) =>
|
|
eb(
|
|
sql`f_unaccent(users.name)`,
|
|
'ilike',
|
|
sql`f_unaccent(${'%' + pagination.query + '%'})`,
|
|
).or(
|
|
sql`users.email`,
|
|
'ilike',
|
|
sql`f_unaccent(${'%' + pagination.query + '%'})`,
|
|
),
|
|
);
|
|
}
|
|
|
|
return executeWithCursorPagination(query, {
|
|
perPage: pagination.limit,
|
|
cursor: pagination.cursor,
|
|
beforeCursor: pagination.beforeCursor,
|
|
fields: [
|
|
{ expression: 'name', direction: 'asc' },
|
|
{ expression: 'id', direction: 'asc' },
|
|
],
|
|
parseCursor: (cursor) => ({ name: cursor.name, id: cursor.id }),
|
|
});
|
|
}
|
|
|
|
async updatePreference(
|
|
userId: string,
|
|
prefKey: string,
|
|
prefValue: string | boolean,
|
|
) {
|
|
return await this.db
|
|
.updateTable('users')
|
|
.set({
|
|
settings: sql`COALESCE(settings, '{}'::jsonb)
|
|
|| jsonb_build_object('preferences', COALESCE(settings->'preferences', '{}'::jsonb)
|
|
|| jsonb_build_object('${sql.raw(prefKey)}', ${sql.lit(prefValue)}))`,
|
|
updatedAt: new Date(),
|
|
})
|
|
.where('id', '=', userId)
|
|
.returning(this.baseFields)
|
|
.executeTakeFirst();
|
|
}
|
|
|
|
async updateNotificationSetting(
|
|
userId: string,
|
|
settingKey: NotificationSettingKey,
|
|
settingValue: boolean,
|
|
) {
|
|
return await this.db
|
|
.updateTable('users')
|
|
.set({
|
|
settings: sql`COALESCE(settings, '{}'::jsonb)
|
|
|| jsonb_build_object('notifications', COALESCE(settings->'notifications', '{}'::jsonb)
|
|
|| jsonb_build_object(${sql.lit(settingKey)}, ${sql.lit(settingValue)}))`,
|
|
updatedAt: new Date(),
|
|
})
|
|
.where('id', '=', userId)
|
|
.returning(this.baseFields)
|
|
.executeTakeFirst();
|
|
}
|
|
|
|
withUserMfa(eb: ExpressionBuilder<DB, 'users'>) {
|
|
return jsonObjectFrom(
|
|
eb
|
|
.selectFrom('userMfa')
|
|
.select([
|
|
'userMfa.id',
|
|
'userMfa.method',
|
|
'userMfa.isEnabled',
|
|
'userMfa.createdAt',
|
|
])
|
|
.whereRef('userMfa.userId', '=', 'users.id'),
|
|
).as('mfa');
|
|
}
|
|
}
|