Sensitive Data Protection

Understand sensitive data exposure in AI applications and learn data minimization, masking, output controls, and safe logging.

🎯 Introduction

AI applications can expose private user information and internal data when calling models, retrieving knowledge, or logging requests. This article explains how to identify sensitive data and protect it before sending it to a model, returning it to a user, or writing it to logs, so unnecessary information is not sent to models or disclosed to unauthorized people.


🧱 What is sensitive data?

Sensitive data is information that could harm an individual or organization if accessed, used, or disclosed without authorization.

Data typeCommon examples
Identity and contact informationNational ID numbers, phone numbers, email addresses
Authentication credentialsAPI keys, passwords, access tokens
Financial and health dataBank accounts, transactions, medical records
Internal business dataUnpublished contracts, quotes, customer records

Sensitivity depends on context. A public support email address may be appropriate in an answer, while a customer's private email address should not be disclosed freely.

Where data can be exposed in AI applications

Processing stagePotential problem
Model inputSending complete user profiles or credentials to a model
Knowledge bases and toolsRetrieving or returning data the current user cannot access
Model outputReturning sensitive context data to the user
Logs and conversation storageSaving complete requests, answers, or authentication information

🧰 Protect model input

Data minimization

Data minimization means providing only the data needed for the current task, rather than sending an entire object returned by a database query to the model.

The following experiment uses fictional data and Node.js 22.x. It requires no third-party dependencies or model API calls.

Create input.mjs:

const order = {
    id: 'ORD-1001',
    status: 'Shipped',
    product: 'Mechanical keyboard',
    phone: '13800001234',
    address: '1 Example Road',
};

function createModelInput(order) {
    // Select only the fields needed to check shipping status
    return {
        id: order.id,
        status: order.status,
    };
}

const modelInput = createModelInput(order);

console.log(JSON.stringify(modelInput));

Run:

node input.mjs

Output:

{"id":"ORD-1001","status":"Shipped"}

Building model input from an allowlist of fields is safer than copying the entire object and deleting sensitive fields: new database fields will not automatically enter the model's context.

When calling the model, serialize modelInput and pass it as task data. Do not pass the original order object.

Data masking

When a task needs some sensitive information, hide the parts it does not need. For example, keep only the last four digits when verifying a phone number's suffix.

Original dataProcessed valueMethod
13800001234138****1234Masking
138000012341234Truncation
Customer nameCUSTOMER_001Identifier substitution (protect the mapping)

Create mask.mjs:

function maskPhone(phone) {
    // Accept only 11 digits; never return the original value on invalid input
    if (typeof phone !== 'string' || !/^\d{11}$/.test(phone)) {
        return '[Hidden]';
    }

    return `${phone.slice(0, 3)}****${phone.slice(-4)}`;
}

console.log(maskPhone('13800001234'));
console.log(maskPhone('unknown'));

Run node mask.mjs. Output:

138****1234
[Hidden]

Choose which parts to retain based on the task. If only the suffix is needed, pass the last four digits directly; there is no need to retain the first three.

Masking is not anonymization. Partial numbers and order identifiers may still be linked with other data to identify an individual.

Credentials and access permissions

Manage API keys, passwords, and other credentials on the server. Do not send them to the model in prompts or tool results. The API key used to call OpenAI authenticates the SDK; it is not model input.

For RAG and tool calls, check data access permissions on the server using the signed-in user's identity, then pass only permitted data to the model. For example, verify order ownership rather than reading an order solely from a model-generated order ID. Masking cannot replace access checks.


🛠 Protect model output

Before returning an answer to the user, check whether it contains data that must not be disclosed.

Create output.mjs and use simulated model answers to verify the blocking logic:

function protectOutput(text) {
    // Demo rule: detect an uninterrupted 11-digit mobile phone number
    const phonePattern = /(?<!\d)1[3-9]\d{9}(?!\d)/;

    if (phonePattern.test(text)) {
        return 'This answer contains restricted information and cannot be displayed.';
    }

    return text;
}

console.log(protectOutput('Your order has shipped.'));
console.log(protectOutput('Contact number: 13800001234'));

Run node output.mjs. Output:

Your order has shipped.
This answer contains restricted information and cannot be displayed.

Streaming output needs special care: sensitive data may span multiple chunks, so checking chunks individually can miss it. If detection requires the complete answer, buffer it, check it, and then send it. This sacrifices real-time output.

Regular expressions only detect specific formats. They cannot reliably identify all sensitive information, such as numbers containing spaces or internal business data. Output detection is an additional safeguard and cannot replace input-side data minimization and permission checks.

🧰 Protect logs and storage

Raw requests, error objects, and conversation history may contain sensitive data and should not be logged directly.

Create log.mjs:

const request = {
    id: 'req-001',
    model: 'gpt-4o-mini',
    prompt: 'Contact number: 13800001234',
    durationMs: 820,
    status: 'success',
};

// Log only fields needed to troubleshoot the request
const log = {
    requestId: request.id,
    model: request.model,
    durationMs: request.durationMs,
    status: request.status,
};

console.log(JSON.stringify(log));

Run node log.mjs. Output:

{"requestId":"req-001","model":"gpt-4o-mini","durationMs":820,"status":"success"}

In production, restrict access to logs and conversation records, set retention periods that fit business requirements, and delete data when it is no longer needed. If raw content must be retained, use appropriate encryption and access controls rather than keeping it forever by default.

When using a third-party model service, also review the relevant endpoint's policies on retention, training use, and storage location. Transport encryption protects data in transit; it does not prevent the provider from processing the data it receives.


❓ Questions and answers

Q1: Can a hashed phone number be published as anonymous data?

No. Phone numbers have a limited range, so ordinary hashes may be matched through enumeration. Matching hashes can also link multiple records. Whether an individual can be identified depends on the processing method and other available data.


🧪 Exercise

Modify input.mjs so the model input supports checking an order's phone suffix: keep id and status, and add phoneLast4 containing the last four digits. Use node:assert/strict to verify that the output contains exactly these three fields, and that neither the complete phone number nor the address enters the model input.


🎉 You have learned the basics of protecting sensitive data in AI applications!