Dev.to Security 🔐 Cybersecurity 👁 0 📖 13 min read

Character.AI Put User Chats Up for Sale. Swap Names for Tokens Before Your LLM Call

Book: Hexagonal Architecture in Python Companion code: hexagonal-python-examples — every listing from the book, free on GitHub My project: Hermes IDE | GitHub — an IDE for developers who ship with Claude Code and othe

Character.AI Put User Chats Up for Sale. Swap Names for Tokens Before Your LLM Call

Chat histories from more than 21 million US accounts are part of a bankruptcy sale. That figure comes from California's attorney general, one of a coalition of 42 attorneys general asking the court to reject the proposed sale of Character.AI's data. Their objection to the terms: the buyer would not have to follow the company's privacy policies or honour users' requests to opt out or delete their data.

The company's FAQ tells users their information "continues to be protected under our Privacy Policy". In an October 27 filing, it also said that the same policy already permitted the sale and transfer of user data. On November 17, with the company's consent, the judge ordered a privacy ombudsman, whose report is due at least seven days before any sale hearing. Coverage from November 27 still has the auction on December 1, and the states' objections go to a sale hearing after it. This was written on November 29, before either one, so check for a ruling if you read it later.

Character.AI is a consumer app, and your LLM vendor's contract is different. Still, the question carries over: what does the vendor hold about your customers if the company behind the promise disappears? You can send less, starting today. The names, emails and order ids you can detect stay in your process while the model works with stand-in tokens like PERSON1X7F3A9C, and your use cases don't have to change.

The use case asks for a reply and nothing else

Start with the port. Reply carries text and tool calls, and ReplyUnusable is how any adapter says "don't show this to anyone."

# app/ports.py
from dataclasses import dataclass
from typing import Protocol

@dataclass(frozen=True)
class ToolCall:
    name: str
    arguments: str  # JSON text, as vendors return it

@dataclass(frozen=True)
class Reply:
    text: str
    tool_calls: tuple[ToolCall, ...] = ()

class ReplyUnusable(Exception):
    """The reply cannot be shown or acted on."""

class LLM(Protocol):
    async def complete(self, prompt: str) -> Reply: ...
# app/draft_reply.py
from app.ports import LLM, Reply

class DraftReply:
    def __init__(self, llm: LLM) -> None:
        self._llm = llm

    async def __call__(self, ticket: str) -> Reply:
        return await self._llm.complete(
            f"Draft a reply to this ticket:\n{ticket}"
        )

DraftReply writes prompts with real names in them. That is fine, because nothing has left the process yet. Put the masking in an adapter that implements LLM and wraps the real one. The use case keeps working with names, and the vendor adapter underneath gets the masked prompt.

Detectors find the values, a vault swaps them

Finding personal data and replacing it are separate jobs. Detectors only report spans:

# adapters/detectors.py
import re
from collections.abc import Iterable
from dataclasses import dataclass
from typing import Protocol

@dataclass(frozen=True)
class Span:
    start: int
    end: int
    kind: str  # letters only: PERSON, EMAIL, ORDER

class Detector(Protocol):
    def find(self, text: str) -> list[Span]: ...

Patterns cover anything with a shape, and KnownValues covers what your database already knows, such as the customer on this ticket.

# adapters/detectors.py, continued
class Pattern:
    def __init__(self, kind: str, regex: str, flags=0) -> None:
        self._kind = kind
        self._rx = re.compile(regex, flags)

    def find(self, text: str) -> list[Span]:
        return [
            Span(m.start(), m.end(), self._kind)
            for m in self._rx.finditer(text)
        ]

class KnownValues:
    def __init__(self, kind: str, values: Iterable[str]) -> None:
        self._patterns = [
            Pattern(
                kind,
                rf"(?<!\w){re.escape(v)}(?!\w)",
                re.IGNORECASE,
            )
            for v in values
            if v.strip()
        ]

    def find(self, text: str) -> list[Span]:
        return [s for p in self._patterns for s in p.find(text)]

EMAIL = Pattern("EMAIL", r"[\w.+-]+@[\w-]+(?:\.[\w-]+)+")
ORDER = Pattern("ORDER", r"\bORD-\d+\b", re.IGNORECASE)

Two detectors can report overlapping spans. Those get merged, because picking one would leave the end of the other in clear text.

# adapters/vault.py
import re
import secrets
from dataclasses import replace

from adapters.detectors import Span
from app.ports import ReplyUnusable

