import Planka upstream

This commit is contained in:
xiaojibeier
2026-07-18 11:48:22 +08:00
commit c26fd3b190
1564 changed files with 214813 additions and 0 deletions
@@ -0,0 +1,21 @@
/*!
* Copyright (c) 2024 PLANKA Software GmbH
* Licensed under the Fair Use License: https://github.com/plankanban/planka/blob/master/LICENSE.md
*/
module.exports = {
sync: true,
inputs: {
response: {
type: 'ref',
required: true,
},
},
fn(inputs) {
inputs.response.clearCookie('httpOnlyToken', {
path: sails.config.custom.baseUrlPath || '/',
});
},
};
@@ -0,0 +1,46 @@
/*!
* Copyright (c) 2024 PLANKA Software GmbH
* Licensed under the Fair Use License: https://github.com/plankanban/planka/blob/master/LICENSE.md
*/
const { v4: uuid } = require('uuid');
const jwt = require('jsonwebtoken');
module.exports = {
sync: true,
inputs: {
subject: {
type: 'json',
required: true,
},
issuedAt: {
type: 'ref',
},
expiresIn: {
type: 'number',
},
},
fn(inputs) {
const { issuedAt = new Date(), expiresIn = sails.config.custom.tokenExpiresIn } = inputs;
const iat = Math.floor(issuedAt / 1000);
const exp = iat + expiresIn;
const payload = {
iat,
exp,
sub: inputs.subject,
};
const token = jwt.sign(payload, sails.config.session.secret, {
keyid: uuid(),
});
return {
token,
payload,
};
},
};
@@ -0,0 +1,191 @@
/*!
* Copyright (c) 2024 PLANKA Software GmbH
* Licensed under the Fair Use License: https://github.com/plankanban/planka/blob/master/LICENSE.md
*/
const { URL } = require('url');
const { ProxyAgent } = require('undici');
const icoToPng = require('ico-to-png');
const sharp = require('sharp');
const FETCH_TIMEOUT = 4000;
const MAX_RESPONSE_LENGTH = 1024 * 1024;
const FAVICON_TAGS_REGEX = /<link [^>]*rel="([^"]* )?icon( [^"]*)?"[^>]*>/gi;
const HREF_REGEX = /href="(.*?)"/i;
const SIZES_REGEX = /sizes="(.*?)"/i;
const fetchWithTimeout = (url) => {
const abortController = new AbortController();
setTimeout(() => abortController.abort(), FETCH_TIMEOUT);
return fetch(url, {
signal: abortController.signal,
dispatcher: sails.config.custom.outgoingProxy
? new ProxyAgent(sails.config.custom.outgoingProxy)
: undefined,
});
};
const readResponse = async (response) => {
const reader = response.body.getReader();
const chunks = [];
let receivedLength = 0;
for (;;) {
const { value, done } = await reader.read(); // eslint-disable-line no-await-in-loop
if (done) {
break;
}
chunks.push(value);
receivedLength += value.length;
if (receivedLength > MAX_RESPONSE_LENGTH) {
reader.cancel();
return {
ok: false,
buffer: Buffer.concat(chunks),
};
}
}
return {
ok: true,
buffer: Buffer.concat(chunks),
};
};
const isWantedFaviconTag = (faviconTag) => {
const sizesMatch = faviconTag.match(SIZES_REGEX);
if (!sizesMatch) {
return false;
}
const sizes = sizesMatch[1].split('x');
return parseInt(sizes[0], 10) >= 32 && parseInt(sizes[1], 10) >= 32;
};
module.exports = {
inputs: {
url: {
type: 'string',
required: true,
},
},
async fn(inputs) {
const { hostname, origin } = new URL(inputs.url);
let response;
let readedResponse;
try {
response = await fetchWithTimeout(origin);
if (!response.ok) {
return;
}
readedResponse = await readResponse(response);
} catch (error) {
return;
}
const content = readedResponse.buffer.toString();
const faviconTagsMatch = content.match(FAVICON_TAGS_REGEX);
let faviconUrl;
if (faviconTagsMatch && faviconTagsMatch.length > 0) {
let faviconTag;
if (faviconTagsMatch.length > 1) {
faviconTag = faviconTagsMatch.find(isWantedFaviconTag);
}
if (!faviconTag) {
[faviconTag] = faviconTagsMatch;
}
const hrefMatch = faviconTag.match(HREF_REGEX);
if (hrefMatch) {
faviconUrl = new URL(hrefMatch[1], response.url).href;
}
}
if (!faviconUrl) {
faviconUrl = new URL('/favicon.ico', response.url).href;
}
try {
response = await fetchWithTimeout(faviconUrl);
if (!response.ok) {
return;
}
readedResponse = await readResponse(response);
} catch (error) {
return;
}
if (!readedResponse.ok) {
return;
}
const availableStorage = await sails.helpers.utils.getAvailableStorage();
if (availableStorage !== null && readedResponse.buffer.length >= availableStorage) {
return;
}
let image = sharp(readedResponse.buffer);
let metadata;
try {
metadata = await image.metadata();
} catch (error) {
/* empty */
}
if (!metadata || metadata.format === 'magick') {
try {
const buffer = await icoToPng(readedResponse.buffer, 32);
image = sharp(buffer);
metadata = await image.metadata();
} catch (error) {
return;
}
}
const fileManager = sails.hooks['file-manager'].getInstance();
const { width, height } = metadata;
image = image
.resize(
32,
32,
width < 32 || height < 32
? {
kernel: sharp.kernel.nearest,
}
: undefined,
)
.png();
try {
await fileManager.save(
`${sails.config.custom.faviconsPathSegment}/${hostname}.png`,
image,
'image/png',
);
} catch (error) {
/* empty */
}
},
};
@@ -0,0 +1,19 @@
/*!
* Copyright (c) 2024 PLANKA Software GmbH
* Licensed under the Fair Use License: https://github.com/plankanban/planka/blob/master/LICENSE.md
*/
module.exports = {
sync: true,
fn() {
const prefix = sails.helpers.utils.generateRandomString(8);
const secret = sails.helpers.utils.generateRandomString(32);
const key = `${prefix}_${secret}`;
return {
key,
prefix,
};
},
};
@@ -0,0 +1,22 @@
/*!
* Copyright (c) 2024 PLANKA Software GmbH
* Licensed under the Fair Use License: https://github.com/plankanban/planka/blob/master/LICENSE.md
*/
module.exports = {
inputs: {
total: {
type: 'number',
required: true,
},
},
async fn(inputs) {
const queryResult = await sails.sendNativeQuery(
'SELECT next_id() as id from generate_series(1, $1) ORDER BY id',
[inputs.total],
);
return sails.helpers.utils.mapRecords(queryResult.rows);
},
};
@@ -0,0 +1,30 @@
/*!
* Copyright (c) 2024 PLANKA Software GmbH
* Licensed under the Fair Use License: https://github.com/plankanban/planka/blob/master/LICENSE.md
*/
const crypto = require('crypto');
const CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
module.exports = {
sync: true,
inputs: {
size: {
type: 'number',
required: true,
},
},
fn(inputs) {
const bytes = crypto.randomBytes(inputs.size);
let result = '';
for (let i = 0; i < inputs.size; i += 1) {
result += CHARS[bytes[i] % 62];
}
return result;
},
};
@@ -0,0 +1,20 @@
/*!
* Copyright (c) 2024 PLANKA Software GmbH
* Licensed under the Fair Use License: https://github.com/plankanban/planka/blob/master/LICENSE.md
*/
const bytes = require('bytes');
module.exports = {
async fn() {
let { storageLimit } = await InternalConfig.qm.getOneMain();
storageLimit = bytes(storageLimit);
if (storageLimit === null) {
return null;
}
const storageUsage = await StorageUsage.qm.getOneMain();
return BigInt(storageLimit) - BigInt(storageUsage.total);
},
};
+21
View File
@@ -0,0 +1,21 @@
/*!
* Copyright (c) 2024 PLANKA Software GmbH
* Licensed under the Fair Use License: https://github.com/plankanban/planka/blob/master/LICENSE.md
*/
const crypto = require('crypto');
module.exports = {
sync: true,
inputs: {
data: {
type: 'ref',
required: true,
},
},
fn(inputs) {
return crypto.createHash('sha256').update(inputs.data).digest('hex');
},
};
+130
View File
@@ -0,0 +1,130 @@
/*!
* Copyright (c) 2024 PLANKA Software GmbH
* Licensed under the Fair Use License: https://github.com/plankanban/planka/blob/master/LICENSE.md
*/
const GAP = 2 ** 14;
const MIN_GAP = 0.125;
const MAX_POSITION = 2 ** 50;
const findBeginnings = (positions) => {
positions.unshift(0);
let prevPosition = positions.pop();
const beginnings = [prevPosition];
// eslint-disable-next-line consistent-return
_.forEachRight(positions, (position) => {
if (prevPosition - MIN_GAP >= position) {
return false;
}
prevPosition = position;
beginnings.unshift(prevPosition);
});
return beginnings;
};
const getRepositionsMap = (positions) => {
const repositionsMap = {};
if (positions.length <= 1) {
if (!_.isUndefined(positions[0]) && positions[0] > MAX_POSITION) {
return null;
}
return repositionsMap;
}
let prevPosition = positions.shift();
for (let i = 0; i < positions.length; i += 1) {
const position = positions[i];
const nextPosition = positions[i + 1];
if (prevPosition + MIN_GAP <= position) {
break;
}
if (!_.isUndefined(nextPosition) && prevPosition + MIN_GAP * 2 <= nextPosition) {
(repositionsMap[position] || (repositionsMap[position] = [])).push(
prevPosition + (nextPosition - prevPosition) / 2,
);
break;
}
prevPosition += GAP;
if (prevPosition > MAX_POSITION) {
return null;
}
(repositionsMap[position] || (repositionsMap[position] = [])).push(prevPosition);
}
return repositionsMap;
};
const getFullRepositionsMap = (positions) => {
const repositionsMap = {};
_.forEach(positions, (position, index) => {
(repositionsMap[position] || (repositionsMap[position] = [])).push(GAP * (index + 1));
});
return repositionsMap;
};
module.exports = {
sync: true,
inputs: {
position: {
type: 'number',
required: true,
},
records: {
type: 'ref',
required: true,
},
},
fn(inputs) {
const lowers = [];
const uppers = [];
inputs.records.forEach(({ position }) => {
(position <= inputs.position ? lowers : uppers).push(position);
});
const beginnings = findBeginnings([...lowers, inputs.position]);
const repositionsMap =
getRepositionsMap([...beginnings, ...uppers]) ||
getFullRepositionsMap([...lowers, inputs.position, ...uppers]);
const position = repositionsMap[inputs.position]
? repositionsMap[inputs.position].pop()
: inputs.position;
const repositions = [];
_.forEachRight(inputs.records, (record) => {
if (_.isEmpty(repositionsMap[record.position])) {
return;
}
repositions.unshift({
record,
position: repositionsMap[record.position].pop(),
});
});
return {
position,
repositions,
};
},
};
@@ -0,0 +1,30 @@
/*!
* Copyright (c) 2024 PLANKA Software GmbH
* Licensed under the Fair Use License: https://github.com/plankanban/planka/blob/master/LICENSE.md
*/
const fs = require('fs');
const path = require('path');
const PRELOADED_FAVICON_FILENAMES = fs
.readdirSync(path.join(sails.config.paths.public, 'preloaded-favicons'))
.filter((filename) => filename.endsWith('.png'));
const PRELOADED_FAVICON_HOSTNAMES_SET = new Set(
PRELOADED_FAVICON_FILENAMES.map((faviconFilename) => faviconFilename.slice(0, -4)),
);
module.exports = {
sync: true,
inputs: {
hostname: {
type: 'string',
required: true,
},
},
fn(inputs) {
return PRELOADED_FAVICON_HOSTNAMES_SET.has(inputs.hostname);
},
};
@@ -0,0 +1,70 @@
/*!
* Copyright (c) 2024 PLANKA Software GmbH
* Licensed under the Fair Use License: https://github.com/plankanban/planka/blob/master/LICENSE.md
*/
const nodemailer = require('nodemailer');
module.exports = {
inputs: {
defaultOptions: {
type: 'json',
},
},
async fn(inputs) {
let config;
let sourceConfig;
if (sails.config.custom.smtpHost) {
sourceConfig = sails.config.custom;
} else {
config = await Config.qm.getOneMain();
if (config.smtpHost) {
sourceConfig = config;
// TODO: hack to make it work with proxy
if (sourceConfig.smtpPort === null) {
sourceConfig.smtpPort = sourceConfig.smtpSecure ? 465 : 587;
}
}
}
if (!sourceConfig) {
return {
config,
transporter: null,
};
}
const transporter = nodemailer.createTransport(
{
...inputs.defaultOptions,
host: sourceConfig.smtpHost,
port: sourceConfig.smtpPort,
name: sourceConfig.smtpName,
secure: sourceConfig.smtpSecure,
auth: sourceConfig.smtpUser && {
user: sourceConfig.smtpUser,
pass: sourceConfig.smtpPassword,
},
tls: {
rejectUnauthorized: sourceConfig.smtpTlsRejectUnauthorized,
},
proxy:
sails.config.custom.outgoingProxy && !sails.config.custom.smtpHost
? sails.config.custom.outgoingProxy
: undefined,
},
{
from: sourceConfig.smtpFrom,
},
);
return {
transporter,
config,
};
},
};
@@ -0,0 +1,37 @@
/*!
* Copyright (c) 2024 PLANKA Software GmbH
* Licensed under the Fair Use License: https://github.com/plankanban/planka/blob/master/LICENSE.md
*/
const path = require('path');
const I18n = require('i18n-2');
module.exports = {
sync: true,
inputs: {
language: {
type: 'string',
allowNull: true,
},
},
fn(inputs) {
const i18n = new I18n({
locales: sails.config.i18n.locales,
defaultLocale: sails.config.i18n.defaultLocale,
directory: path.join(sails.config.appPath, sails.config.i18n.localesDirectory),
extension: '.json',
devMode: false,
});
i18n.setLocale(inputs.language || sails.config.i18n.defaultLocale);
/* eslint-disable no-underscore-dangle */
const translator = i18n.__.bind(i18n);
translator.n = i18n.__n.bind(i18n);
/* eslint-enable no-underscore-dangle */
return translator;
},
};
@@ -0,0 +1,41 @@
/*!
* Copyright (c) 2024 PLANKA Software GmbH
* Licensed under the Fair Use License: https://github.com/plankanban/planka/blob/master/LICENSE.md
*/
module.exports = {
sync: true,
inputs: {
records: {
type: 'ref',
required: true,
},
attribute: {
type: 'string',
defaultsTo: 'id',
},
unique: {
type: 'boolean',
defaultsTo: false,
},
withoutNull: {
type: 'boolean',
defaultsTo: false,
},
},
fn(inputs) {
let result = _.map(inputs.records, inputs.attribute);
if (inputs.unique) {
result = _.uniq(result);
}
if (inputs.withoutNull) {
result = _.without(result, null);
}
return result;
},
};
@@ -0,0 +1,59 @@
/*!
* Copyright (c) 2024 PLANKA Software GmbH
* Licensed under the Fair Use License: https://github.com/plankanban/planka/blob/master/LICENSE.md
*/
const util = require('util');
module.exports = {
inputs: {
file: {
type: 'ref',
required: true,
},
enforceStorageLimit: {
type: 'boolean',
defaultsTo: true,
},
},
async fn(inputs, exits) {
const { maxUploadFileSize } = sails.config.custom;
let availableStorage = null;
if (inputs.enforceStorageLimit) {
availableStorage = await sails.helpers.utils.getAvailableStorage();
}
let maxBytes = maxUploadFileSize;
if (availableStorage !== null) {
if (maxBytes) {
maxBytes = availableStorage < maxBytes ? availableStorage : maxBytes;
} else {
maxBytes = availableStorage;
}
}
const upload = util.promisify((options, callback) =>
inputs.file.upload(options, (error, files) => {
if (
error &&
error.code === 'E_EXCEEDS_UPLOAD_LIMIT' &&
availableStorage !== null &&
(maxUploadFileSize === null || error.maxBytes < maxUploadFileSize)
) {
return callback(new Error('Storage limit reached'), files);
}
return callback(error, files);
}),
);
return exits.success(
await upload({
maxBytes,
dirname: sails.config.custom.uploadsTempPath,
}),
);
},
};
@@ -0,0 +1,41 @@
/*!
* Copyright (c) 2024 PLANKA Software GmbH
* Licensed under the Fair Use License: https://github.com/plankanban/planka/blob/master/LICENSE.md
*/
const { Types } = require('../../models/UploadedFile');
const PATH_SEGMENT_BY_TYPE = {
[Types.USER_AVATAR]: sails.config.custom.userAvatarsPathSegment,
[Types.BACKGROUND_IMAGE]: sails.config.custom.backgroundImagesPathSegment,
[Types.ATTACHMENT]: sails.config.custom.attachmentsPathSegment,
};
module.exports = {
sync: true,
inputs: {
uploadedFileOrUploadedFiles: {
type: 'ref',
required: true,
},
},
fn(inputs) {
const uploadedFiles = _.isPlainObject(inputs.uploadedFileOrUploadedFiles)
? [inputs.uploadedFileOrUploadedFiles]
: inputs.uploadedFileOrUploadedFiles;
const fileManager = sails.hooks['file-manager'].getInstance();
// TODO: optimize?
uploadedFiles.forEach(async (uploadedFile) => {
if (uploadedFile.referencesTotal !== null) {
return;
}
await fileManager.deleteDir(`${PATH_SEGMENT_BY_TYPE[uploadedFile.type]}/${uploadedFile.id}`);
await UploadedFile.qm.deleteOne(uploadedFile.id);
});
},
};
@@ -0,0 +1,35 @@
/*!
* Copyright (c) 2024 PLANKA Software GmbH
* Licensed under the Fair Use License: https://github.com/plankanban/planka/blob/master/LICENSE.md
*/
module.exports = {
inputs: {
transporter: {
type: 'ref',
required: true,
},
to: {
type: 'string',
required: true,
},
subject: {
type: 'string',
required: true,
},
html: {
type: 'string',
required: true,
},
},
async fn(inputs) {
try {
const info = await inputs.transporter.sendMail(inputs);
sails.log.info(`Email sent: ${info.messageId}`);
} catch (error) {
sails.log.error(`Error sending email: ${error}`);
}
},
};
@@ -0,0 +1,54 @@
/*!
* Copyright (c) 2024 PLANKA Software GmbH
* Licensed under the Fair Use License: https://github.com/plankanban/planka/blob/master/LICENSE.md
*/
const { execFile } = require('child_process');
const path = require('path');
const util = require('util');
const PYTHON_PATH =
process.platform === 'win32'
? path.join(sails.config.appPath, '.venv', 'Scripts', 'python.exe')
: path.join(sails.config.appPath, '.venv', 'bin', 'python');
const promisifyExecFile = util.promisify(execFile);
module.exports = {
inputs: {
services: {
type: 'json',
required: true,
},
title: {
type: 'string',
required: true,
},
bodyByFormat: {
type: 'json',
required: true,
},
},
async fn(inputs) {
try {
await promisifyExecFile(
PYTHON_PATH,
[
path.join(sails.config.appPath, 'utils', 'send_notifications.py'),
JSON.stringify(inputs.services),
inputs.title,
JSON.stringify(inputs.bodyByFormat),
],
{
env: {
HTTP_PROXY: sails.config.custom.outgoingProxy,
HTTPS_PROXY: sails.config.custom.outgoingProxy,
},
},
);
} catch (error) {
sails.log.error(`Error sending notifications:\n${error.stderr || error.message}`);
}
},
};
@@ -0,0 +1,143 @@
/*!
* Copyright (c) 2024 PLANKA Software GmbH
* Licensed under the Fair Use License: https://github.com/plankanban/planka/blob/master/LICENSE.md
*/
const { ProxyAgent } = require('undici');
const Webhook = require('../../models/Webhook');
/**
* @typedef {Object} Included
* @property {any[]} [users] - Array of users (optional).
* @property {any[]} [projects] - Array of projects (optional).
* @property {any[]} [baseCustomFieldGroups] - Array of base custom field groups (optional).
* @property {any[]} [boards] - Array of boards (optional).
* @property {any[]} [boardMemberships] - Array of board memberships (optional).
* @property {any[]} [labels] - Array of labels (optional).
* @property {any[]} [lists] - Array of lists (optional).
* @property {any[]} [cards] - Array of cards (optional).
* @property {any[]} [cardMemberships] - Array of card memberships (optional).
* @property {any[]} [taskLists] - Array of task lists (optional).
* @property {any[]} [customFieldGroups] - Array of custom field groups (optional).
* @property {any[]} [customFields] - Array of custom fields (optional).
* @property {any[]} [comments] - Array of comments (optional).
* @property {any[]} [actions] - Array of actions (optional).
*/
/**
* @typedef {Object} Data
* @property {any} item - Actual event data.
* @property {Included} [included] - Optional included data.
*/
/**
* Sends a webhook notification to a configured URL.
*
* @param {*} webhook - Webhook configuration.
* @param {string} event - The event.
* @param {Data} data - The data object containing event data and optionally included data.
* @param {Data} [prevData] - The data object containing previous state of data (optional).
* @param {ref} user - User object associated with the event.
* @returns {Promise<void>}
*/
async function sendWebhook(webhook, event, data, prevData, user) {
const headers = {
'Content-Type': 'application/json',
'User-Agent': `planka (+${sails.config.custom.baseUrl})`,
};
if (webhook.accessToken) {
headers.Authorization = `Bearer ${webhook.accessToken}`;
}
const body = JSON.stringify({
event,
data,
prevData,
user,
});
try {
const response = await fetch(webhook.url, {
headers,
body,
method: 'POST',
dispatcher: sails.config.custom.outgoingProxy
? new ProxyAgent(sails.config.custom.outgoingProxy)
: undefined,
});
if (!response.ok) {
const message = await response.text();
sails.log.error(
`Webhook ${webhook.name} failed with status ${response.status} and message: ${message}`,
);
}
} catch (error) {
sails.log.error(`Webhook ${webhook.name} failed with error: ${error}`);
}
}
module.exports = {
sync: true,
inputs: {
webhooks: {
type: 'ref',
required: true,
},
event: {
type: 'string',
required: true,
isIn: Object.values(Webhook.Events),
},
buildData: {
type: 'ref',
required: true,
},
buildPrevData: {
type: 'ref',
},
user: {
type: 'ref',
required: true,
},
},
fn(inputs) {
const webhooks = inputs.webhooks.filter((webhook) => {
if (!webhook.url) {
return false;
}
if (webhook.excludedEvents && webhook.excludedEvents.includes(inputs.event)) {
return false;
}
if (webhook.events && !webhook.events.includes(inputs.event)) {
return false;
}
return true;
});
if (webhooks.length === 0) {
return;
}
const data = inputs.buildData();
const prevData = inputs.buildPrevData && inputs.buildPrevData();
webhooks.forEach((webhook) => {
sendWebhook(
webhook,
inputs.event,
data,
prevData,
sails.helpers.users.presentOne(inputs.user),
);
});
},
};
@@ -0,0 +1,33 @@
/*!
* Copyright (c) 2024 PLANKA Software GmbH
* Licensed under the Fair Use License: https://github.com/plankanban/planka/blob/master/LICENSE.md
*/
module.exports = {
sync: true,
inputs: {
value: {
type: 'string',
required: true,
},
accessTokenPayload: {
type: 'json',
required: true,
},
response: {
type: 'ref',
required: true,
},
},
fn(inputs) {
inputs.response.cookie('httpOnlyToken', inputs.value, {
expires: new Date(inputs.accessTokenPayload.exp * 1000),
path: sails.config.custom.baseUrlPath || '/',
secure: sails.config.custom.baseUrlSecure,
httpOnly: true,
sameSite: 'strict',
});
},
};
@@ -0,0 +1,35 @@
/*!
* Copyright (c) 2024 PLANKA Software GmbH
* Licensed under the Fair Use License: https://github.com/plankanban/planka/blob/master/LICENSE.md
*/
const jwt = require('jsonwebtoken');
module.exports = {
sync: true,
inputs: {
token: {
type: 'string',
required: true,
},
},
exits: {
invalidToken: {},
},
fn(inputs) {
let payload;
try {
payload = jwt.verify(inputs.token, sails.config.session.secret);
} catch (error) {
throw { invalidToken: error };
}
return {
subject: payload.sub,
issuedAt: new Date(payload.iat * 1000),
};
},
};