Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

2.1 KB
Raw Blame
import { createPrivateTextCipher } from './crypto';

const cipher = createPrivateTextCipher('ab'.repeat(32));
const binding = ['owner', 'tenant-a', 'message-1'];

// Generated by seal() before authTagLength was specified.
const legacyEnvelope = 'v1:68pebNDOtCw9330w:gkL8WAsny7wcvwxHF+BTfA==:xZCEA00xZU/kYxx7BNAI';

describe('private text cipher', () => {
  it.each(['', 'private message', '秘密 🔐'])('round-trips %j with a 16-byte tag', (text) => {
    const envelope = cipher.seal(text, binding);
    expect(Buffer.from(envelope.split(':')[2], 'base64')).toHaveLength(16);
    expect(cipher.open(envelope, binding)).toBe(text);
  });

  it('opens existing envelopes with full-length tags', () => {
    expect(cipher.open(legacyEnvelope, binding)).toBe('private message');
  });

  it.each(Array.from({ length: 16 }, (_, length) => length))(
    'rejects a tag truncated to %i bytes',
    (length) => {
      const [version, nonce, tag, ciphertext] = cipher.seal('private message', binding).split(':');
      const truncated = Buffer.from(tag, 'base64').subarray(0, length).toString('base64');
      const envelope = [version, nonce, truncated, ciphertext].join(':');
      expect(() => cipher.open(envelope, binding)).toThrow('Private message text is unavailable.');
    },
  );

  it.each([17, 32])('rejects an oversized %i-byte tag', (length) => {
    const [version, nonce, tag, ciphertext] = cipher.seal('private message', binding).split(':');
    const extended = Buffer.concat([
      Buffer.from(tag, 'base64'),
      Buffer.alloc(length - 16),
    ]).toString('base64');
    const envelope = [version, nonce, extended, ciphertext].join(':');
    expect(() => cipher.open(envelope, binding)).toThrow('Private message text is unavailable.');
  });

  it('rejects a modified full-length tag', () => {
    const [version, nonce, tag, ciphertext] = cipher.seal('private message', binding).split(':');
    const modified = Buffer.from(tag, 'base64');
    modified[0] ^= 1;
    const envelope = [version, nonce, modified.toString('base64'), ciphertext].join(':');
    expect(() => cipher.open(envelope, binding)).toThrow('Private message text is unavailable.');
  });
});