feat: complete Skill management CRUD

This commit is contained in:
Dustin Healy 2026-10-07 13:33:22 -07:00
parent 5ee091e99d
commit 9135a35883
8 changed files with 833 additions and 58 deletions

View file

@ -108,6 +108,7 @@ describe('Agents OpenAPI actual HTTP contract', () => {
await mongoose.connect(mongoServer.getUri());
createModels(mongoose);
db = require('~/models');
await db.seedDefaultRoles();
user = await mongoose.models.User.create({
email: 'openapi-contract@example.test',
@ -240,8 +241,9 @@ describe('Agents OpenAPI actual HTTP contract', () => {
});
const { getSkillManagementFileSaver } = require('~/server/services/Endpoints/agents/skillDeps');
const { getSkillsHandlers } = require('~/server/services/Skills/handlers');
const skillHandlers = createSkillManagementHandlers({
handlers: {},
handlers: getSkillsHandlers(),
getSkillById: db.getSkillById,
getRoleByName,
checkPermission: async () => true,
@ -263,7 +265,10 @@ describe('Agents OpenAPI actual HTTP contract', () => {
restoreTenantContextFromReq,
fileHandlers.upload,
);
app.post('/api/agents/v1/skills', skillHandlers.create);
app.put('/api/agents/v1/skills/:id/files/*relativePath', skillHandlers.updateFile);
app.delete('/api/agents/v1/skills/:id/files/*relativePath', skillHandlers.deleteFile);
app.delete('/api/agents/v1/skills/:id', skillHandlers.delete);
app.get('/api/agents/v1/agents/:id', (_req, _res, next) =>
next(new Error('contract fixture escaped error')),
);
@ -353,6 +358,47 @@ describe('Agents OpenAPI actual HTTP contract', () => {
expect(fs.readFileSync(diskPath, 'utf8')).toBe(content);
});
it('documents and validates Skill creation and complete deletion cleanup', async () => {
const created = await request(app)
.post('/api/agents/v1/skills')
.set('Authorization', `Bearer ${token}`)
.send({
name: 'managed-contract-skill',
description: 'Created through the versioned management contract.',
body: '# Managed contract Skill',
});
expect(created.status).toBe(201);
expectResponseToMatchSpec(spec, 'createSkill', created);
expect(await mongoose.models.Skill.findById(created.body.id).lean()).toMatchObject({
tenantId,
});
const file = await request(app)
.put(`/api/agents/v1/skills/${created.body.id}/files/references/delete-me.md`)
.set('Authorization', `Bearer ${token}`)
.send({ content: 'temporary' });
expect(file.status).toBe(200);
const deletedFile = await request(app)
.delete(`/api/agents/v1/skills/${created.body.id}/files/references/delete-me.md`)
.set('Authorization', `Bearer ${token}`);
expect(deletedFile.status).toBe(200);
expectResponseToMatchSpec(spec, 'deleteSkillFile', deletedFile);
expect(
await mongoose.models.SkillFile.findOne({
skillId: created.body.id,
relativePath: 'references/delete-me.md',
}).lean(),
).toBeNull();
const deleted = await request(app)
.delete(`/api/agents/v1/skills/${created.body.id}`)
.set('Authorization', `Bearer ${token}`);
expect(deleted.status).toBe(200);
expectResponseToMatchSpec(spec, 'deleteSkill', deleted);
expect(await mongoose.models.Skill.findById(created.body.id).lean()).toBeNull();
});
it('validates parser and normalized management errors against their documented JSON forms', async () => {
const malformed = await request(app)
.put(`/api/agents/v1/skills/${skillId}/files/contract.md`)

View file

@ -14,11 +14,14 @@ jest.mock('@librechat/api', () => ({
mockDeps = deps;
return {
list: mockList,
create: mockWrite,
get: mockList,
update: mockWrite,
delete: mockWrite,
listFiles: mockList,
getFile: mockList,
updateFile: mockWrite,
deleteFile: mockWrite,
};
},
mapAgentManagementError: () => ({ status: 404, body: { error: { code: 'not_found' } } }),

View file

@ -27,11 +27,14 @@ const handlers = createSkillManagementHandlers({
});
router.use(requireAgentManagementAuth, checkBan, configMiddleware);
router.get('/', handlers.list);
router.post('/', handlers.create);
router.get('/:id', handlers.get);
router.patch('/:id', handlers.update);
router.delete('/:id', handlers.delete);
router.get('/:id/files', handlers.listFiles);
router.get('/:id/files/*relativePath', handlers.getFile);
router.put('/:id/files/*relativePath', handlers.updateFile);
router.delete('/:id/files/*relativePath', handlers.deleteFile);
router.use((_req, res) => {
const { status, body } = mapAgentManagementError('not_found');
body.error.message = 'Skill or file not found';

View file

@ -7,17 +7,34 @@ execution router and does not accept browser sessions or execution API keys as f
| Method | Path | Operation |
| ------ | ----------------------------------------------- | --------------------------------------------- |
| GET | `/api/agents/v1/skills` | List accessible Skills (`limit` and `cursor`) |
| POST | `/api/agents/v1/skills` | Create an inline Skill |
| GET | `/api/agents/v1/skills/:id` | Read Skill metadata, body, and frontmatter |
| PATCH | `/api/agents/v1/skills/:id` | Update an inline Skill |
| DELETE | `/api/agents/v1/skills/:id` | Delete an inline Skill |
| GET | `/api/agents/v1/skills/:id/files` | List file metadata |
| GET | `/api/agents/v1/skills/:id/files/*relativePath` | Read a file as JSON |
| PUT | `/api/agents/v1/skills/:id/files/*relativePath` | Create or replace a text file |
| DELETE | `/api/agents/v1/skills/:id/files/*relativePath` | Delete a file |
Skill results expose `id`, configuration fields, `version`, `fileCount`, and ISO timestamps.
Ownership, tenant, source metadata, and storage locations are excluded. Skill lists use the Agent
management envelope: `object`, `data`, `first_id`, `last_id`, `has_more`, and `after`.
Pass returned Skill IDs in the Agent management `skills` field to assign them to an Agent.
Create an inline Skill with its required identity and instruction fields:
```json
{
"name": "query-review",
"description": "Review a query and recommend improvements.",
"body": "Review the supplied query for correctness and efficiency."
}
```
Creation also accepts the editable optional fields described below. The authenticated principal is
recorded as the owner; callers cannot set ownership, tenant, source, or permissions. Skill deletion
uses the existing cleanup path for Agent allowlists, Skill files, permissions, and stored blobs.
Updates require the version returned by the latest read:
```json
@ -36,8 +53,8 @@ permissions. Inaccessible and cross-tenant IDs return the same 404 envelope.
Text-file writes accept `{ "content": "replacement text" }`, capped at 1 MiB of UTF-8 data.
Use a relative path such as `references/guide.md`. Absolute paths, traversal, and NUL bytes are
rejected. Update `SKILL.md` through the Skill's `body` field with `expectedVersion`, not the file
endpoint. File writes use replacement semantics without a version precondition; serialize writers
rejected. Delete the same path to remove the file. Update `SKILL.md` through the Skill's `body`
field with `expectedVersion`, not the file endpoint. File writes use replacement semantics without a version precondition; serialize writers
to the same path. After a file write, read the Skill again before a versioned metadata/body update: file writes also
increment the parent version. Storage selection stays server-controlled. File JSON reads omit content for
binary or oversized files; raw download mode is not supported on this surface.

View file

@ -1249,6 +1249,140 @@
}
}
}
},
"post": {
"operationId": "createSkill",
"summary": "Create a skill",
"tags": [
"Skills"
],
"security": [
{
"oidcBearer": []
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/SkillCreateRequest"
}
}
}
},
"responses": {
"201": {
"description": "The created skill",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Skill"
}
}
}
},
"400": {
"description": "Invalid request, or a malformed JSON body",
"content": {
"application/json": {
"schema": {
"anyOf": [
{
"$ref": "#/components/schemas/Error"
},
{
"$ref": "#/components/schemas/JsonParseError"
}
]
}
}
}
},
"401": {
"description": "Authentication failed",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorMessage"
}
}
}
},
"403": {
"description": "Permission denied, the caller is banned, or the request fails tenant isolation",
"content": {
"application/json": {
"schema": {
"anyOf": [
{
"$ref": "#/components/schemas/Error"
},
{
"$ref": "#/components/schemas/MessageError"
},
{
"$ref": "#/components/schemas/ErrorMessage"
}
]
}
}
}
},
"404": {
"description": "Not found",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"409": {
"description": "The Skill name already exists, or the bound account is being deleted",
"content": {
"application/json": {
"schema": {
"anyOf": [
{
"$ref": "#/components/schemas/Error"
},
{
"$ref": "#/components/schemas/AccountDeletionConflict"
}
]
}
}
}
},
"500": {
"description": "Internal server error. Errors normalized by the route use JSON; the final application error controller sends a text body with the text/html media type.",
"content": {
"application/json": {
"schema": {
"anyOf": [
{
"$ref": "#/components/schemas/Error"
},
{
"$ref": "#/components/schemas/ErrorMessage"
}
]
}
},
"text/html": {
"schema": {
"type": "string",
"enum": [
"An unknown error occurred.",
"Processing error in ErrorController."
]
}
}
}
}
}
}
},
"/skills/{id}": {
@ -1524,6 +1658,134 @@
}
}
}
},
"delete": {
"operationId": "deleteSkill",
"summary": "Delete a skill",
"tags": [
"Skills"
],
"security": [
{
"oidcBearer": []
}
],
"parameters": [
{
"in": "path",
"name": "id",
"description": "The skill id",
"schema": {
"type": "string"
},
"required": true
}
],
"responses": {
"200": {
"description": "The skill was deleted",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/SkillDeleted"
}
}
}
},
"400": {
"description": "Invalid request, or a malformed JSON body",
"content": {
"application/json": {
"schema": {
"anyOf": [
{
"$ref": "#/components/schemas/Error"
},
{
"$ref": "#/components/schemas/JsonParseError"
}
]
}
}
}
},
"401": {
"description": "Authentication failed",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorMessage"
}
}
}
},
"403": {
"description": "Permission denied, the caller is banned, or the request fails tenant isolation",
"content": {
"application/json": {
"schema": {
"anyOf": [
{
"$ref": "#/components/schemas/Error"
},
{
"$ref": "#/components/schemas/MessageError"
},
{
"$ref": "#/components/schemas/ErrorMessage"
}
]
}
}
}
},
"404": {
"description": "Not found",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"409": {
"description": "The bound account is being deleted",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/AccountDeletionConflict"
}
}
}
},
"500": {
"description": "Internal server error. Errors normalized by the route use JSON; the final application error controller sends a text body with the text/html media type.",
"content": {
"application/json": {
"schema": {
"anyOf": [
{
"$ref": "#/components/schemas/Error"
},
{
"$ref": "#/components/schemas/ErrorMessage"
}
]
}
},
"text/html": {
"schema": {
"type": "string",
"enum": [
"An unknown error occurred.",
"Processing error in ErrorController."
]
}
}
}
}
}
}
},
"/skills/{id}/files": {
@ -1794,6 +2056,143 @@
}
}
},
"delete": {
"operationId": "deleteSkillFile",
"summary": "Delete a skill's file",
"tags": [
"Skills"
],
"security": [
{
"oidcBearer": []
}
],
"parameters": [
{
"in": "path",
"name": "id",
"description": "The skill id",
"schema": {
"type": "string"
},
"required": true
},
{
"in": "path",
"name": "relativePath",
"description": "The file path within the skill",
"schema": {
"type": "string"
},
"required": true
}
],
"responses": {
"200": {
"description": "The file was deleted",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/SkillFileDeleted"
}
}
}
},
"400": {
"description": "Invalid request, or a malformed JSON body",
"content": {
"application/json": {
"schema": {
"anyOf": [
{
"$ref": "#/components/schemas/Error"
},
{
"$ref": "#/components/schemas/JsonParseError"
}
]
}
}
}
},
"401": {
"description": "Authentication failed",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorMessage"
}
}
}
},
"403": {
"description": "Permission denied, the caller is banned, or the request fails tenant isolation",
"content": {
"application/json": {
"schema": {
"anyOf": [
{
"$ref": "#/components/schemas/Error"
},
{
"$ref": "#/components/schemas/MessageError"
},
{
"$ref": "#/components/schemas/ErrorMessage"
}
]
}
}
}
},
"404": {
"description": "Not found",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"409": {
"description": "The bound account is being deleted",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/AccountDeletionConflict"
}
}
}
},
"500": {
"description": "Internal server error. Errors normalized by the route use JSON; the final application error controller sends a text body with the text/html media type.",
"content": {
"application/json": {
"schema": {
"anyOf": [
{
"$ref": "#/components/schemas/Error"
},
{
"$ref": "#/components/schemas/ErrorMessage"
}
]
}
},
"text/html": {
"schema": {
"type": "string",
"enum": [
"An unknown error occurred.",
"Processing error in ErrorController."
]
}
}
}
}
}
},
"put": {
"operationId": "updateSkillFile",
"summary": "Create or update a skill's file",
@ -3807,6 +4206,41 @@
"after"
]
},
"SkillCreateRequest": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"displayTitle": {
"type": "string"
},
"description": {
"type": "string"
},
"body": {
"type": "string"
},
"frontmatter": {
"type": "object",
"additionalProperties": {
"$ref": "#/components/schemas/SkillFrontmatterValue"
}
},
"category": {
"type": "string"
},
"alwaysApply": {
"type": "boolean"
}
},
"required": [
"name",
"description",
"body"
],
"additionalProperties": false
},
"SkillUpdateRequest": {
"type": "object",
"properties": {
@ -3845,6 +4279,26 @@
"additionalProperties": false,
"minProperties": 2
},
"SkillDeleted": {
"type": "object",
"properties": {
"id": {
"type": "string",
"pattern": "^[a-f\\d]{24}$"
},
"deleted": {
"type": "boolean",
"const": true
},
"cleanupComplete": {
"type": "boolean"
}
},
"required": [
"id",
"deleted"
]
},
"SkillFile": {
"type": "object",
"properties": {
@ -3949,6 +4403,27 @@
"bytes"
]
},
"SkillFileDeleted": {
"type": "object",
"properties": {
"skillId": {
"type": "string",
"pattern": "^[a-f\\d]{24}$"
},
"relativePath": {
"type": "string"
},
"deleted": {
"type": "boolean",
"const": true
}
},
"required": [
"skillId",
"relativePath",
"deleted"
]
},
"ErrorMessage": {
"type": "object",
"properties": {

View file

@ -3,12 +3,15 @@ import type { ZodTypeAny } from 'zod';
import type { EndpointContract } from './adapter';
import {
skillManagementUpdateSchema,
skillManagementCreateSchema,
skillManagementResponseSchema,
skillSummarySchema,
skillFileSchema,
skillFileContentSchema,
skillFileUpdateSchema,
skillFrontmatterValueSchema,
skillDeleteResponseSchema,
skillFileDeleteResponseSchema,
} from '../skills/management';
import {
errorMessageResponseSchema,
@ -42,12 +45,15 @@ export const skillComponentSchemas: Record<string, ZodTypeAny> = {
SkillFrontmatterValue: skillFrontmatterValueSchema,
Skill: skillManagementResponseSchema,
SkillList: skillListResponseSchema,
SkillCreateRequest: skillManagementCreateSchema,
SkillUpdateRequest: skillManagementUpdateSchema,
SkillDeleted: skillDeleteResponseSchema,
SkillFile: skillFileSchema,
SkillFileList: skillFileListResponseSchema,
SkillFileContent: skillFileContentSchema,
SkillFileUpdateRequest: skillFileUpdateSchema,
SkillFileUpdated: skillFileUpdatedSchema,
SkillFileDeleted: skillFileDeleteResponseSchema,
};
const errorResponses = [
@ -95,6 +101,24 @@ export const skillContracts: EndpointContract[] = [
...errorResponses,
],
},
{
operationId: 'createSkill',
method: 'post',
path: '/skills',
tags: [TAG],
summary: 'Create a skill',
security: SECURITY,
body: skillManagementCreateSchema,
responses: [
{ status: 201, description: 'The created skill', schema: skillManagementResponseSchema },
...errorResponses,
{
status: 409,
description: 'The Skill name already exists, or the bound account is being deleted',
schema: z.union([agentManagementErrorSchema, accountDeletionResponseSchema]),
},
],
},
{
operationId: 'getSkill',
method: 'get',
@ -128,6 +152,19 @@ export const skillContracts: EndpointContract[] = [
},
],
},
{
operationId: 'deleteSkill',
method: 'delete',
path: '/skills/{id}',
tags: [TAG],
summary: 'Delete a skill',
security: SECURITY,
pathParams: [{ name: 'id', description: 'The skill id' }],
responses: [
{ status: 200, description: 'The skill was deleted', schema: skillDeleteResponseSchema },
...errorResponses,
],
},
{
operationId: 'listSkillFiles',
method: 'get',
@ -157,6 +194,22 @@ export const skillContracts: EndpointContract[] = [
...errorResponses,
],
},
{
operationId: 'deleteSkillFile',
method: 'delete',
path: '/skills/{id}/files/{relativePath}',
tags: [TAG],
summary: "Delete a skill's file",
security: SECURITY,
pathParams: [
{ name: 'id', description: 'The skill id' },
{ name: 'relativePath', description: 'The file path within the skill' },
],
responses: [
{ status: 200, description: 'The file was deleted', schema: skillFileDeleteResponseSchema },
...errorResponses,
],
},
{
operationId: 'updateSkillFile',
method: 'put',

View file

@ -21,8 +21,10 @@ let db: AllMethods;
let app: express.Express;
let skillId: string;
let allowEdit: boolean;
let allowDelete: boolean;
let allowView: boolean;
let allowUse: boolean;
let allowCreate: boolean;
let canManage: boolean;
let authenticated: boolean;
let saveFile: jest.MockedFunction<SkillManagementDeps['saveFile']>;
@ -54,8 +56,10 @@ afterAll(async () => {
beforeEach(async () => {
await mongoose.connection.dropDatabase();
allowEdit = true;
allowDelete = true;
allowView = true;
allowUse = true;
allowCreate = true;
canManage = false;
authenticated = true;
filters = undefined;
@ -100,12 +104,15 @@ beforeEach(async () => {
permissions: {
[PermissionTypes.SKILLS]: {
[Permissions.USE]: allowUse,
[Permissions.CREATE]: true,
[Permissions.CREATE]: allowCreate,
},
},
}) as IRole,
checkPermission: async ({ requiredPermission }) =>
requiredPermission === PermissionBits.EDIT ? allowEdit : allowView,
checkPermission: async ({ requiredPermission }) => {
if (requiredPermission === PermissionBits.EDIT) return allowEdit;
if (requiredPermission === PermissionBits.DELETE) return allowDelete;
return allowView;
},
saveFile,
hasCapability: capabilityCheck,
});
@ -119,12 +126,18 @@ beforeEach(async () => {
app.get('/skills', async (req, res) => {
await management.list(req, res);
});
app.post('/skills', async (req, res) => {
await management.create(req, res);
});
app.get('/skills/:id', async (req, res) => {
await management.get(req, res);
});
app.patch('/skills/:id', async (req, res) => {
await management.update(req, res);
});
app.delete('/skills/:id', async (req, res) => {
await management.delete(req, res);
});
app.get('/skills/:id/files', async (req, res) => {
await management.listFiles(req, res);
});
@ -134,6 +147,65 @@ beforeEach(async () => {
app.put('/skills/:id/files/*relativePath', async (req, res) => {
await management.updateFile(req, res);
});
app.delete('/skills/:id/files/*relativePath', async (req, res) => {
await management.deleteFile(req, res);
});
});
it('creates an inline tenant Skill and returns the versioned representation', async () => {
const response = await request(app)
.post('/skills')
.send({
name: 'created-skill',
description: 'A newly created management Skill.',
body: 'Created instructions',
})
.expect(201);
expect(response.body).toMatchObject({
name: 'created-skill',
body: 'Created instructions',
version: 1,
});
expect(response.body.id).toMatch(/^[a-f\d]{24}$/i);
expect(response.body).not.toHaveProperty('_id');
expect(await inTenant(() => db.getSkillById(response.body.id))).toMatchObject({
tenantId,
source: 'inline',
});
});
it.each([
{ name: 'missing-body', description: 'Missing body.' },
{ name: 'forged-tenant', description: 'Forged tenant.', body: 'x', tenantId: 'foreign' },
{ name: 'forged-author', description: 'Forged author.', body: 'x', author: 'caller' },
{ name: 'forged-source', description: 'Forged source.', body: 'x', source: 'github' },
])('rejects malformed or caller-controlled creation input %j', async (body) => {
await request(app).post('/skills').send(body).expect(400);
});
it('requires create capability for management mutations', async () => {
allowCreate = false;
await request(app)
.post('/skills')
.send({ name: 'denied', description: 'Denied Skill.', body: 'Denied' })
.expect(403);
await request(app)
.patch(`/skills/${skillId}`)
.send({ expectedVersion: 1, body: 'Denied' })
.expect(403);
await request(app).delete(`/skills/${skillId}`).expect(403);
});
it('deletes an authorized inline Skill through the existing cleanup path', async () => {
const response = await request(app).delete(`/skills/${skillId}`).expect(200);
expect(response.body).toEqual({ id: skillId, deleted: true, cleanupComplete: true });
expect(await inTenant(() => db.getSkillById(skillId))).toBeNull();
});
it('requires DELETE permission without revealing inaccessible Skills', async () => {
allowDelete = false;
await request(app).delete(`/skills/${skillId}`).expect(404);
expect(await inTenant(() => db.getSkillById(skillId))).not.toBeNull();
});
it('lists and retrieves stable representations without ownership or storage internals', async () => {
@ -201,6 +273,7 @@ it.each([
it('hides inaccessible and cross-tenant Skills, including on file writes', async () => {
allowView = false;
allowEdit = false;
allowDelete = false;
await request(app).get(`/skills/${skillId}`).expect(404);
await request(app)
.patch(`/skills/${skillId}`)
@ -210,6 +283,8 @@ it('hides inaccessible and cross-tenant Skills, including on file writes', async
.put(`/skills/${skillId}/files/reference.md`)
.send({ content: 'x' })
.expect(404);
await request(app).delete(`/skills/${skillId}`).expect(404);
await request(app).delete(`/skills/${skillId}/files/reference.md`).expect(404);
expect(saveFile).not.toHaveBeenCalled();
allowView = true;
allowEdit = true;
@ -257,6 +332,8 @@ it('keeps synchronized Skill content and files read-only', async () => {
.put(`/skills/${skillId}/files/reference.md`)
.send({ content: 'x' })
.expect(403);
await request(app).delete(`/skills/${skillId}`).expect(403);
await request(app).delete(`/skills/${skillId}/files/reference.md`).expect(403);
expect(saveFile).not.toHaveBeenCalled();
});
it('writes nested text files through existing storage and rejects unsafe paths', async () => {
@ -284,6 +361,32 @@ it('writes nested text files through existing storage and rejects unsafe paths',
}
expect(saveFile).not.toHaveBeenCalled();
});
it('deletes nested Skill files and rejects unsafe paths', async () => {
await inTenant(() =>
db.upsertSkillFile({
skillId,
relativePath: 'references/guide.md',
file_id: 'file-revision',
filename: 'guide.md',
filepath: '/uploads/guide.md',
source: 'local',
mimeType: 'text/markdown',
bytes: 5,
author,
tenantId,
}),
);
const response = await request(app)
.delete(`/skills/${skillId}/files/references/guide.md`)
.expect(200);
expect(response.body).toEqual({
skillId,
relativePath: 'references/guide.md',
deleted: true,
});
expect(await inTenant(() => db.getSkillFileByPath(skillId, 'references/guide.md'))).toBeNull();
await request(app).delete(`/skills/${skillId}/files/..%2Fescape.md`).expect(400);
});
it('rejects raw downloads and malformed pagination', async () => {
await request(app).get(`/skills/${skillId}/files/SKILL.md?raw=true`).expect(400);
await request(app).get('/skills?limit=0').expect(400);

View file

@ -6,7 +6,14 @@ import {
PermissionTypes,
ResourceType,
} from 'librechat-data-provider';
import type { SkillFrontmatterValue, TSkill, TUpdateSkillPayload } from 'librechat-data-provider';
import type {
SkillFrontmatterValue,
TCreateSkill,
TDeleteSkillFileResponse,
TDeleteSkillResponse,
TSkill,
TUpdateSkillPayload,
} from 'librechat-data-provider';
import type { Request, Response, RequestHandler } from 'express';
import type { SkillsHandlers, SkillsHandlersDeps } from './handlers';
import type { AgentManagementReadDeps } from '../agents/reads';
@ -38,6 +45,18 @@ export const skillFrontmatterValueSchema: z.ZodType<SkillFrontmatterValue> = z.l
);
export type SkillManagementUpdate = TUpdateSkillPayload & { expectedVersion: number };
export const skillManagementCreateSchema: z.ZodType<TCreateSkill> = z
.object({
name: fields.name,
displayTitle: fields.displayTitle,
description: fields.description,
body: z.string(),
frontmatter: z.record(skillFrontmatterValueSchema).optional(),
category: fields.category,
alwaysApply: fields.alwaysApply,
})
.strict();
export const skillManagementUpdateSchema: z.ZodType<SkillManagementUpdate> = z
.object({
name: fields.name.optional(),
@ -107,6 +126,16 @@ export const skillFileContentSchema: z.AnyZodObject = skillFileSchema.extend({
export const skillFileUpdateSchema: z.AnyZodObject = z
.object({ content: z.string().max(1024 * 1024) })
.strict();
export const skillDeleteResponseSchema: z.ZodType<TDeleteSkillResponse> = z.object({
id: idSchema,
deleted: z.literal(true),
cleanupComplete: z.boolean().optional(),
});
export const skillFileDeleteResponseSchema: z.ZodType<TDeleteSkillFileResponse> = z.object({
skillId: idSchema,
relativePath: z.string(),
deleted: z.literal(true),
});
const listSchema = agentManagementListSchema;
type ManagementRequest = Request &
@ -210,7 +239,15 @@ async function admitFileWrite(req: Request, res: Response, limiters: RequestHand
export function createSkillManagementHandlers(
deps: SkillManagementDeps,
): Record<
'list' | 'get' | 'update' | 'listFiles' | 'getFile' | 'updateFile',
| 'list'
| 'create'
| 'get'
| 'update'
| 'delete'
| 'listFiles'
| 'getFile'
| 'updateFile'
| 'deleteFile',
(request: Request, res: Response) => Promise<Response>
> {
async function canManageSkills(req: ManagementRequest): Promise<boolean> {
@ -225,17 +262,18 @@ export function createSkillManagementHandlers(
function wrap(
permission: PermissionBits | undefined,
operation: (req: ManagementRequest, res: Response) => Promise<Response>,
options: { mutation?: boolean } = {},
) {
return async (request: Request, res: Response): Promise<Response> => {
const req = request as ManagementRequest;
try {
if (!req.user?.id || !req.user.tenantId) return sendError(res, 'permission_denied');
const editing = permission === PermissionBits.EDIT;
const mutation = options.mutation === true;
const allowed = await checkAccessWithRequestCache({
req,
user: req.user,
permissionType: PermissionTypes.SKILLS,
permissions: editing ? [Permissions.USE, Permissions.CREATE] : [Permissions.USE],
permissions: mutation ? [Permissions.USE, Permissions.CREATE] : [Permissions.USE],
getRoleByName: deps.getRoleByName,
});
if (!allowed) return sendError(res, 'permission_denied');
@ -260,7 +298,7 @@ export function createSkillManagementHandlers(
}))
)
return sendError(res, 'not_found');
if (editing && (deployment || skill.source !== 'inline'))
if (mutation && (deployment || skill.source !== 'inline'))
return sendError(res, 'permission_denied');
req.resourceAccess = { resourceInfo: skill };
}
@ -310,6 +348,16 @@ export function createSkillManagementHandlers(
},
);
}),
create: wrap(
undefined,
async (req, res) => {
const parsed = skillManagementCreateSchema.safeParse(req.body);
if (!parsed.success) return sendError(res, 'invalid_request', parsed.error);
req.body = parsed.data;
return runHandler(req, res, deps.handlers.create, (body) => projectSkill(body, true));
},
{ mutation: true },
),
get: wrap(PermissionBits.VIEW, (req, res) =>
runHandler(
req,
@ -318,18 +366,28 @@ export function createSkillManagementHandlers(
(body) => projectSkill(body, true),
),
),
update: wrap(PermissionBits.EDIT, async (req, res) => {
const parsed = skillManagementUpdateSchema.safeParse(req.body);
if (!parsed.success) return sendError(res, 'invalid_request', parsed.error);
req.body = parsed.data;
return runHandler(
req,
res,
(request, response) =>
deps.handlers.patch(request, response, { includePublicStatus: false }),
(body) => projectSkill(body, true),
);
}),
update: wrap(
PermissionBits.EDIT,
async (req, res) => {
const parsed = skillManagementUpdateSchema.safeParse(req.body);
if (!parsed.success) return sendError(res, 'invalid_request', parsed.error);
req.body = parsed.data;
return runHandler(
req,
res,
(request, response) =>
deps.handlers.patch(request, response, { includePublicStatus: false }),
(body) => projectSkill(body, true),
);
},
{ mutation: true },
),
delete: wrap(
PermissionBits.DELETE,
(req, res) =>
runHandler(req, res, deps.handlers.delete, (body) => skillDeleteResponseSchema.parse(body)),
{ mutation: true },
),
listFiles: wrap(PermissionBits.VIEW, (req, res) =>
runHandler(req, res, deps.handlers.listFiles, (body) => ({
object: 'list',
@ -342,41 +400,58 @@ export function createSkillManagementHandlers(
skillFileContentSchema.parse(body),
);
}),
updateFile: wrap(PermissionBits.EDIT, async (req, res) => {
const parsed = skillFileUpdateSchema.safeParse(req.body);
if (!parsed.success) return sendError(res, 'invalid_request', parsed.error);
const relativePath = resolveSkillFilePathParam(req.params.relativePath);
if (relativePath == null || validateRelativePath(relativePath).length > 0)
return sendError(res, 'invalid_request');
const buffer = Buffer.from(parsed.data.content, 'utf8');
if (buffer.length > 1024 * 1024 || buffer.includes(0))
return sendError(res, 'invalid_request');
try {
assertSkillFileContentAllowed(req.config?.filters, {
buffer,
originalName: relativePath,
relativePath,
});
} catch (error) {
if (!isContentFilterError(error)) throw error;
return sendError(res, 'invalid_request');
}
if (!(await admitFileWrite(req, res, deps.fileWriteLimiters ?? []))) return res;
try {
const result = await deps.saveFile({
req: req as ServerRequest,
skillId: req.params.id,
relativePath,
content: parsed.data.content,
mimeType: 'text/plain',
});
return res.status(200).json({ relativePath: result.relativePath, bytes: result.bytes });
} catch (error) {
if (error instanceof Error && 'code' in error && error.code === 'SKILL_FILE_CONFLICT') {
return sendError(res, 'conflict');
updateFile: wrap(
PermissionBits.EDIT,
async (req, res) => {
const parsed = skillFileUpdateSchema.safeParse(req.body);
if (!parsed.success) return sendError(res, 'invalid_request', parsed.error);
const relativePath = resolveSkillFilePathParam(req.params.relativePath);
if (relativePath == null || validateRelativePath(relativePath).length > 0)
return sendError(res, 'invalid_request');
const buffer = Buffer.from(parsed.data.content, 'utf8');
if (buffer.length > 1024 * 1024 || buffer.includes(0))
return sendError(res, 'invalid_request');
try {
assertSkillFileContentAllowed(req.config?.filters, {
buffer,
originalName: relativePath,
relativePath,
});
} catch (error) {
if (!isContentFilterError(error)) throw error;
return sendError(res, 'invalid_request');
}
throw error;
}
}),
if (!(await admitFileWrite(req, res, deps.fileWriteLimiters ?? []))) return res;
try {
const result = await deps.saveFile({
req: req as ServerRequest,
skillId: req.params.id,
relativePath,
content: parsed.data.content,
mimeType: 'text/plain',
});
return res.status(200).json({ relativePath: result.relativePath, bytes: result.bytes });
} catch (error) {
if (error instanceof Error && 'code' in error && error.code === 'SKILL_FILE_CONFLICT') {
return sendError(res, 'conflict');
}
throw error;
}
},
{ mutation: true },
),
deleteFile: wrap(
PermissionBits.EDIT,
async (req, res) => {
const relativePath = resolveSkillFilePathParam(req.params.relativePath);
if (relativePath == null || validateRelativePath(relativePath).length > 0)
return sendError(res, 'invalid_request');
req.params.relativePath = relativePath;
return runHandler(req, res, deps.handlers.deleteFile, (body) =>
skillFileDeleteResponseSchema.parse(body),
);
},
{ mutation: true },
),
};
}