mirror of
https://github.com/whyour/qinglong.git
synced 2026-11-30 16:27:21 +08:00
Upgrade SQLite to 1.1.5 so tar resolves safely without an override. Update vulnerable dependencies while retaining scoped compatibility overrides and the CommonJS decoder patch required by Umi's query-string consumers. Limit sensitive endpoints, constrain script file operations to checked paths, and serialize Python environment values safely. Add compatibility regressions and include the decoder patch in Docker and npm installation inputs.
295 lines
8.5 KiB
TypeScript
295 lines
8.5 KiB
TypeScript
import groupBy from 'lodash/groupBy';
|
|
import { FindOptions, Op } from 'sequelize';
|
|
import { Inject, Service } from 'typedi';
|
|
import winston from 'winston';
|
|
import config from '../config';
|
|
import {
|
|
Env,
|
|
EnvModel,
|
|
EnvStatus,
|
|
initPosition,
|
|
maxPosition,
|
|
minPosition,
|
|
stepPosition,
|
|
} from '../data/env';
|
|
import { writeFileWithLock } from '../shared/utils';
|
|
import { sequelize } from '../data';
|
|
import {
|
|
assertAllowedTaskEnvName,
|
|
isAllowedTaskEnvName,
|
|
} from '../shared/taskEnvName';
|
|
|
|
@Service()
|
|
export default class EnvService {
|
|
constructor(@Inject('logger') private logger: winston.Logger) { }
|
|
|
|
public async create(payloads: Env[]): Promise<Env[]> {
|
|
payloads.forEach((payload) => assertAllowedTaskEnvName(payload.name));
|
|
const envs = await this.envs();
|
|
let position = initPosition;
|
|
if (
|
|
envs &&
|
|
envs.length > 0 &&
|
|
typeof envs[envs.length - 1].position === 'number'
|
|
) {
|
|
position = this.getPrecisionPosition(envs[envs.length - 1].position!);
|
|
}
|
|
const tabs = payloads.map((x) => {
|
|
position = position - stepPosition;
|
|
const tab = new Env({ ...x, position });
|
|
return tab;
|
|
});
|
|
const docs = await this.insert(tabs);
|
|
await this.set_envs();
|
|
await this.checkPosition(tabs[tabs.length - 1].position!);
|
|
return docs;
|
|
}
|
|
|
|
public async insert(payloads: Env[]): Promise<Env[]> {
|
|
const result: Env[] = [];
|
|
for (const env of payloads) {
|
|
const doc = await EnvModel.create(env, { returning: true });
|
|
result.push(doc);
|
|
}
|
|
return result;
|
|
}
|
|
|
|
public async update(payload: Env): Promise<Env> {
|
|
const doc = await this.getDb({ id: payload.id });
|
|
const tab = new Env({ ...doc, ...payload });
|
|
assertAllowedTaskEnvName(tab.name);
|
|
const newDoc = await this.updateDb(tab);
|
|
await this.set_envs();
|
|
return newDoc;
|
|
}
|
|
|
|
private async updateDb(payload: Env): Promise<Env> {
|
|
await EnvModel.update({ ...payload }, { where: { id: payload.id } });
|
|
return await this.getDb({ id: payload.id });
|
|
}
|
|
|
|
public async remove(ids: number[]) {
|
|
await EnvModel.destroy({ where: { id: ids } });
|
|
await this.set_envs();
|
|
}
|
|
|
|
public async move(
|
|
id: number,
|
|
{
|
|
fromIndex,
|
|
toIndex,
|
|
}: {
|
|
fromIndex: number;
|
|
toIndex: number;
|
|
},
|
|
): Promise<Env> {
|
|
let targetPosition: number;
|
|
const isUpward = fromIndex > toIndex;
|
|
const envs = await this.envs();
|
|
if (toIndex === 0 || toIndex === envs.length - 1) {
|
|
targetPosition = isUpward
|
|
? envs[0].position! + stepPosition
|
|
: envs[toIndex].position! - stepPosition;
|
|
} else {
|
|
targetPosition = isUpward
|
|
? (envs[toIndex].position! + envs[toIndex - 1].position!) / 2
|
|
: (envs[toIndex].position! + envs[toIndex + 1].position!) / 2;
|
|
}
|
|
|
|
const newDoc = await this.update({
|
|
id,
|
|
position: this.getPrecisionPosition(targetPosition),
|
|
});
|
|
|
|
await this.checkPosition(targetPosition, envs[toIndex].position!);
|
|
return newDoc;
|
|
}
|
|
|
|
private async checkPosition(position: number, edge: number = 0) {
|
|
const precisionPosition = this.getPrecisionPosition(position);
|
|
if (
|
|
precisionPosition < minPosition ||
|
|
precisionPosition > maxPosition ||
|
|
Math.abs(precisionPosition - edge) < minPosition
|
|
) {
|
|
const envs = await this.envs();
|
|
let position = initPosition;
|
|
for (const env of envs) {
|
|
position = position - stepPosition;
|
|
await this.updateDb({ id: env.id, position });
|
|
}
|
|
}
|
|
}
|
|
|
|
private getPrecisionPosition(position: number): number {
|
|
return Math.trunc(parseFloat(position.toPrecision(16)));
|
|
}
|
|
|
|
public async envs(searchText: string = '', query: any = {}): Promise<Env[]> {
|
|
let condition = { ...query };
|
|
if (searchText) {
|
|
const encodeText = encodeURI(searchText);
|
|
const reg = {
|
|
[Op.or]: [
|
|
{ [Op.like]: `%${searchText}%` },
|
|
{ [Op.like]: `%${encodeText}%` },
|
|
],
|
|
};
|
|
|
|
condition = {
|
|
...condition,
|
|
[Op.or]: [
|
|
{
|
|
name: reg,
|
|
},
|
|
{
|
|
value: reg,
|
|
},
|
|
{
|
|
remarks: reg,
|
|
},
|
|
],
|
|
};
|
|
}
|
|
try {
|
|
const result = await this.find(condition, [
|
|
[sequelize.literal('COALESCE(`isPinned`, 0)'), 'DESC'],
|
|
['position', 'DESC'],
|
|
['createdAt', 'ASC'],
|
|
]);
|
|
return result.map((env) => ({
|
|
...env,
|
|
securityBlocked: !isAllowedTaskEnvName(env.name),
|
|
}));
|
|
} catch (error) {
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
private async find(query: any, sort: any = []): Promise<Env[]> {
|
|
const docs = await EnvModel.findAll({
|
|
where: { ...query },
|
|
order: [...sort],
|
|
});
|
|
return docs.map((x) => x.get({ plain: true }));
|
|
}
|
|
|
|
public async getDb(query: FindOptions<Env>['where']): Promise<Env> {
|
|
const doc: any = await EnvModel.findOne({ where: { ...query } });
|
|
if (!doc) {
|
|
throw new Error(`Env ${JSON.stringify(query)} not found`);
|
|
}
|
|
return doc.get({ plain: true });
|
|
}
|
|
|
|
public async disabled(ids: number[]) {
|
|
await EnvModel.update(
|
|
{ status: EnvStatus.disabled },
|
|
{ where: { id: ids } },
|
|
);
|
|
await this.set_envs();
|
|
}
|
|
|
|
public async enabled(ids: number[]) {
|
|
const docs = await EnvModel.findAll({ where: { id: ids } });
|
|
docs.forEach((doc) => assertAllowedTaskEnvName(doc.name));
|
|
await EnvModel.update({ status: EnvStatus.normal }, { where: { id: ids } });
|
|
await this.set_envs();
|
|
}
|
|
|
|
public async updateNames({ ids, name }: { ids: number[]; name: string }) {
|
|
assertAllowedTaskEnvName(name);
|
|
await EnvModel.update({ name }, { where: { id: ids } });
|
|
await this.set_envs();
|
|
}
|
|
|
|
public async pin(ids: number[]) {
|
|
await EnvModel.update({ isPinned: 1 }, { where: { id: ids } });
|
|
}
|
|
|
|
public async unPin(ids: number[]) {
|
|
await EnvModel.update({ isPinned: 0 }, { where: { id: ids } });
|
|
}
|
|
|
|
public async addLabels(ids: number[], labels: string[]) {
|
|
await sequelize.transaction(async (transaction) => {
|
|
const docs = await EnvModel.findAll({
|
|
where: { id: ids },
|
|
transaction,
|
|
});
|
|
for (const doc of docs) {
|
|
const env = doc.get({ plain: true });
|
|
await EnvModel.update(
|
|
{ labels: Array.from(new Set([...(env.labels || []), ...labels])) },
|
|
{ where: { id: env.id }, transaction },
|
|
);
|
|
}
|
|
});
|
|
return await this.find({ id: ids });
|
|
}
|
|
|
|
public async removeLabels(ids: number[], labels: string[]) {
|
|
await sequelize.transaction(async (transaction) => {
|
|
const docs = await EnvModel.findAll({
|
|
where: { id: ids },
|
|
transaction,
|
|
});
|
|
for (const doc of docs) {
|
|
const env = doc.get({ plain: true });
|
|
await EnvModel.update(
|
|
{
|
|
labels: (env.labels || []).filter(
|
|
(label: string) => !labels.includes(label),
|
|
),
|
|
},
|
|
{ where: { id: env.id }, transaction },
|
|
);
|
|
}
|
|
});
|
|
return await this.find({ id: ids });
|
|
}
|
|
|
|
public async set_envs() {
|
|
const envs = await this.envs('', {
|
|
name: { [Op.not]: null },
|
|
status: EnvStatus.normal,
|
|
});
|
|
const invalid = envs.filter((env) => !isAllowedTaskEnvName(env.name));
|
|
if (invalid.length > 0) {
|
|
this.logger.warn(
|
|
'Skipped reserved environment variables in task files: %s',
|
|
JSON.stringify(invalid.map((env) => ({ id: env.id, name: env.name }))),
|
|
);
|
|
}
|
|
const groups = groupBy(envs, 'name');
|
|
let env_string = '';
|
|
let js_env_string = '';
|
|
let py_env_string = 'import os, json\n';
|
|
for (const key in groups) {
|
|
if (Object.prototype.hasOwnProperty.call(groups, key)) {
|
|
const group = groups[key];
|
|
|
|
// Ignore invalid and reserved names, including legacy database rows.
|
|
if (isAllowedTaskEnvName(key)) {
|
|
let value = group
|
|
.map((x) => x.value)
|
|
.join('&')
|
|
.replace(/'/g, "'\\''")
|
|
.trim();
|
|
env_string += `export ${key}='${value}'\n`;
|
|
js_env_string += `process.env[${JSON.stringify(key)}]=${JSON.stringify(
|
|
group.map((x) => x.value).join('&'),
|
|
)};\n`;
|
|
// Serialize data instead of constructing an escaped Python literal.
|
|
py_env_string += `os.environ['${key}']=json.loads(${JSON.stringify(
|
|
JSON.stringify(group.map((x) => x.value).join('&')),
|
|
)})\n`;
|
|
}
|
|
}
|
|
}
|
|
await writeFileWithLock(config.envFile, env_string);
|
|
await writeFileWithLock(config.jsEnvFile, js_env_string);
|
|
await writeFileWithLock(config.pyEnvFile, py_env_string);
|
|
}
|
|
}
|