Node.js based forum software built for the modern web
feat: don't display tokens on /admin/api page
Barış Soner Uşaklıb7e5d85cc88f
diff --git a/public/language/en-GB/admin/settings/api.json b/public/language/en-GB/admin/settings/api.jsonindex 5a8eef2102..951ea15fa3 100644--- a/public/language/en-GB/admin/settings/api.json+++ b/public/language/en-GB/admin/settings/api.json@@ -26,5 +26,10 @@"roll": "Roll","delete-confirm": "Are you sure you wish to delete this token? It will not be recoverable.",- "roll-confirm": "Are you sure you wish to regenerate this token? The old token will be immediately revoked and will not be recoverable."+ "roll-confirm": "Are you sure you wish to regenerate this token? The old token will be immediately revoked and will not be recoverable.",+ "token-once-title": "Copy Token Now",+ "token-once-warning": "This token will only be shown once. Store it securely before closing this dialog.",+ "copy-token": "Copy",+ "token-copied": "Token copied to clipboard.",+ "token-copy-failed": "Unable to copy token. Please copy it manually."}\ No newline at end of filediff --git a/public/src/admin/manage/api.js b/public/src/admin/manage/api.jsindex 7c23f726f2..75a86d5fdf 100644--- a/public/src/admin/manage/api.js+++ b/public/src/admin/manage/api.js@@ -1,6 +1,8 @@'use strict';-define('admin/manage/api', ['settings', 'clipboard', 'modals', 'benchpress', 'api', 'alerts'], function (settings, clipboard, modals, Benchpress, api, alerts) {+define('admin/manage/api', [+ 'settings', 'clipboard', 'modals', 'benchpress', 'api', 'alerts', 'utils', 'helpers',+], function (settings, clipboard, modals, Benchpress, api, alerts, utils, helpers) {const ACP = {};ACP.init = function () {@@ -9,15 +11,54 @@ define('admin/manage/api', ['settings', 'clipboard', 'modals', 'benchpress', 'apsettings.save('core.api', $('.core-api-settings'));});- // Click to copy- const copyEls = document.querySelectorAll('[data-component="acp/tokens"] [data-action="copy"]');- new clipboard(copyEls);-$('[data-action="create"]').on('click', handleTokenCreation);handleActions();};+ function normalizeTokenForTable(tokenObj) {+ const tokenValue = tokenObj.secret || tokenObj.token || '';+ return {+ ...tokenObj,+ tokenId: tokenObj.tokenId || tokenObj.token,+ tokenMasked: tokenObj.tokenMasked || utils.maskToken(tokenValue),+ };+ }++ async function revealTokenOnce(token) {+ if (!token) {+ return;+ }++ const modal = await modals.dialog({+ title: '[[admin/settings/api:token-once-title]]',+ message: `+ <p class="text-danger fw-semibold mb-2">[[admin/settings/api:token-once-warning]]</p>+ <div class="input-group">+ <input type="text" class="form-control user-select-all" readonly data-component="token-secret" value="${helpers.escape(token)}" />+ <button type="button" class="btn btn-ghost border" data-action="copy" data-clipboard-text="${helpers.escape(token)}">[[admin/settings/api:copy-token]]</button>+ </div>+ `,+ buttons: {+ ok: {+ label: '[[modules:bootbox.ok]]',+ className: 'btn-primary',+ },+ },+ });+ modal.on('shown.bs.modal', () => {+ const clip = new clipboard(modal.find('[data-action="copy"]').get(0), {+ container: modal.get(0),+ });+ clip.on('success', () => {+ alerts.success('[[admin/settings/api:token-copied]]');+ });+ clip.on('error', () => {+ alerts.error('[[admin/settings/api:token-copy-failed]]');+ });+ });+ }+function handleActions() {const formEl = document.querySelector('#content form');if (!formEl) {@@ -76,19 +117,25 @@ define('admin/manage/api', ['settings', 'clipboard', 'modals', 'benchpress', 'apdescription,...(isMasterToken ? { password } : {}),});+ const secret = tokenObj.secret;+ const tableObj = normalizeTokenForTable(tokenObj);+ delete tableObj.token;+ delete tableObj.secret;if (!tokensTableBody) {modal.modal('hide');+ await revealTokenOnce(secret);return ajaxify.refresh();}- ajaxify.data.tokens.push(tokenObj);+ ajaxify.data.tokens.push(tableObj);const rowEl = (await app.parseAndTranslate(ajaxify.data.template.name, 'tokens', {- tokens: [tokenObj],+ tokens: [tableObj],})).get(0);tokensTableBody.append(rowEl);$(rowEl).find('.timeago').timeago();modal.modal('hide');+ await revealTokenOnce(secret);} catch (e) {alerts.error(e);}@@ -125,8 +172,11 @@ define('admin/manage/api', ['settings', 'clipboard', 'modals', 'benchpress', 'aptry {const tokenObj = await api.put(`/admin/tokens/${token}`, { uid, description });+ const tableObj = normalizeTokenForTable(tokenObj);+ delete tableObj.token;+ delete tableObj.secret;const newEl = (await app.parseAndTranslate(ajaxify.data.template.name, 'tokens', {- tokens: [tokenObj],+ tokens: [tableObj],})).get(0);rowEl.replaceWith(newEl);@@ -179,12 +229,17 @@ define('admin/manage/api', ['settings', 'clipboard', 'modals', 'benchpress', 'apif (ok) {try {const tokenObj = await api.post(`/admin/tokens/${token}/roll`);+ const secret = tokenObj.secret;+ const tableObj = normalizeTokenForTable(tokenObj);+ delete tableObj.token;+ delete tableObj.secret;const newEl = (await app.parseAndTranslate(ajaxify.data.template.name, 'tokens', {- tokens: [tokenObj],+ tokens: [tableObj],})).get(0);rowEl.replaceWith(newEl);$(newEl).find('.timeago').timeago();+ await revealTokenOnce(secret);} catch (e) {alerts.error(e);}diff --git a/public/src/utils.common.js b/public/src/utils.common.jsindex fb9232f82a..a7d55d66b5 100644--- a/public/src/utils.common.js+++ b/public/src/utils.common.js@@ -723,6 +723,15 @@ const utils = {return str.replace(/\s+$/g, '');},+ maskToken: function (token) {+ token = String(token || '');+ if (!token) {+ return '';+ }++ return `${token.slice(0, 4)}...${token.slice(-4)}`;+ },+debounce: function (func, wait, immediate) {// modified from https://davidwalsh.name/javascript-debounce-functionlet timeout;diff --git a/src/api/utils.js b/src/api/utils.jsindex 0426b90d87..f8c9d85a39 100644--- a/src/api/utils.js+++ b/src/api/utils.js@@ -1,5 +1,6 @@'use strict';+const crypto = require('crypto');const db = require('../database');const user = require('../user');@@ -10,6 +11,32 @@ const utils = module.exports;// internal token management utilities onlyutils.tokens = {};+utils.tokens.fingerprint = token => crypto.createHash('sha256').update(token).digest('hex');++utils.tokens.resolveIdentifier = async (identifier) => {+ identifier = String(identifier || '').trim();+ if (!identifier) {+ throw new Error('[[error:invalid-data]]');+ }++ if (/^[a-f0-9]{64}$/i.test(identifier)) {+ const normalizedIdentifier = identifier.toLowerCase();+ const tokens = await db.getSortedSetRange('tokens:createtime', 0, -1);+ const token = tokens.find(t => utils.tokens.fingerprint(t) === normalizedIdentifier);+ if (!token) {+ throw new Error('[[error:invalid-data]]');+ }++ return token;+ }++ if (await db.exists(`token:${identifier}`)) {+ return identifier;+ }++ throw new Error('[[error:invalid-data]]');+};+utils.tokens.list = async (start = 0, stop = -1) => {// Validation handled at higher levelconst tokens = await db.getSortedSetRange(`tokens:createtime`, start, stop);diff --git a/src/controllers/admin/api.js b/src/controllers/admin/api.jsindex 24de2df15b..d3f28bc4cd 100644--- a/src/controllers/admin/api.js+++ b/src/controllers/admin/api.js@@ -2,6 +2,7 @@const api = require('../../api');const pagination = require('../../pagination');+const utils = require('../../utils');const controller = module.exports;@@ -14,10 +15,18 @@ controller.get = async (req, res) => {api.utils.tokens.list(start, stop),api.utils.tokens.count(),]);+ const acpTokens = tokens.filter(Boolean).map((tokenObj) => {+ const { token, ...rest } = tokenObj;+ return {+ ...rest,+ tokenId: api.utils.tokens.fingerprint(token),+ tokenMasked: utils.maskToken(token),+ };+ });const pageCount = Math.ceil(count / resultsPerPage);res.render('admin/manage/api', {title: '[[admin/menu:settings/api]]',- tokens,+ tokens: acpTokens,pagination: pagination.create(page, pageCount, req.query),});};\ No newline at end of filediff --git a/src/controllers/write/admin.js b/src/controllers/write/admin.jsindex fefe54a691..08965a2304 100644--- a/src/controllers/write/admin.js+++ b/src/controllers/write/admin.js@@ -10,6 +10,25 @@ const utils = require('../../utils');const Admin = module.exports;+function formatTokenForAdmin(tokenObj, { includeSecret = false } = {}) {+ if (!tokenObj) {+ return null;+ }++ const { token, ...rest } = tokenObj;+ const payload = {+ ...rest,+ tokenId: api.utils.tokens.fingerprint(token),+ tokenMasked: utils.maskToken(token),+ };++ if (includeSecret) {+ payload.secret = token;+ }++ return payload;+}+Admin.updateSetting = async (req, res) => {await api.admin.updateSetting(req, {setting: req.params.setting,@@ -38,6 +57,7 @@ Admin.generateToken = async (req, res) => {const uid = String(req.body.uid).trim();const { description } = req.body;const token = await api.utils.tokens.generate({ uid, description });+ const tokenObj = await api.utils.tokens.get(token);await events.log({type: 'token-add',uid: req.uid,@@ -45,29 +65,34 @@ Admin.generateToken = async (req, res) => {_tokenUid: uid,description,});- helpers.formatApiResponse(200, res, await api.utils.tokens.get(token));+ helpers.formatApiResponse(200, res, formatTokenForAdmin(tokenObj, { includeSecret: true }));};Admin.getToken = async (req, res) => {- helpers.formatApiResponse(200, res, await api.utils.tokens.get(req.params.token));+ const token = await api.utils.tokens.resolveIdentifier(req.params.token);+ const tokenObj = await api.utils.tokens.get(token);+ helpers.formatApiResponse(200, res, tokenObj ? {+ uid: tokenObj.uid,+ description: tokenObj.description,+ } : null);};Admin.updateToken = async (req, res) => {const { uid, description } = req.body;- const { token } = req.params;+ const token = await api.utils.tokens.resolveIdentifier(req.params.token);- helpers.formatApiResponse(200, res, await api.utils.tokens.update(token, { uid, description }));+ helpers.formatApiResponse(200, res, formatTokenForAdmin(await api.utils.tokens.update(token, { uid, description })));};Admin.rollToken = async (req, res) => {- let { token } = req.params;-- token = await api.utils.tokens.roll(token);- helpers.formatApiResponse(200, res, await api.utils.tokens.get(token));+ const token = await api.utils.tokens.resolveIdentifier(req.params.token);+ const newToken = await api.utils.tokens.roll(token);+ const tokenObj = await api.utils.tokens.get(newToken);+ helpers.formatApiResponse(200, res, formatTokenForAdmin(tokenObj, { includeSecret: true }));};Admin.deleteToken = async (req, res) => {- const { token } = req.params;+ const token = await api.utils.tokens.resolveIdentifier(req.params.token);await api.utils.tokens.delete(token);await events.log({type: 'token-delete',diff --git a/src/routes/admin.js b/src/routes/admin.jsindex 77af0b1b86..3e7b5d6f82 100644--- a/src/routes/admin.js+++ b/src/routes/admin.js@@ -32,7 +32,7 @@ module.exports = function (app, name, middleware, controllers) {helpers.setupAdminPageRoute(app, `/${name}/manage/uploads`, middlewares, controllers.admin.uploads.get);helpers.setupAdminPageRoute(app, `/${name}/manage/digest`, middlewares, controllers.admin.digest.get);- helpers.setupAdminPageRoute(app, `/${name}/manage/api`, [...middlewares, middleware.requirePageReAuth()], controllers.admin.api.get);+ helpers.setupAdminPageRoute(app, `/${name}/manage/api`, middlewares, controllers.admin.api.get);helpers.setupAdminPageRoute(app, `/${name}/settings/general`, middlewares, controllers.admin.settings.general);helpers.setupAdminPageRoute(app, `/${name}/settings/navigation`, middlewares, controllers.admin.settings.navigation);diff --git a/src/views/admin/manage/api.tpl b/src/views/admin/manage/api.tplindex 1e45da2704..9dd711f1a4 100644--- a/src/views/admin/manage/api.tpl+++ b/src/views/admin/manage/api.tpl@@ -51,11 +51,9 @@</thead><tbody>{{{ each tokens }}}- <tr data-token="{./token}" class="">- <td class="text-nowrap">- <button type="button" class="btn btn-link" data-action="copy" data-clipboard-text="{./token}"><i class="fa fa-fw fa-clipboard" aria-hidden="true"></i></button>- <div class="vr me-3" aria-hidden="true"></div>- <span class="user-select-all">{./token}</span>+ <tr data-token="{./tokenId}" class="">+ <td class="text-nowrap align-middle">+ {./tokenMasked}</td><td class="align-middle">{{{ if ./description }}}