Files
wekan/server/notifications/outgoing.js
T
Lauri Ojansivu 5b83e8e256 Webhooks send the username too, and TODO Later loses three settled entries.
An audit of the TODO Later backlog against the open issues and the current
source. Three no longer belong there.

#3113 - an outgoing webhook said who did something by DISPLAY name and had no
field for the login name. params.user comes from getActivityUserName(), which
prefers getName() because the same params feed the e-mail notification text,
where "Lauri Ojansivu commented on ..." is what a person wants to read; a webhook
consumer needs the identifier, received "Lauri Ojansivu" where it needed "xet7",
and matching users by display name is wrong the moment two people share one.
Changing what `user` means would break every consumer already reading it, which
is what left this recorded as needing a maintainer decision. It needs none: the
username travels as its OWN field. `user` is untouched, `username` is beside it
in the default WEBHOOKS_ATTRIBUTES list, and a deployment that pinned its own
list still gets exactly the fields it asked for.

#6542 - "Import finished. Users imported: 60, but only 25 are listed". The Admin
Panel People pane paginates and passes its total to the shared table page
(totalLabelKey: 'people-number'), so the 60 the importer reported is on screen
next to the 25 rows of the current page. That is what the report was about, and
it is already true in this source.

#6500 - Docker `latest` not loading in a browser: already closed upstream, so it
was only sitting in the backlog.

The rest of the backlog stays, each with its reason: they need an SMTP server, an
LDAP directory, a container, a browser to drag in, or a maintainer's decision on
an intended contract - none of which a source reading can settle.

tests/webhookUsername.test.cjs pins both halves of the webhook change: that the
username is there and set from the same user document as the display name, and
that `user` still means what it always did, including the notification text that
depends on it. Three of its seven assertions fail on the previous commit.

Thanks to xet7 !

Fixes #3113,
Fixes #6542.
2026-08-08 02:50:15 +03:00

241 lines
7.7 KiB
JavaScript