def merge(spans: list[Span]) -> list[Span]:
    out: list[Span] = []
    for s in sorted(spans, key=lambda s: (s.start, -s.end)):
        if out and s.start < out[-1].end:
            end = max(out[-1].end, s.end)
            out[-1] = replace(out[-1], end=end)
        else:
            out.append(s)
    return out

The vault holds the mapping, in memory, for one conversation. A token like PERSON1X7F3A9C is a kind, a counter, and a random tail shared by the whole conversation.

# adapters/vault.py, continued
class Vault:
    def __init__(self, nonce: str | None = None) -> None:
        self._tail = "X" + (nonce or secrets.token_hex(3)).upper()
        self._tokens: dict[tuple[str, str], str] = {}
        self._values: dict[str, str] = {}
        self._stems: set[str] = set()
        self._rx = re.compile(
            r"(?<![a-z0-9])([a-z]+)[ _-]?(\d+)[ _-]?"
            + self._tail
            + r"(?![a-z0-9])",
            re.IGNORECASE,
        )

    @property
    def note(self) -> str:
        return (
            f"\n\nCodes ending in {self._tail} stand for "
            "private values. Copy them character for character."
        )

    def hide(self, text: str, spans: list[Span]) -> str:
        out, pos = [], 0
        for s in merge(spans):
            value = text[s.start:s.end]
            out.append(text[pos:s.start])
            out.append(self._token(s.kind, value))
            pos = s.end
        out.append(text[pos:])
        return "".join(out)

    def restore(self, text: str) -> str:
        rest = self._rx.sub(" ", text).upper()
        if self._tail in rest or any(
            stem in rest for stem in self._stems
        ):
            raise ReplyUnusable("mangled token")
        return self._rx.sub(self._value, text)

    def _token(self, kind: str, value: str) -> str:
        key = (kind, value)
        if key not in self._tokens:
            n = 1 + sum(k == kind for k, _ in self._tokens)
            self._stems.add(f"{kind}{n}")
            token = f"{kind}{n}{self._tail}"
            self._tokens[key] = token
            self._values[token] = value
        return self._tokens[key]

    def _value(self, m: re.Match[str]) -> str:
        token = f"{m[1]}{m[2]}{self._tail}".upper()
        if token not in self._values:
            raise ReplyUnusable("unknown token")
        return self._values[token]

Tokens use only letters and digits, so they need no escaping in JSON or Markdown. Restoring uses a function as the replacement in re.sub, so a backslash in a real value is never read as a regex escape.

The exceptions name the problem and never include the text. An error message with the reply in it would put the data in your logs.

A black silhouette leaning out of a doorway in a burnt-orange wall, holding out a blank tag beside a locked black box
The tag is handed out. The box stays locked.

The adapter: mask, call, restore

# adapters/pseudonymizing.py
import json
from collections.abc import Collection, Sequence
from dataclasses import replace
from typing import Any

from adapters.detectors import Detector
from adapters.vault import Vault
from app.ports import LLM, Reply, ReplyUnusable, ToolCall

class PseudonymizingLLM:
    def __init__(
        self,
        inner: LLM,
        vault: Vault,
        detectors: Sequence[Detector],
        local_tools: Collection[str] = (),
    ) -> None:
        self._inner = inner
        self._vault = vault
        self._detectors = detectors
        self._local_tools = local_tools

    async def complete(self, prompt: str) -> Reply:
        spans = [
            s for d in self._detectors for s in d.find(prompt)
        ]
        masked = self._vault.hide(prompt, spans)
        if spans:
            masked += self._vault.note
        reply = await self._inner.complete(masked)
        return Reply(
            text=self._vault.restore(reply.text),
            tool_calls=tuple(
                self._restore_call(c) for c in reply.tool_calls
            ),
        )

    def _restore_call(self, call: ToolCall) -> ToolCall:
        if call.name not in self._local_tools:
            return call
        try:
            args = json.loads(call.arguments)
        except json.JSONDecodeError:
            raise ReplyUnusable("bad tool JSON") from None
        return replace(
            call, arguments=json.dumps(self._walk(args))
        )

    def _walk(self, node: Any) -> Any:
        if isinstance(node, str):
            return self._vault.restore(node)
        if isinstance(node, list):
            return [self._walk(x) for x in node]
        if isinstance(node, dict):
            return {
                self._walk(k): self._walk(v)
                for k, v in node.items()
            }
        return node

local_tools is the line I'd defend hardest in review. If you restore tokens in every tool call, a prompt injection can tell the model to put EMAIL1X7F3A9C in a URL, and your adapter will fill in the real address on the way out. The model leaks a value it never saw. Restore only for tools whose effect stays inside your own system, such as saving a draft for a person to check. A send_email tool runs in your process and still delivers wherever the model says, so it gets the token unless your code picks the recipient and a person approves the body.

