Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

fix(security): redact bearer tokens and token parameters in error text

spacesdrivedf81b3ac641b
diff --git a/backend/lib/errors.ts b/backend/lib/errors.ts
index 02c098a..bc0432e 100644
--- a/backend/lib/errors.ts
+++ b/backend/lib/errors.ts
@@ -1,4 +1,4 @@
-import { redactUrls } from './redact.ts';
+import { redactSecrets } from './redact.ts';
import type { ApiErrorCode } from '../../shared/types/domain.ts';
// services throw these; middleware/errorHandler.ts maps each code to a status and the one error body
@@ -62,13 +62,13 @@ export interface UpstreamDetails {
cause?: unknown;
}
-// keeps the platform's wording, which users can act on, but never a url that may carry a key or token
+// keeps the platform's wording, which users can act on, but never a url, header or token that may carry a credential
export class UpstreamError extends AppError {
readonly reason: string;
readonly upstreamStatus: number | undefined;
constructor(message: string, { reason = '', status, cause }: UpstreamDetails = {}) {
- super('UPSTREAM_ERROR', redactUrls(message), { cause });
+ super('UPSTREAM_ERROR', redactSecrets(message), { cause });
this.reason = reason;
this.upstreamStatus = status;
}
diff --git a/backend/lib/logger.ts b/backend/lib/logger.ts
index ecb34f5..e9cce3a 100644
--- a/backend/lib/logger.ts
+++ b/backend/lib/logger.ts
@@ -1,4 +1,4 @@
-import { redactUrls } from './redact.ts';
+import { redactSecrets } from './redact.ts';
export type LogFields = Record<string, unknown>;
@@ -30,10 +30,10 @@ export function createLogger(base: LogFields = {}): Logger {
};
}
-// the message and the message of its cause, with urls removed; never the stack, which can hold request data
+// the message and the message of its cause, with urls and tokens removed; never the stack, which can hold request data
export function errorFields(err: unknown): LogFields {
const error = err as Error & { cause?: unknown };
- const fields: LogFields = { error: redactUrls(String(error?.message ?? err)), errorName: error?.name };
- if (error?.cause !== undefined) fields.cause = redactUrls(String((error.cause as Error)?.message ?? error.cause));
+ const fields: LogFields = { error: redactSecrets(String(error?.message ?? err)), errorName: error?.name };
+ if (error?.cause !== undefined) fields.cause = redactSecrets(String((error.cause as Error)?.message ?? error.cause));
return fields;
}
diff --git a/backend/lib/redact.ts b/backend/lib/redact.ts
index e7fc73d..55f9815 100644
--- a/backend/lib/redact.ts
+++ b/backend/lib/redact.ts
@@ -1,4 +1,11 @@
-// platform errors can echo the request url, which carries the api key or access token
-export function redactUrls(message: string): string {
- return message.replace(/https?:\/\/[^\s)]+/g, '[url]');
+// names whose value is a credential wherever it appears, in a query string, a form body or JSON
+const SECRET_NAMES = 'access_token|refresh_token|id_token|client_secret|app_secret|api_key|apikey|password|token|secret';
+
+// platform errors can echo the request url, a header or the form body, which carry the api key or access token
+export function redactSecrets(message: string): string {
+ return message
+ .replace(/https?:\/\/[^\s)]+/g, '[url]')
+ .replace(/\bBearer\s+[^\s"',]+/gi, 'Bearer [redacted]')
+ .replace(new RegExp(`\\b(${SECRET_NAMES})=[^&\\s"',]+`, 'gi'), '$1=[redacted]')
+ .replace(new RegExp(`"(${SECRET_NAMES})"\\s*:\\s*"[^"]*"`, 'gi'), '"$1":"[redacted]"');
}
diff --git a/backend/services/automationReconciler.ts b/backend/services/automationReconciler.ts
index 283125f..ceebe7e 100644
--- a/backend/services/automationReconciler.ts
+++ b/backend/services/automationReconciler.ts
@@ -10,7 +10,7 @@ import {
REVIEW_BATCH, REVIEW_MAX_CHECKS, REVIEW_RECHECK_SECONDS, REVIEW_SETTLE_SECONDS, SUBREQUESTS_PER_REVIEW, findSentReply, reviewNote,
} from '../lib/automationReview.ts';
import { errorFields } from '../lib/logger.ts';
-import { redactUrls } from '../lib/redact.ts';
+import { redactSecrets } from '../lib/redact.ts';
import type { AutomationCommentRepository, ExpiredCounts, ReviewCandidate, ReviewResult } from '../repositories/automationCommentRepository.ts';
import type { AutomationPublicReplyRepository, PublicReviewCandidate, PublicReviewResult } from '../repositories/automationPublicReplyRepository.ts';
import type { QueueHealth } from '../lib/automationHealth.ts';
@@ -79,7 +79,7 @@ export function createAutomationReconciler({ comments, publicReplies, context }:
} catch (err) {
// an Instagram error is a check that could not be made; it counts, so a broken conversation is not asked forever
reviewed.failed++;
- const reason = redactUrls((err as Error).message ?? 'unknown error').slice(0, 200);
+ const reason = redactSecrets((err as Error).message ?? 'unknown error').slice(0, 200);
log.warn('automation review check failed', { commentRowId: candidate.id, ...errorFields(err) });
await comments.recordReview(candidate.id, { found: false, note: `Twiligent could not read the conversation on Instagram (${reason}). Check it yourself before you retry.` })
.catch(recordErr => log.error('automation review not recorded', { commentRowId: candidate.id, ...errorFields(recordErr) }));
@@ -117,7 +117,7 @@ export function createAutomationReconciler({ comments, publicReplies, context }:
else reviewed.notFound++;
} catch (err) {
reviewed.failed++;
- const reason = redactUrls((err as Error).message ?? 'unknown error').slice(0, 200);
+ const reason = redactSecrets((err as Error).message ?? 'unknown error').slice(0, 200);
log.warn('automation public review check failed', { publicReplyId: candidate.id, ...errorFields(err) });
await publicReplies.recordReview(candidate.id, { found: false, note: `Twiligent could not read the comment's replies on Instagram (${reason}). Check the comment yourself before you retry.`, resend: false })
.catch(recordErr => log.error('automation public review not recorded', { publicReplyId: candidate.id, ...errorFields(recordErr) }));
diff --git a/backend/services/instagram/instagramMessaging.ts b/backend/services/instagram/instagramMessaging.ts
index 4fd33ba..9c7a7d9 100644
--- a/backend/services/instagram/instagramMessaging.ts
+++ b/backend/services/instagram/instagramMessaging.ts
@@ -1,6 +1,6 @@
import { buildGraphUrl, igFetch, igPost } from './instagramApi.ts';
import { UpstreamError, isAbortError } from '../../lib/errors.ts';
-import { redactUrls } from '../../lib/redact.ts';
+import { redactSecrets } from '../../lib/redact.ts';
import { FOLLOW_CHECK_TIMEOUT_MS, SEND_TIMEOUT_MS, classifySendError } from '../../lib/automationDelivery.ts';
import type { FollowCheck, SendResult } from '../../lib/automationDelivery.ts';
import type { ConversationMessage } from '../../lib/automationReview.ts';
@@ -71,7 +71,7 @@ export async function postOnce<T extends InstagramApiErrorBody>(endpoint: string
code: error.code,
subcode: error.error_subcode,
httpStatus: response.status,
- message: redactUrls(error.message || body.error_message || `HTTP ${response.status}`),
+ message: redactSecrets(error.message || body.error_message || `HTTP ${response.status}`),
usageHeader,
};
}
@@ -111,7 +111,7 @@ export async function readFollowStatus(igsid: string, accessToken: string): Prom
return { kind: 'unverifiable', message: 'its answer had no follow status' };
}
const error = body.error ?? {};
- const message = redactUrls(error.message || body.error_message || `HTTP ${response.status}`);
+ const message = redactSecrets(error.message || body.error_message || `HTTP ${response.status}`);
const kind = classifySendError({ code: error.code, subcode: error.error_subcode, httpStatus: response.status, message });
if (kind === 'rate_limited' || kind === 'blocked' || kind === 'transient') return { kind: 'retry', message };
if (kind === 'not_authorized') return { kind: 'not_authorized', message };
diff --git a/backend/tests/lib/redact.test.ts b/backend/tests/lib/redact.test.ts
new file mode 100644
index 0000000..75ca2c9
--- /dev/null
+++ b/backend/tests/lib/redact.test.ts
@@ -0,0 +1,28 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { redactSecrets } from '../../lib/redact.ts';
+
+test('a url in an error message is replaced, since it can carry an api key', () => {
+ assert.equal(redactSecrets('GET https://graph.instagram.com/me?access_token=IGQ123 failed'), 'GET [url] failed');
+});
+
+test('a bearer token is hidden but the rest of the message stays readable', () => {
+ assert.equal(redactSecrets('Authorization: Bearer eyJhbGciOi.abc.def was refused'), 'Authorization: Bearer [redacted] was refused');
+});
+
+test('token-like parameters in a form body or query are hidden by name', () => {
+ assert.equal(
+ redactSecrets('body grant_type=ig_exchange_token&client_secret=abc123&access_token=IGQ456 rejected'),
+ 'body grant_type=ig_exchange_token&client_secret=[redacted]&access_token=[redacted] rejected',
+ );
+});
+
+test('token-like fields in an echoed json body are hidden by name', () => {
+ assert.equal(redactSecrets('{"refresh_token": "r-1", "user": "u-1"}'), '{"refresh_token":"[redacted]", "user": "u-1"}');
+});
+
+test('ordinary messages, database ones included, pass through unchanged', () => {
+ const message = 'duplicate key value violates unique constraint "accounts_id_user_id_key"';
+ assert.equal(redactSecrets(message), message);
+ assert.equal(redactSecrets('The token has expired. Reconnect the account.'), 'The token has expired. Reconnect the account.');
+});