Skip to content

SC-2419: message whitelisting per builder #6668

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions examples/ts/build-message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,8 @@
*/

import {BitGoAPI} from '@bitgo/sdk-api';
import {MessageStandardType} from "@bitgo/sdk-core";
import {MessageStandardType, getMidnightGlacierDropClaimMsg} from "@bitgo/sdk-core";
import {Hteth} from "@bitgo/sdk-coin-eth";
import {MIDNIGHT_TNC_HASH} from "@bitgo/account-lib";
require('dotenv').config({ path: '../../.env' });

const bitgo = new BitGoAPI({
Expand All @@ -30,7 +29,8 @@ async function main() {
console.log(`Wallet label: ${wallet.label()}`);

const adaTestnetDestinationAddress = 'addr_test1vz7xs7ceu4xx9n5xn57lfe86vrwddqpp77vjwq5ptlkh49cqy3wur';
const testnetMessageRaw = `STAR 12345678 to ${adaTestnetDestinationAddress} ${MIDNIGHT_TNC_HASH}`;
const allocationAmt = 12345678;
const testnetMessageRaw = getMidnightGlacierDropClaimMsg(adaTestnetDestinationAddress, allocationAmt);

const txRequest = await wallet.buildSignMessageRequest({
message: {
Expand Down
6 changes: 3 additions & 3 deletions examples/ts/sign-message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
* Copyright 2025, BitGo, Inc. All Rights Reserved.
*/
import { BitGo } from 'bitgo';
import { MessageStandardType } from '@bitgo/sdk-core';
import { MIDNIGHT_TNC_HASH } from "@bitgo/account-lib";
import { getMidnightGlacierDropClaimMsg, MessageStandardType } from '@bitgo/sdk-core';

const bitgo = new BitGo({ env: 'test' });

Expand All @@ -20,7 +19,8 @@ async function signMessage(): Promise<void> {
const walletInstance = await basecoin.wallets().get({ id: walletId });

const adaTestnetDestinationAddress = 'addr_test1vz7xs7ceu4xx9n5xn57lfe86vrwddqpp77vjwq5ptlkh49cqy3wur';
const testnetMessageRaw = `STAR 12345678 to ${adaTestnetDestinationAddress} ${MIDNIGHT_TNC_HASH}`;
const allocationAmt = 12345678;
const testnetMessageRaw = getMidnightGlacierDropClaimMsg(adaTestnetDestinationAddress, allocationAmt);

const messageTxn = await walletInstance.signMessage({
message: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,10 @@ export class Eip191MessageBuilder extends BaseMessageBuilder {
async buildMessage(options: MessageOptions): Promise<IMessage> {
return new EIP191Message(options);
}

protected getWhitelistedMessageTemplates(): Record<string, string> {
// EIP-191 does not have whitelisted message templates
// This means all messages are allowed
return {};
}
}
16 changes: 7 additions & 9 deletions modules/account-lib/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ import {
BaseMessageBuilderFactory,
BuildMessageError,
MessageStandardType,
MIDNIGHT_TNC_HASH,
} from '@bitgo/sdk-core';
export { MIDNIGHT_TNC_HASH };

import { BaseCoin as CoinConfig, CoinFeature, coins } from '@bitgo/statics';
export { Ed25519BIP32, Eddsa };

Expand Down Expand Up @@ -206,9 +209,6 @@ export { Vet };
import * as CosmosSharedCoin from '@bitgo/sdk-coin-cosmos';
export { CosmosSharedCoin };

import { validateAgainstMessageTemplates, MIDNIGHT_TNC_HASH } from './utils';
export { MIDNIGHT_TNC_HASH };

const coinBuilderMap = {
trx: Trx.WrappedBuilder,
ttrx: Trx.WrappedBuilder,
Expand Down Expand Up @@ -429,15 +429,13 @@ export async function verifyMessage(
try {
const messageBuilderFactory = getMessageBuilderFactory(coinName);
const messageBuilder = messageBuilderFactory.getMessageBuilder(messageStandardType);
messageBuilder.setPayload(messageRaw);
const message = await messageBuilder.build();
const isValidMessageEncoded = await message.verifyEncodedPayload(messageEncoded, metadata);
if (!isValidMessageEncoded) {
if (!messageBuilder || !messageBuilder.isMessageWhitelisted(messageRaw)) {
return false;
}
return validateAgainstMessageTemplates(messageRaw);
messageBuilder.setPayload(messageRaw);
const message = await messageBuilder.build();
return await message.verifyEncodedPayload(messageEncoded, metadata);
} catch (e) {
console.error(`Error verifying message for coin ${coinName}:`, e);
return false;
}
}
2 changes: 0 additions & 2 deletions modules/account-lib/src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,3 @@ export function register(coinName: string): BaseUtils {
}
throw new NotSupported(`${coinName} util factory not supported`);
}

export * from './messages';
28 changes: 0 additions & 28 deletions modules/account-lib/src/utils/messages/index.ts

This file was deleted.

32 changes: 21 additions & 11 deletions modules/account-lib/test/unit/utils/messages/index.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,42 @@
import should from 'should';
import { MIDNIGHT_TNC_HASH, validateAgainstMessageTemplates } from '../../../../src/utils';
import {
getMidnightGlacierDropClaimMsg,
isMessageWhitelisted,
MIDNIGHT_GLACIER_DROP_CLAIM_MESSAGE_TEMPLATE,
MIDNIGHT_TNC_HASH,
} from '@bitgo/sdk-core';

describe('Message validation', () => {
describe('validateAgainstMessageTemplates', () => {
describe('isMessageWhitelisted', () => {
const whitelistedMessageTemplates: Record<string, string> = {
midnightGDClaimMsgTemplate: MIDNIGHT_GLACIER_DROP_CLAIM_MESSAGE_TEMPLATE,
};

const adaTestnetDestinationAddress = 'addr_test1vz7xs7ceu4xx9n5xn57lfe86vrwddqpp77vjwq5ptlkh49cqy3wur';
const adaMainnetDestinationAddress =
'addr1q9k6u7lhf467y2f8skr2dafldx2npsd8fymq0mslnj0t44nd4ealwnt4ug5j0pvx5m6n76v4xrq6wjfkqlhpl8y7httq2m9cmu';
const allocationAmt = 100;

it('should validate testnet message matching the Midnight glacier drop claim template', () => {
const messageRaw = `STAR 100 to ${adaTestnetDestinationAddress} ${MIDNIGHT_TNC_HASH}`;
const messageRaw = getMidnightGlacierDropClaimMsg(adaTestnetDestinationAddress, allocationAmt);

const result = validateAgainstMessageTemplates(messageRaw);
const result = isMessageWhitelisted(whitelistedMessageTemplates, messageRaw);

should.equal(result, true);
});

it('should validate mainnet message matching the Midnight glacier drop claim template', () => {
const messageRaw = `STAR 100 to ${adaMainnetDestinationAddress} ${MIDNIGHT_TNC_HASH}`;
const messageRaw = getMidnightGlacierDropClaimMsg(adaMainnetDestinationAddress, allocationAmt);

const result = validateAgainstMessageTemplates(messageRaw);
const result = isMessageWhitelisted(whitelistedMessageTemplates, messageRaw);

should.equal(result, true);
});

it('should not validate message with incorrect format', () => {
const messageRaw = `INCORRECT 100 to ${adaTestnetDestinationAddress} ${MIDNIGHT_TNC_HASH}`;

const result = validateAgainstMessageTemplates(messageRaw);
const result = isMessageWhitelisted(whitelistedMessageTemplates, messageRaw);

should.equal(result, false);
});
Expand All @@ -35,7 +45,7 @@ describe('Message validation', () => {
// Missing "to addr" part
const messageRaw = `STAR 100 ${MIDNIGHT_TNC_HASH}`;

const result = validateAgainstMessageTemplates(messageRaw);
const result = isMessageWhitelisted(whitelistedMessageTemplates, messageRaw);

should.equal(result, false);
});
Expand All @@ -46,21 +56,21 @@ describe('Message validation', () => {
'5af1adf825baa496729e2eac1e895ebc77973744bce67f44276bf6006f5c21de863ed121e11828d8fc0241773191e26dc1134803a681a9a98ba0ae812553db24';
const messageRaw = `STAR 100 to ${adaTestnetDestinationAddress} ${incorrectHash}`;

const result = validateAgainstMessageTemplates(messageRaw);
const result = isMessageWhitelisted(whitelistedMessageTemplates, messageRaw);

should.equal(result, false);
});

it('should handle empty message', () => {
const result = validateAgainstMessageTemplates('');
const result = isMessageWhitelisted(whitelistedMessageTemplates, '');

should.equal(result, false);
});

it('should not validate message with special regex characters', () => {
const messageRaw = `STAR shade.with+special*chars to addr.with[special]chars ${MIDNIGHT_TNC_HASH}`;

const result = validateAgainstMessageTemplates(messageRaw);
const result = isMessageWhitelisted(whitelistedMessageTemplates, messageRaw);

should.equal(result, false);
});
Expand Down
6 changes: 3 additions & 3 deletions modules/account-lib/test/unit/verifyMessage.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import should from 'should';
import * as accountLib from '../../src';
import { MessageStandardType } from '@bitgo/sdk-core';
import { MIDNIGHT_TNC_HASH } from '../../src/utils';
import { getMidnightGlacierDropClaimMsg, MessageStandardType } from '@bitgo/sdk-core';

describe('verifyMessage', () => {
const adaTestnetOriginAddress = 'addr_test1wz4h6068hs93n8j5ar88fgzz6sfnw8krng09xx0mmf36m8c7j9yap';
const adaTestnetDestinationAddress = 'addr_test1vz7xs7ceu4xx9n5xn57lfe86vrwddqpp77vjwq5ptlkh49cqy3wur';
const testnetMessageRaw = `STAR 100 to ${adaTestnetDestinationAddress} ${MIDNIGHT_TNC_HASH}`;
const allocationAmt = 100;
const testnetMessageRaw = getMidnightGlacierDropClaimMsg(adaTestnetDestinationAddress, allocationAmt);

describe('EIP191 Message', function () {
const eip191MessageBuilder = accountLib
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
MessageOptions,
MessagePayload,
MessageStandardType,
} from '../../../bitgo';
} from './messageTypes';
import { IMessage } from './iface';
import { serializeSignatures, Signature } from '../iface';

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { BroadcastableMessage, MessageOptions, MessagePayload, MessageStandardType } from '../../../bitgo';
import { BroadcastableMessage, MessageOptions, MessagePayload, MessageStandardType } from './messageTypes';
import { BaseCoin as CoinConfig } from '@bitgo/statics';
import { IMessage, IMessageBuilder } from './iface';
import { deserializeSignatures, Signature } from '../iface';
import { isMessageWhitelisted, MIDNIGHT_GLACIER_DROP_CLAIM_MESSAGE_TEMPLATE } from './index';

/**
* Base Message Builder
Expand All @@ -12,6 +13,7 @@ export abstract class BaseMessageBuilder implements IMessageBuilder {
protected type: MessageStandardType;
protected signatures: Signature[] = [];
protected signers: string[] = [];
protected whitelistedMessageTemplates: Record<string, string> = {};
protected metadata?: Record<string, unknown> = {};
protected digest?: string;

Expand All @@ -26,6 +28,7 @@ export abstract class BaseMessageBuilder implements IMessageBuilder {
) {
this.coinConfig = coinConfig;
this.type = messageType;
this.whitelistedMessageTemplates = this.getWhitelistedMessageTemplates();
}

/**
Expand Down Expand Up @@ -118,6 +121,10 @@ export abstract class BaseMessageBuilder implements IMessageBuilder {
return this;
}

public isMessageWhitelisted(messageRaw: string): boolean {
return isMessageWhitelisted(this.whitelistedMessageTemplates, messageRaw);
}

/**
* Builds a message using the previously set payload and metadata
* @returns A Promise resolving to the built IMessage
Expand Down Expand Up @@ -167,4 +174,11 @@ export abstract class BaseMessageBuilder implements IMessageBuilder {
};
return this.build();
}

protected getWhitelistedMessageTemplates(): Record<string, string> {
return {
midnightGDClaimMsgTemplate: MIDNIGHT_GLACIER_DROP_CLAIM_MESSAGE_TEMPLATE,
// Add more whitelisted templates as needed
};
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { BaseCoin as CoinConfig } from '@bitgo/statics';
import { IMessageBuilder, IMessageBuilderFactory } from './iface';
import { BroadcastableMessage, MessageStandardType } from '../../../bitgo';
import { BroadcastableMessage, MessageStandardType } from './messageTypes';
import { deserializeSignatures } from '../iface';

/**
Expand Down
11 changes: 10 additions & 1 deletion modules/sdk-core/src/account-lib/baseCoin/messages/iface.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BroadcastableMessage, MessageMetadata, MessagePayload, MessageStandardType } from '../../../bitgo';
import { BroadcastableMessage, MessageMetadata, MessagePayload, MessageStandardType } from './messageTypes';
import { Signature } from '../iface';

/**
Expand Down Expand Up @@ -136,6 +136,15 @@ export interface IMessageBuilder {
*/
getPayload(): MessagePayload | undefined;

/**
* Checks if the message string is whitelisted.
* Some message standards like EIP-191 allow any message
*
* @param messageRaw The raw message string to check
* @return True if the message builder allows any message or the message is whitelisted, false otherwise
*/
isMessageWhitelisted(messageRaw: string): boolean;

/**
* Gets the current metadata
* @returns The current metadata
Expand Down
3 changes: 3 additions & 0 deletions modules/sdk-core/src/account-lib/baseCoin/messages/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,6 @@ export * from './baseMessageBuilder';
export * from './baseMessageBuilderFactory';
export * from './iface';
export * from './simple';
export * from './messageTypes';
export * from './midnight';
export * from './utils';
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { BaseCoin as CoinConfig } from '@bitgo/statics';
import { SerializedSignature, Signature } from '../../account-lib';
import { SerializedSignature, Signature } from '../iface';

/**
* Supported message signing standard types
Expand Down
12 changes: 12 additions & 0 deletions modules/sdk-core/src/account-lib/baseCoin/messages/midnight.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export const MIDNIGHT_TNC_HASH = '31a6bab50a84b8439adcfb786bb2020f6807e6e8fda629b424110fc7bb1c6b8b';

/*
* matches a message that starts with "STAR ", followed by a number,
* then " to addr" or " to addr_test1", followed by a 50+ character alphanumeric address,
* and ends with the midnight TnC hash
*/
export const MIDNIGHT_GLACIER_DROP_CLAIM_MESSAGE_TEMPLATE = `STAR \\d+ to addr(?:1|_test1)[a-z0-9]{50,} ${MIDNIGHT_TNC_HASH}`;

export function getMidnightGlacierDropClaimMsg(cardanoDestAddr: string, allocationAmt: number): string {
return `STAR ${allocationAmt} to ${cardanoDestAddr} ${MIDNIGHT_TNC_HASH}`;
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { BaseMessage } from '../baseMessage';
import { MessageOptions, MessageStandardType } from '../../../../bitgo';
import { MessageOptions, MessageStandardType } from '../messageTypes';

/**
* Implementation of String Message
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { SimpleMessage } from './simpleMessage';
import { BaseCoin as CoinConfig } from '@bitgo/statics';
import { BaseMessageBuilder } from '../baseMessageBuilder';
import { MessageOptions, MessageStandardType } from '../../../../bitgo';
import { MessageOptions, MessageStandardType } from '../messageTypes';
import { IMessage } from '../iface';

/**
Expand Down
17 changes: 17 additions & 0 deletions modules/sdk-core/src/account-lib/baseCoin/messages/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* Validates a message against a set of whitelisted templates.
* The templates can contain placeholders like {{variable}} which will be replaced with a wildcard in the regex.
*
* @param whitelistedMessageTemplates - A record of whitelisted message templates.
* @param {string} messageRaw - The raw message to validate.
* @returns {boolean} - Returns true if the message matches any of the whitelisted templates, false otherwise.
*/
export function isMessageWhitelisted(whitelistedMessageTemplates: Record<string, string>, messageRaw: string): boolean {
if (!whitelistedMessageTemplates || !Object.keys(whitelistedMessageTemplates).length) {
return true;
}
return Object.values(whitelistedMessageTemplates).some((template) => {
const regex = new RegExp(`^${template}$`, 's'); // 's' flag to match newlines
return regex.test(messageRaw);
});
}
4 changes: 2 additions & 2 deletions modules/sdk-core/src/bitgo/baseCoin/iBaseCoin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ import EddsaUtils, { PrebuildTransactionWithIntentOptions, TxRequest } from '../
import { CreateAddressFormat, CustomSigningFunction, IWallet, IWallets, Wallet, WalletData, Memo } from '../wallet';

import { IWebhooks } from '../webhook/iWebhooks';
import { TransactionType } from '../../account-lib';
import { MessageStandardType, TransactionType } from '../../account-lib';
import { IInscriptionBuilder } from '../inscriptionBuilder';
import { Hash } from 'crypto';
import { MessageStandardType, MPCTx, PopulatedIntent, TokenType } from '../utils';
import { MPCTx, PopulatedIntent, TokenType } from '../utils';

export const multisigTypes = {
onchain: 'onchain',
Expand Down
1 change: 0 additions & 1 deletion modules/sdk-core/src/bitgo/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,5 @@ export * from './util';
export * from './decode';
export * from './notEmpty';
export * from './wallet';
export * from './messageTypes';

export { openpgpUtils };
Loading
Loading