Test that caught values never reach the vendor

The fake inner adapter records every prompt it receives. Most of these pytest tests go through DraftReply, which shows the use case needs no changes.

# tests/test_pseudonymizing.py
import asyncio
import json

import pytest

from adapters.detectors import EMAIL, ORDER, KnownValues
from adapters.pseudonymizing import PseudonymizingLLM
from adapters.vault import Vault
from app.draft_reply import DraftReply
from app.ports import Reply, ReplyUnusable, ToolCall

TICKET = "Alice Moreno ([email protected]): where is ORD-10442?"
SECRETS = ["Alice", "Moreno", "[email protected]", "ORD-10442"]

class RecordingLLM:
    def __init__(self, reply: Reply) -> None:
        self.reply = reply
        self.prompts: list[str] = []

    async def complete(self, prompt: str) -> Reply:
        self.prompts.append(prompt)
        return self.reply

ask wires the adapter around the fake, with a fixed nonce so the tests can name tokens:

# tests/test_pseudonymizing.py, continued
def ask(inner, ticket=TICKET, name="Alice Moreno", extra=()):
    llm = PseudonymizingLLM(
        inner,
        Vault(nonce="7F3A9C"),
        [EMAIL, ORDER, KnownValues("PERSON", [name]), *extra],
        local_tools={"save_draft"},
    )
    return asyncio.run(DraftReply(llm)(ticket))

def test_caught_values_never_reach_the_inner_adapter():
    inner = RecordingLLM(
        Reply("Hi PERSON1X7F3A9C, ORDER1X7F3A9C ships today.")
    )
    reply = ask(inner)

    sent = inner.prompts[0].lower()
    assert all(s.lower() not in sent for s in SECRETS)
    assert reply.text == "Hi Alice Moreno, ORD-10442 ships today."

def test_same_value_gets_the_same_token_across_calls():
    vault = Vault(nonce="7F3A9C")
    first = vault.hide("ORD-1", ORDER.find("ORD-1"))
    again = vault.hide("ORD-1", ORDER.find("ORD-1"))
    other = vault.hide("ORD-2", ORDER.find("ORD-2"))
    assert first == again != other

That is the happy path. The next tests cover three ways masking breaks.

The reply mangles a token. A model can change the case, add a space, or cut the end off. The vault repairs small changes and raises ReplyUnusable on any damaged or invented token it can recognise.

@pytest.mark.parametrize("token", [
    "person1x7f3a9c",
    "PERSON 1 X7F3A9C",
    "PERSON_1_X7F3A9C",
])
def test_small_changes_are_repaired(token):
    reply = ask(RecordingLLM(Reply(f"Hi {token}.")))
    assert reply.text == "Hi Alice Moreno."

@pytest.mark.parametrize("token", [
    "PERSON1",          # tail lost
    "PERSON1X7F3A",     # cut short
    "PERSONX7F3A9C",    # counter lost
    "PERSON9X7F3A9C",   # never issued
])
def test_damaged_tokens_are_refused(token):
    with pytest.raises(ReplyUnusable):
        ask(RecordingLLM(Reply(f"Hi {token}.")))

The token sits inside a JSON argument. Replacing on the raw string fails twice. A name with quotes in it breaks the JSON, and an escaped newline glues an n to the front of the token (\nPERSON1…), so it reads as a different token. Parsing first avoids both.

def test_tokens_in_json_arguments():
    args = {
        "to": "EMAIL1X7F3A9C",
        "body": "Dear\nPERSON1X7F3A9C",
    }
    call = ToolCall("save_draft", json.dumps(args))
    name = 'Alice "Al" Moreno'
    reply = ask(
        RecordingLLM(Reply("", (call,))),
        ticket=f"{name} wrote from [email protected]",
        name=name,
    )
    assert json.loads(reply.tool_calls[0].arguments) == {
        "to": "[email protected]",
        "body": f"Dear\n{name}",
    }

def test_external_tools_only_get_the_token():
    call = ToolCall("web_search", '{"q": "EMAIL1X7F3A9C"}')
    reply = ask(RecordingLLM(Reply("", (call,))))
    assert reply.tool_calls == (call,)

The name is in free text. "My neighbour Priya signed for it" matches no pattern and no record in your database. This test records the hole:

