Compare commits

..
Author SHA1 Message Date
Vishnu NarayananandGitHub 6c5077dbad Merge branch 'develop' into fix/widget-conversations-throttle-key 2026-05-27 15:27:33 +05:30
Silva Dev BRandGitHub 2628d7a7fd fix: prevent alt shortcuts while typing (#14526) 2026-05-27 15:11:49 +05:30
Shivam MishraandGitHub 94daf26ead chore: update jwt and faraday (#14577)
This PR updates two dependencies — `faraday` (2.14.1 → 2.14.2) and `jwt`
(2.10.1 → 2.10.3) — to pick up security patches flagged by
`bundle-audit`. Both are bumped to the minimal patched release within
their existing major lines to keep the blast radius small.

### Faraday

`Faraday::Connection#build_exclusive_url` still allowed a
protocol-relative host override when the request target was passed as a
`URI` object (rather than a `String`), bypassing the earlier fix for the
string-based variant (CVE-2026-25765 / GHSA-33mh-2634-fwr2). On a
fixed-base connection this could redirect a request to an
attacker-controlled host while still forwarding connection-scoped
headers such as `Authorization` — i.e. off-host request forgery
(CVE-2026-33637 / GHSA-5rv5-xj5j-3484).

The fix is a clean patch bump to `2.14.2`, within Faraday's existing
version range — no API changes and no other gems affected.

### JWT

`jwt` 2.10.1 accepts an empty/`nil` HMAC key during verification:
`JWT.decode(token, "", true, algorithm: 'HS256')` (and keyfinder paths
returning `""`/`nil`) verify a forged token, because the empty-key HMAC
digest is treated as valid and `enforce_hmac_key_length` defaults to
`false` (CVE-2026-45363, High).

The advisory offers two fixes — `~> 2.10.3` or `>= 3.2.0`. We chose
**2.10.3** deliberately: jumping to 3.x cascaded into upgrading
`oauth2`, `twilio-ruby`, `googleauth`, `web-push`, and `signet` (all
pinned `jwt < 3.0`), and `jwt` is used directly in 8+ places here (token
services, OAuth callbacks, integration helpers), so a major bump carries
real breakage risk for no extra security benefit. The Gemfile is pinned
`'~> 2.10', '>= 2.10.3'` to hold the 2.x line.

**Spec changes.** 2.10.3 tightens key handling: HMAC sign/verify now
raises on a `nil`, empty, or non-`String` key instead of silently
coercing it. A few specs relied on the old lax behaviour and needed
updating:

- `microsoft` / `google` callback specs built unsigned ID tokens via
`JWT.encode(payload, false)`. Replaced with the correct unsigned form,
`JWT.encode(payload, nil, 'none')`.
- `instagram` / `linear` / `shopify` helper specs have a "client secret
not configured" context where `client_secret` is `nil`. Their shared
`valid_token` `let` signed with that `nil` secret, which Ruby evaluates
before the helper runs — now raising. Since the helper short-circuits on
the blank secret and never decodes the token, those contexts now
override `valid_token` with a throwaway string.

**Production is unaffected.** Every production HMAC path uses a real,
non-empty key — `Rails.application.secret_key_base` (`BaseTokenService`,
`Widget::TokenService`) or a client secret guarded by `return if
client_secret.blank?` (Instagram/TikTok/Shopify/Linear helpers). The one
`nil`-key call, `JWT.decode(id_token, nil, false)` in
`OauthCallbackController`, runs with verification disabled, so the key
is never inspected. Twilio voice tokens use `Twilio::JWT::AccessToken`
from `twilio-ruby`, not this gem. The specs failed precisely because
they exercised the unsafe empty-key pattern the patch now blocks —
production never did.
2026-05-27 14:43:23 +05:30
Sivin VargheseandGitHub 7422b656cd fix: prevent status label overflow (#14580) 2026-05-27 14:17:57 +05:30
Vinícius FitznerandGitHub 39a93db007 fix(sidebar): prevent line wrap in availability selector (#13940) 2026-05-27 14:06:45 +05:30
Vishnu Narayanan 4bd84f05be fix: add widget conversation throttle by ip + website_token
Replaces the per-IP 6-per-12h throttle (disabled in cloud as too aggressive
for shared NAT IPs) with a per-(IP, website_token) 30-per-minute burst
throttle. Distinct widgets behind a shared NAT IP get separate buckets so
the original NAT pain is preserved while a single source can no longer
create unbounded conversations against one widget.

Adds ENABLE_RACK_ATTACK_WIDGET_CONVERSATIONS as an independent kill switch
so this throttle can be toggled without re-enabling the legacy widget
throttles. RATE_LIMIT_WIDGET_CONVERSATIONS controls the per-minute cap.
2026-05-05 22:59:27 +05:30
30 changed files with 128 additions and 213 deletions
+1 -1
View File
@@ -89,7 +89,7 @@ gem 'rails-i18n', '~> 7.0'
# two-factor authentication
gem 'devise-two-factor', '>= 5.0.0'
# authorization
gem 'jwt'
gem 'jwt', '~> 2.10', '>= 2.10.3'
gem 'pundit'
# super admin
+3 -3
View File
@@ -301,7 +301,7 @@ GEM
railties (>= 5.0.0)
faker (3.2.0)
i18n (>= 1.8.11, < 2)
faraday (2.14.1)
faraday (2.14.2)
faraday-net_http (>= 2.0, < 3.5)
json
logger
@@ -491,7 +491,7 @@ GEM
judoscale-sidekiq (1.8.2)
judoscale-ruby (= 1.8.2)
sidekiq (>= 5.0)
jwt (2.10.1)
jwt (2.10.3)
base64
kaminari (1.2.2)
activesupport (>= 4.1.0)
@@ -1102,7 +1102,7 @@ DEPENDENCIES
json_schemer
judoscale-rails
judoscale-sidekiq
jwt
jwt (~> 2.10, >= 2.10.3)
kaminari
koala
letter_opener
@@ -16,7 +16,6 @@ const props = defineProps({
name: { type: String, default: '' },
email: { type: String, default: '' },
additionalAttributes: { type: Object, default: () => ({}) },
countryCode: { type: String, default: '' },
phoneNumber: { type: String, default: '' },
thumbnail: { type: String, default: '' },
availabilityStatus: { type: String, default: null },
@@ -43,7 +42,6 @@ const getInitialContactData = () => ({
name: props.name,
email: props.email,
phoneNumber: props.phoneNumber,
countryCode: props.countryCode,
additionalAttributes: props.additionalAttributes,
});
@@ -60,13 +58,12 @@ const countriesMap = computed(() => {
const countryDetails = computed(() => {
const attributes = props.additionalAttributes || {};
const { country, countryCode: additionalCountryCode, city } = attributes;
const countryCode = props.countryCode || additionalCountryCode;
const { country, countryCode, city } = attributes;
if (!country && !countryCode) return null;
const activeCountry =
countriesMap.value[countryCode] || countriesMap.value[country];
countriesMap.value[country] || countriesMap.value[countryCode];
if (!activeCountry) return null;
@@ -96,7 +96,6 @@ const prepareStateBasedOnProps = () => {
name = '',
email: emailAddress,
phoneNumber,
countryCode: contactCountryCode = '',
additionalAttributes = {},
} = props.contactData || {};
const { firstName, lastName } = splitName(name || '');
@@ -123,7 +122,7 @@ const prepareStateBasedOnProps = () => {
additionalAttributes: {
description,
companyName,
countryCode: contactCountryCode || countryCode,
countryCode,
country,
city,
socialProfiles: {
@@ -94,7 +94,6 @@ const handleAvatarHover = (id, isHovered) => {
:email="contact.email"
:thumbnail="contact.thumbnail"
:phone-number="contact.phoneNumber"
:country-code="contact.countryCode"
:additional-attributes="contact.additionalAttributes"
:availability-status="contact.availabilityStatus"
:is-expanded="expandedCardId === contact.id"
@@ -78,26 +78,27 @@ function changeAvailabilityStatus(availability) {
<template>
<DropdownSection class="[&>ul]:overflow-visible">
<div class="grid gap-0">
<DropdownItem preserve-open>
<div class="flex-grow flex items-center gap-1">
<DropdownItem preserve-open class="gap-1">
<div class="flex-grow flex items-center gap-1 min-w-0">
{{ $t('SIDEBAR.SET_YOUR_AVAILABILITY') }}
</div>
<DropdownContainer>
<DropdownContainer class="shrink-0">
<template #trigger="{ toggle }">
<Button
size="sm"
color="slate"
variant="faded"
class="min-w-[96px]"
icon="i-lucide-chevron-down"
trailing-icon
@click="toggle"
>
<div class="flex gap-1 items-center flex-grow text-sm">
<div class="flex gap-1 items-center min-w-0 text-sm">
<div class="p-1 flex-shrink-0">
<div class="size-2 rounded-sm" :class="activeStatus.color" />
</div>
<span>{{ activeStatus.label }}</span>
<span class="truncate max-w-[7rem]">
{{ activeStatus.label }}
</span>
</div>
</Button>
</template>
@@ -114,12 +115,12 @@ function changeAvailabilityStatus(availability) {
</DropdownContainer>
</DropdownItem>
<DropdownItem>
<div class="flex-grow flex items-center gap-1">
<div class="flex-grow min-w-0">
{{ $t('SIDEBAR.SET_AUTO_OFFLINE.TEXT') }}
<Icon
v-tooltip.top="$t('SIDEBAR.SET_AUTO_OFFLINE.INFO_SHORT')"
icon="i-lucide-info"
class="size-4 text-n-slate-10"
class="inline-block align-middle ms-1 size-4 text-n-slate-10"
/>
</div>
<ToggleSwitch v-model="autoOfflineToggle" />
@@ -589,11 +589,11 @@ function isCmdPlusEnterToSendEnabled() {
useKeyboardEvents({
'Alt+KeyP': {
action: focusEditorInputField,
allowOnFocusedInput: true,
allowOnFocusedInput: false,
},
'Alt+KeyL': {
action: focusEditorInputField,
allowOnFocusedInput: true,
allowOnFocusedInput: false,
},
});
@@ -105,11 +105,11 @@ export default {
const keyboardEvents = {
'Alt+KeyP': {
action: () => handleNoteClick(),
allowOnFocusedInput: true,
allowOnFocusedInput: false,
},
'Alt+KeyL': {
action: () => handleReplyClick(),
allowOnFocusedInput: true,
allowOnFocusedInput: false,
},
};
useKeyboardEvents(keyboardEvents);
@@ -1,6 +1,47 @@
const keyboardEventsMock = vi.hoisted(() => ({
mountedCallbacks: [],
unmountedCallbacks: [],
registeredKeybindings: {},
}));
vi.mock('vue', async importOriginal => ({
...(await importOriginal()),
onMounted: vi.fn(callback =>
keyboardEventsMock.mountedCallbacks.push(callback)
),
onUnmounted: vi.fn(callback =>
keyboardEventsMock.unmountedCallbacks.push(callback)
),
}));
vi.mock('dashboard/composables/useDetectKeyboardLayout', () => ({
useDetectKeyboardLayout: vi.fn(() => Promise.resolve('QWERTY')),
}));
vi.mock('tinykeys', () => ({
createKeybindingsHandler: vi.fn(keybindings => {
keyboardEventsMock.registeredKeybindings = keybindings;
return event => keybindings[event.shortcut]?.(event);
}),
}));
import { useDetectKeyboardLayout } from 'dashboard/composables/useDetectKeyboardLayout';
import { useKeyboardEvents } from 'dashboard/composables/useKeyboardEvents';
import { LAYOUT_QWERTZ } from 'shared/helpers/KeyboardHelpers';
const mount = async events => {
useKeyboardEvents(events);
await keyboardEventsMock.mountedCallbacks[0]();
return keyboardEventsMock.registeredKeybindings;
};
describe('useKeyboardEvents', () => {
beforeEach(() => {
keyboardEventsMock.mountedCallbacks = [];
keyboardEventsMock.unmountedCallbacks = [];
keyboardEventsMock.registeredKeybindings = {};
});
it('should be defined', () => {
expect(useKeyboardEvents).toBeDefined();
});
@@ -9,18 +50,46 @@ describe('useKeyboardEvents', () => {
expect(useKeyboardEvents).toBeInstanceOf(Function);
});
it('should set up listeners on mount and remove them on unmount', async () => {
const events = {
'ALT+KeyL': () => {},
};
it('registers keybindings on mount and removes the listener on unmount', async () => {
const addEventListener = vi.spyOn(document, 'addEventListener');
const mountedMock = vi.fn();
const unmountedMock = vi.fn();
useKeyboardEvents(events);
mountedMock();
unmountedMock();
const keybindings = await mount({ 'ALT+KeyL': () => {} });
expect(Object.keys(keybindings)).toEqual(['ALT+KeyL']);
expect(mountedMock).toHaveBeenCalled();
expect(unmountedMock).toHaveBeenCalled();
const { signal } = addEventListener.mock.calls[0][2];
expect(signal.aborted).toBe(false);
keyboardEventsMock.unmountedCallbacks[0]();
expect(signal.aborted).toBe(true);
});
it('prefixes Shift on QWERTZ layouts for the affected keys', async () => {
useDetectKeyboardLayout.mockResolvedValueOnce(LAYOUT_QWERTZ);
const keybindings = await mount({ 'Alt+KeyL': () => {} });
expect(Object.keys(keybindings)).toEqual(['Shift+Alt+KeyL']);
});
it('ignores shortcuts on focused typeable elements by default', async () => {
const action = vi.fn();
const keybindings = await mount({
'Alt+KeyL': { action, allowOnFocusedInput: false },
});
keybindings['Alt+KeyL']({ target: document.createElement('textarea') });
expect(action).not.toHaveBeenCalled();
});
it('runs shortcuts on focused typeable elements when allowed', async () => {
const action = vi.fn();
const keybindings = await mount({
'Alt+KeyL': { action, allowOnFocusedInput: true },
});
keybindings['Alt+KeyL']({ target: document.createElement('textarea') });
expect(action).toHaveBeenCalledTimes(1);
});
});
@@ -37,10 +37,6 @@ const props = defineProps({
type: Object,
default: () => ({}),
},
countryCode: {
type: String,
default: '',
},
updatedAt: {
type: Number,
default: 0,
@@ -64,17 +60,12 @@ const updatedAtTime = computed(() => {
});
const countryDetails = computed(() => {
const {
country,
countryCode: additionalCountryCode,
city,
} = props.additionalAttributes;
const countryCode = props.countryCode || additionalCountryCode;
const { country, countryCode, city } = props.additionalAttributes;
if (!country && !countryCode) return null;
const activeCountry =
countriesMap.value[countryCode] || countriesMap.value[country];
countriesMap.value[country] || countriesMap.value[countryCode];
if (!activeCountry) return null;
@@ -41,7 +41,6 @@ const accountId = useMapGetter('getCurrentAccountId');
:name="contact.name"
:email="contact.email"
:phone="contact.phoneNumber"
:country-code="contact.countryCode"
:additional-attributes="contact.additionalAttributes"
:account-id="accountId"
:thumbnail="contact.thumbnail"
@@ -72,14 +72,12 @@ export default {
city = '',
country_code: countryCode,
} = this.additionalAttributes;
const canonicalCountryCode =
this.contact.country_code || this.contact.countryCode || countryCode;
const cityAndCountry = [city, country].filter(item => !!item).join(', ');
if (!cityAndCountry) {
return '';
}
return this.findCountryFlag(canonicalCountryCode, cityAndCountry);
return this.findCountryFlag(countryCode, cityAndCountry);
},
socialProfiles() {
const {
-1
View File
@@ -32,7 +32,6 @@ class Account::ContactsExportJob < ApplicationJob
def value_for_header(contact, header)
return contact_labels_by_id.fetch(contact.id, []).join(LABELS_DELIMITER) if header == LABELS_COLUMN
return contact.canonical_country_code if header == 'country_code'
contact.send(header)
end
@@ -1,26 +0,0 @@
module ContactCountryHelpers
extend ActiveSupport::Concern
def canonical_country_code
attributes = additional_attributes || {}
CountryCodeNormalizer.normalize(self[:country_code]) ||
CountryCodeNormalizer.normalize(attributes['country_code']) ||
CountryCodeNormalizer.normalize(attributes['country'])
end
def canonical_country_name
CountryCodeNormalizer.name_for(canonical_country_code)
end
def additional_attributes_with_canonical_country
attributes = additional_attributes.deep_dup || {}
code = canonical_country_code
return attributes if code.blank?
attributes.merge(
'country_code' => code,
'country' => canonical_country_name || attributes['country']
)
end
end
-1
View File
@@ -44,7 +44,6 @@
class Contact < ApplicationRecord
include Avatarable
include AvailabilityStatusable
include ContactCountryHelpers
include Labelable
include LlmFormattable
-42
View File
@@ -1,42 +0,0 @@
require 'tzinfo'
class CountryCodeNormalizer
COUNTRY_ALIASES = {
'united states of america' => 'US',
'usa' => 'US',
'uk' => 'GB',
'united kingdom' => 'GB'
}.freeze
class << self
def normalize(value)
return if value.blank?
value = value.to_s.strip
code = value.upcase
return code if country_by_code.key?(code)
country_by_name[normalized_name(value)] || COUNTRY_ALIASES[normalized_name(value)]
end
def name_for(code)
country_by_code[normalize(code)]&.name
end
private
def country_by_code
@country_by_code ||= TZInfo::Country.all_codes.index_with { |code| TZInfo::Country.get(code) }
end
def country_by_name
@country_by_name ||= country_by_code.each_with_object({}) do |(code, country), result|
result[normalized_name(country.name)] = code
end
end
def normalized_name(value)
value.to_s.strip.downcase
end
end
end
@@ -26,7 +26,7 @@ class LlmFormatter::ContactLlmFormatter < LlmFormatter::DefaultLlmFormatter
attributes << "Email: #{@record.email}"
attributes << "Phone: #{@record.phone_number}"
attributes << "Location: #{@record.location}"
attributes << "Country Code: #{@record.canonical_country_code}"
attributes << "Country Code: #{@record.country_code}"
@record.account.custom_attribute_definitions.with_attribute_model('contact_attribute').each do |attribute|
attributes << "#{attribute.attribute_display_name}: #{@record.custom_attributes[attribute.attribute_key]}"
end
@@ -3,6 +3,5 @@ json.id contact.id
json.name contact.name
json.phone_number contact.phone_number
json.identifier contact.identifier
json.country_code contact.canonical_country_code
json.additional_attributes contact.additional_attributes_with_canonical_country
json.additional_attributes contact.additional_attributes
json.last_activity_at contact.last_activity_at&.to_i
@@ -1,6 +1,5 @@
json.additional_attributes resource.additional_attributes_with_canonical_country
json.additional_attributes resource.additional_attributes
json.availability_status resource.availability_status
json.country_code resource.canonical_country_code
json.email resource.email
json.id resource.id
json.name resource.name
+15 -5
View File
@@ -170,15 +170,25 @@ class Rack::Attack
###-----------Widget API Throttling---------------###
###-----------------------------------------------###
## Burst protection on widget conversation creation. Keyed on (IP, website_token)
## so distinct widgets behind a shared NAT IP get separate buckets. Independent
## kill switch so it can be toggled without touching the legacy ENABLE_RACK_ATTACK_WIDGET_API.
if ActiveModel::Type::Boolean.new.cast(ENV.fetch('ENABLE_RACK_ATTACK_WIDGET_CONVERSATIONS', true))
throttle('api/v1/widget/conversations',
limit: ENV.fetch('RATE_LIMIT_WIDGET_CONVERSATIONS', '30').to_i,
period: 1.minute) do |req|
next unless req.path_without_extentions == '/api/v1/widget/conversations' && req.post?
token = req.params['website_token'].presence ||
ActionDispatch::Request.new(req.env).params['website_token'].presence
"#{req.ip}:#{token}" if token
end
end
# Rack attack on widget APIs can be disabled by setting ENABLE_RACK_ATTACK_WIDGET_API to false
# For clients using the widgets in specific conditions like inside and iframe
# TODO: Deprecate this feature in future after finding a better solution
if ActiveModel::Type::Boolean.new.cast(ENV.fetch('ENABLE_RACK_ATTACK_WIDGET_API', true))
## Prevent Conversation Bombing on Widget APIs ###
throttle('api/v1/widget/conversations', limit: 6, period: 12.hours) do |req|
req.ip if req.path_without_extentions == '/api/v1/widget/conversations' && req.post?
end
## Prevent Contact update Bombing in Widget API ###
throttle('api/v1/widget/contacts', limit: 60, period: 1.hour) do |req|
req.ip if req.path_without_extentions == '/api/v1/widget/contacts' && (req.patch? || req.put?)
@@ -54,23 +54,6 @@ RSpec.describe 'Contacts API', type: :request do
expect(contact_inboxes_source_ids).to include(contact_inbox.source_id)
end
it 'returns canonical country attributes for contact display' do
contact.update!(additional_attributes: { country: 'United States' })
get "/api/v1/accounts/#{account.id}/contacts",
headers: admin.create_new_auth_token,
as: :json
response_body = response.parsed_body
response_contact = response_body['payload'].find { |item| item['id'] == contact.id }
expect(response_contact['additional_attributes']).to include(
'country_code' => 'US',
'country' => 'United States'
)
expect(response_contact['country_code']).to eq('US')
end
it 'returns all contacts without contact inboxes' do
get "/api/v1/accounts/#{account.id}/contacts?include_contact_inboxes=false",
headers: admin.create_new_auth_token,
@@ -8,12 +8,12 @@ RSpec.describe 'Google::CallbacksController', type: :request do
describe 'GET /google/callback' do
let(:response_body_success) do
{ id_token: JWT.encode({ email: email, name: 'test' }, false), access_token: SecureRandom.hex(10), token_type: 'Bearer',
{ id_token: JWT.encode({ email: email, name: 'test' }, nil, 'none'), access_token: SecureRandom.hex(10), token_type: 'Bearer',
refresh_token: SecureRandom.hex(10) }
end
let(:response_body_success_without_name) do
{ id_token: JWT.encode({ email: email }, false), access_token: SecureRandom.hex(10), token_type: 'Bearer',
{ id_token: JWT.encode({ email: email }, nil, 'none'), access_token: SecureRandom.hex(10), token_type: 'Bearer',
refresh_token: SecureRandom.hex(10) }
end
@@ -8,12 +8,12 @@ RSpec.describe 'Microsoft::CallbacksController', type: :request do
describe 'GET /microsoft/callback' do
let(:response_body_success) do
{ id_token: JWT.encode({ email: email, name: 'test' }, false), access_token: SecureRandom.hex(10), token_type: 'Bearer',
{ id_token: JWT.encode({ email: email, name: 'test' }, nil, 'none'), access_token: SecureRandom.hex(10), token_type: 'Bearer',
refresh_token: SecureRandom.hex(10) }
end
let(:response_body_success_without_name) do
{ id_token: JWT.encode({ email: email }, false), access_token: SecureRandom.hex(10), token_type: 'Bearer',
{ id_token: JWT.encode({ email: email }, nil, 'none'), access_token: SecureRandom.hex(10), token_type: 'Bearer',
refresh_token: SecureRandom.hex(10) }
end
@@ -82,6 +82,7 @@ RSpec.describe Instagram::IntegrationHelper do
context 'when client secret is not configured' do
let(:client_secret) { nil }
let(:valid_token) { 'any-token' }
it 'returns nil' do
expect(verify_instagram_token(valid_token)).to be_nil
@@ -65,6 +65,7 @@ RSpec.describe Linear::IntegrationHelper do
context 'when client secret is not configured' do
let(:client_secret) { nil }
let(:valid_token) { 'any-token' }
it 'returns nil' do
expect(verify_linear_token(valid_token)).to be_nil
@@ -65,6 +65,7 @@ RSpec.describe Shopify::IntegrationHelper do
context 'when client secret is not configured' do
let(:client_secret) { nil }
let(:valid_token) { 'any-token' }
it 'returns nil' do
expect(verify_shopify_token(valid_token)).to be_nil
@@ -99,19 +99,6 @@ RSpec.describe Account::ContactsExportJob do
expect(row['labels']).to eq('vip')
end
it 'exports canonical country codes from legacy country data' do
legacy_country_contact = create(:contact, account: account, email: 'legacy-country@example.com',
additional_attributes: { country: 'United States' })
described_class.perform_now(account.id, user.id, %w[email country_code], {})
csv_content = account.contacts_export.download.force_encoding('UTF-8').delete_prefix("\xEF\xBB\xBF")
csv_data = CSV.parse(csv_content, headers: true)
row = csv_data.find { |record| record['email'] == legacy_country_contact.email }
expect(row['country_code']).to eq('US')
end
it 'bulk loads labels while exporting contacts' do
create(:label, account: account, title: 'vip')
create(:label, account: account, title: 'support')
-36
View File
@@ -93,42 +93,6 @@ RSpec.describe Contact do
end
end
describe '#canonical_country_code' do
it 'prefers the contact country_code column when it has a valid country code' do
contact = create(:contact, additional_attributes: { country_code: 'IN', country: 'India' })
contact[:country_code] = 'US'
expect(contact.canonical_country_code).to eq('US')
expect(contact.canonical_country_name).to eq('United States')
end
it 'falls back to additional_attributes country_code' do
contact = create(:contact, additional_attributes: { country_code: 'in' })
expect(contact.canonical_country_code).to eq('IN')
expect(contact.canonical_country_name).to eq('India')
end
it 'normalizes legacy country names from additional_attributes country' do
contact = create(:contact, additional_attributes: { country: 'United States' })
expect(contact.canonical_country_code).to eq('US')
expect(contact.canonical_country_name).to eq('United States')
end
end
describe '#additional_attributes_with_canonical_country' do
it 'returns additional attributes with normalized country values without persisting them' do
contact = create(:contact, additional_attributes: { country: 'United States' })
expect(contact.additional_attributes_with_canonical_country).to include(
'country_code' => 'US',
'country' => 'United States'
)
expect(contact.reload.additional_attributes).not_to include('country_code')
end
end
context 'when a contact is created' do
it 'has contact type "visitor" by default' do
contact = create(:contact)
@@ -48,16 +48,6 @@ RSpec.describe LlmFormatter::ContactLlmFormatter do
end
end
context 'when contact has legacy country data' do
before do
contact.update!(additional_attributes: { country: 'United States' })
end
it 'uses the canonical country code' do
expect(formatter.format).to include('Country Code: US')
end
end
context 'when contact has custom attributes' do
let!(:custom_attribute) do
create(:custom_attribute_definition, account: account, attribute_model: 'contact_attribute', attribute_display_name: 'Company')
-3
View File
@@ -11,9 +11,6 @@ properties:
availability_status:
type: string
description: The availability status of the contact
country_code:
type: string
description: The normalized ISO country code of the contact
email:
type: string
description: The email address of the contact