| 1 | // Paid posts: the encryption key auto-generates (no env needed). This file runs
|
|---|
| 2 | // in its own process (node --test), so deleting PAID_SECRET here doesn't affect
|
|---|
| 3 | // the other paid tests, which set it.
|
|---|
| 4 | import { test } from 'node:test';
|
|---|
| 5 | import assert from 'node:assert/strict';
|
|---|
| 6 | import fs from 'fs';
|
|---|
| 7 | import os from 'os';
|
|---|
| 8 | import path from 'path';
|
|---|
| 9 |
|
|---|
| 10 | delete process.env.PAID_SECRET; // force the file path
|
|---|
| 11 | const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'paidkey-'));
|
|---|
| 12 | process.env.DATABASE_PATH = path.join(dir, 'database.sqlite');
|
|---|
| 13 |
|
|---|
| 14 | const { encrypt, decrypt, cryptoBoxReady } = await import('../src/services/CryptoBox.js');
|
|---|
| 15 | const keyFile = path.join(dir, '.paid-secret');
|
|---|
| 16 |
|
|---|
| 17 | test('without PAID_SECRET, a key file is generated and the box is ready', () => {
|
|---|
| 18 | assert.equal(cryptoBoxReady(), true);
|
|---|
| 19 | assert.ok(fs.existsSync(keyFile), 'key file was written next to the database');
|
|---|
| 20 | if (process.platform !== 'win32') {
|
|---|
| 21 | assert.equal(fs.statSync(keyFile).mode & 0o777, 0o600, 'key file is 0600');
|
|---|
| 22 | }
|
|---|
| 23 | });
|
|---|
| 24 |
|
|---|
| 25 | test('encrypt/decrypt roundtrips with the generated key', () => {
|
|---|
| 26 | const enc = encrypt('patreon-creator-token');
|
|---|
| 27 | assert.notEqual(enc, 'patreon-creator-token');
|
|---|
| 28 | assert.equal(decrypt(enc), 'patreon-creator-token');
|
|---|
| 29 | });
|
|---|
| 30 |
|
|---|
| 31 | test('the generated key persists (a second read reuses the same file)', () => {
|
|---|
| 32 | const first = fs.readFileSync(keyFile, 'utf8');
|
|---|
| 33 | assert.ok(first.length >= 16);
|
|---|
| 34 | // Encrypt now, and decrypting still works: the same persisted key is used.
|
|---|
| 35 | const enc = encrypt('x');
|
|---|
| 36 | assert.equal(fs.readFileSync(keyFile, 'utf8'), first, 'key file unchanged');
|
|---|
| 37 | assert.equal(decrypt(enc), 'x');
|
|---|
| 38 | });
|
|---|