def test_free_text_names_need_a_detector():
    text = "My neighbour Priya signed for ORD-10442."

    bare = RecordingLLM(Reply("ok"))
    ask(bare, ticket=text)
    assert "Priya" in bare.prompts[0]  # leaks

    ner = KnownValues("PERSON", ["Priya"])  # stand-in
    guarded = RecordingLLM(Reply("ok"))
    ask(guarded, ticket=text, extra=[ner])
    assert "Priya" not in guarded.prompts[0]

Run it with the project root on pytest's path (pythonpath = . under [pytest] in pytest.ini).

A burnt-orange sieve catching round and square black shapes while one small irregular shape slips through a gap in the mesh
Patterns catch what has a shape. A name in a sentence has none.

Plug in a real detector, per conversation

Presidio is an open source toolkit that detects personal data, and its analyzer has a PERSON entity. Run pip install presidio_analyzer, then python -m spacy download en_core_web_lg for the spaCy model (install docs), and a small wrapper fits it to the Detector protocol:

# adapters/presidio_names.py
from presidio_analyzer import AnalyzerEngine

from adapters.detectors import Span

class PresidioNames:
    def __init__(self, engine: AnalyzerEngine) -> None:
        self._engine = engine

    def find(self, text: str) -> list[Span]:
        hits = self._engine.analyze(
            text=text, entities=["PERSON"], language="en"
        )
        return [Span(h.start, h.end, "PERSON") for h in hits]
# main.py
from presidio_analyzer import AnalyzerEngine

from adapters.detectors import EMAIL, ORDER, KnownValues
from adapters.presidio_names import PresidioNames
from adapters.pseudonymizing import PseudonymizingLLM
from adapters.vault import Vault
from app.draft_reply import DraftReply
from app.ports import LLM

NAMES = PresidioNames(AnalyzerEngine())

def draft_reply_for(vendor: LLM, names: list[str]) -> DraftReply:
    known = KnownValues("PERSON", names)
    return DraftReply(
        PseudonymizingLLM(
            vendor,
            Vault(),
            [EMAIL, ORDER, known, NAMES],
            local_tools={"save_draft"},
        )
    )

Load the engine once, but create a vault for every conversation and keep it for all of that conversation's turns. A vault shared between customers would let one customer's reply restore another customer's name. If you also have a logging or fallback adapter, wrap it on the inside, so it sees the same masked prompt the vendor does.

Pass first and last names as separate entries in names if customers sign with one of them. The detector's accuracy is your ceiling: Presidio's own docs say "there is no guarantee that Presidio will find all sensitive information". Analysis is also CPU work inside an async call, so move it to a thread if it shows up in your latency.

This is pseudonymisation, so keep treating it as personal data

You hold the mapping, so the data isn't anonymous in your hands. GDPR Article 4(5) calls the technique pseudonymisation and expects the extra information to be kept separately and protected. A prompt with a missed name in it doesn't meet that definition. The UK regulator says: "It is not a way of transforming personal data to the extent the law no longer applies." Your data processing agreement and your retention settings still matter. This is an engineering starting point and none of it is legal advice.

Some limits to write in the design doc:

  • The rest of the sentence still goes out. "The only vet in our village" identifies someone with no name in it.
  • A reply that says "Person 1" has lost the tail and the shape, and the residue check won't catch it.
  • The reply text is always restored, so a token inside a link or image URL becomes the real value. Treat it as untrusted output: if you render it as Markdown or HTML, block remote images and strip model-written links first.
  • Detection is per mention. A name caught in one turn and missed in the next goes out in clear text, so feed the names you have already found back in as KnownValues.
  • Opaque tokens can cost quality. The LOPSIDED paper argues that earlier approaches often degrade responses, and swaps in semantically consistent pseudonyms instead. The trade is that a realistic fake name is harder to spot when the model gets it wrong.
  • Nothing here recalls what you already sent. Images, attachments and embedding calls need their own adapter.
  • Lose the process and you lose the mapping. If conversations outlive it, the vault needs storage, and that store is personal data too.

If your vendor's prompt logs change hands one day, every mention your detectors caught is in there only as a token like PERSON1X7F3A9C. The mapping stayed with you.

If this was useful

The masking went in without an edit to DraftReply, because the use case depends on a port. Hexagonal Architecture in Python takes one async FastAPI and SQLAlchemy 2 service, writes it five ways (Hexagonal, Clean, Onion, layered and vertical slice) and measures what each one costs. AI isn't its subject, but the boundary is the same idea. If you want a core you can wrap, swap and test without the outside world, every listing runs from the free companion repo.

Hexagonal Architecture in Python by Gabriel Anhaia

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.