import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';
import { ReactiveCache } from '/imports/reactiveCache';
import { TAPi18n } from '/imports/i18n';
import { fetchSafe } from '/server/lib/ssrfGuard';
import CardComments from '/models/cardComments';
import Integrations from '/models/integrations';
const Lock = {
_lock: {},
_timer: {},
echoDelay: 500, // echo should be happening much faster
normalDelay: 1e3, // normally user typed comment will be much slower
ECHO: 2,
NORMAL: 1,
NULL: 0,
has(id, value) {
const existing = this._lock[id];
let ret = this.NULL;
if (existing) {
ret = existing === value ? this.ECHO : this.NORMAL;
}
return ret;
},
clear(id, delay) {
const previous = this._timer[id];
if (previous) {
Meteor.clearTimeout(previous);
}
this._timer[id] = Meteor.setTimeout(() => this.unset(id), delay);
},
set(id, value) {
const state = this.has(id, value);
let delay = this.normalDelay;
if (state === this.ECHO) {
delay = this.echoDelay;
}
if (!value) {
// user commented, we set a lock
value = 1;
}
this._lock[id] = value;
this.clear(id, delay); // always auto reset the locker after delay
},
unset(id) {
delete this._lock[id];
},
};
const webhooksAtbts = (process.env.WEBHOOKS_ATTRIBUTES &&
process.env.WEBHOOKS_ATTRIBUTES.split(',')) || [
'cardId',
'listId',
'oldListId',
'boardId',
'comment',
'user',
// #3113: the display name (`user`) and the login name, both. WEBHOOKS_ATTRIBUTES
// overrides this list wholesale, so a deployment that already sets it keeps
// exactly the fields it asked for.
'username',
'card',
'commentId',
'swimlaneId',
'customField',
'customFieldValue',
'labelId',
'label',
'attachmentId',
];
const responseFunc = async (data, integration) => {
const paramCommentId = data.commentId;
const paramCardId = data.cardId;
const paramBoardId = data.boardId;
const newComment = data.comment;
// Authorization: Verify the request is from a bidirectional webhook
if (!integration || integration.type !== Integrations.Const.TWOWAY) {
return; // Only bidirectional webhooks can update comments
}
// Authorization: Prevent cross-board comment injection
if (paramBoardId !== integration.boardId) {
return; // Webhook can only modify comments in its own board
}
if (paramCardId && paramBoardId && newComment && paramCommentId) {
// only process data with the commentId, cardId, boardId and comment text
const comment = await ReactiveCache.getCardComment({
_id: paramCommentId,
cardId: paramCardId,
boardId: paramBoardId,
});
const board = await ReactiveCache.getBoard(paramBoardId);
const card = await ReactiveCache.getCard(paramCardId);
if (board && card && comment) {
// Only update existing comments - do not create new comments from webhook responses
Lock.set(comment._id, newComment);
await CardComments.direct.updateAsync(comment._id, {
$set: {
text: newComment,
},
});
}
}
};
Meteor.methods({
async outgoingWebhooks(integration, description, params) {
if (this.userId) {
check(integration, Object);
check(description, String);
check(params, Object);
this.unblock();
// label activity did not work yet, see wekan/models/activities.js
const quoteParams = { ...params };
const clonedParams = { ...params };
[
'card',
'list',
'oldList',
'board',
'oldBoard',
'comment',
'checklist',
'swimlane',
'oldSwimlane',
'labelId',
'label',
'attachment',
'attachmentId',
].forEach(key => {
if (quoteParams[key]) quoteParams[key] = `"${params[key]}"`;
});
const userId = params.userId || integration.userId || this.userId;
const user = await ReactiveCache.getUser(userId);
if (!user || typeof user.getLanguage !== 'function') {
return;
}
// #5875: load the recipient's language bundle on the server before
// translating, otherwise it falls back to English.
await TAPi18n.ensureLanguageLoaded(user.getLanguage());
const descriptionText = TAPi18n.__(
description,
quoteParams,
user.getLanguage(),
);
// If you don't want a hook, set the webhook description to "-".
if (descriptionText === "-") return;
const text = `${params.user} ${descriptionText}\n${params.url}`;
if (text.length === 0) return;
const value = {
text: `${text}`,
};
webhooksAtbts.forEach(key => {
if (params[key]) value[key] = params[key];
});
value.description = description;
//integrations.forEach(integration => {
const is2way = integration.type === Integrations.Const.TWOWAY;
const token = integration.token || '';
const fetchHeaders = {
'Content-Type': 'application/json',
};
if (token) fetchHeaders['X-Wekan-Token'] = token;
// The `integration` object is supplied by the caller and must not be
// trusted: verify a matching integration actually exists on its board
// AND that the caller is a member of that board. Otherwise any
// authenticated user could drive webhooks (and, via the two-way
// response path below, overwrite comments) on boards they cannot access.
const storedIntegration = await ReactiveCache.getIntegration({
url: integration.url,
boardId: integration.boardId,
});
if (!storedIntegration) return;
const integrationBoard = await ReactiveCache.getBoard(storedIntegration.boardId);
if (!integrationBoard || !integrationBoard.hasMember(this.userId)) return;
const url = integration.url;
if (is2way) {
const cid = params.commentId;
const comment = params.comment;
const lockState = cid && Lock.has(cid, comment);
if (cid && lockState !== Lock.NULL) {
// it's a comment and there is a previous lock
return;
} else if (cid) {
Lock.set(cid, comment); // set a lock here
}
}
// fetchSafe resolves DNS once, pins the connection to the resolved IP,
// and blocks redirects — fully preventing DNS-rebinding SSRF attacks.
let response;
try {
response = await fetchSafe(url, {
method: 'POST',
headers: fetchHeaders,
body: JSON.stringify(is2way ? { description, ...clonedParams } : value),
});
} catch (err) {
throw new Meteor.Error(
'invalid-webhook-url',
`Webhook request failed: ${err.message}`,
);
}
if (response && response.status >= 200 && response.status < 300) {
if (is2way) {
// Only act on a JSON-encoded response body
let data = null;
try {
data = await response.json();
} catch {
data = null;
}
if (data) {
try {
await responseFunc(data, integration);
} catch (e) {
throw new Meteor.Error('error-process-data');
}
}
}
return response; // eslint-disable-line consistent-return
} else {
throw new Meteor.Error('error-invalid-webhook-response');
}
}
},
});