Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion packages/cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,10 @@ Trust ladder: T0 read/preview, T2 emit (requires `--yes`), T3 void (requires

Idempotency: every emit is keyed by `RUC-tipo-serie-numero`. Re-running with the
same key returns the cached CDR without re-submitting to SUNAT. Audit log lives
in `~/.sunat/audit/YYYY-MM-DD.jsonl` (two-phase: pending → success/error).
in `~/.sunat/audit/YYYY-MM.jsonl` (two-phase: pending → success/error). Older
months can be compacted into `~/.sunat/audit/archive/YYYY-MM.jsonl.gz` with
`sunat-cli audit compact`, and archived months can be removed manually with
`sunat-cli audit prune --before YYYY-MM`.

Full shaping rationale + recon dossier + SUNAT debugging notes:
`src/commands/cpe/RESEARCH.md`.
Expand Down
12 changes: 7 additions & 5 deletions packages/cli/bin/sunat.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
#!/usr/bin/env bun
import { Command } from "commander";
import { createRheCommand } from "../src/commands/rhe/index.ts";
import { createApiCommand } from "../src/commands/api/index.ts";
import { createAuditCommand } from "../src/commands/audit.ts";
import { createCpeCommand } from "../src/commands/cpe/index.ts";
import { createF616Command } from "../src/commands/f616/index.ts";
import { createLoginCommand } from "../src/commands/login.ts";
import { createWhoamiCommand } from "../src/commands/whoami.ts";
import { createSchemaCommand } from "../src/commands/schema.ts";
import { createApiCommand } from "../src/commands/api/index.ts";
import { createLukeaCommand } from "../src/commands/lukea/index.ts";
import { createCpeCommand } from "../src/commands/cpe/index.ts";
import { createPadronCommand } from "../src/commands/padron/index.ts";
import { createRheCommand } from "../src/commands/rhe/index.ts";
import { createSchemaCommand } from "../src/commands/schema.ts";
import { createSireCommand } from "../src/commands/sire/index.ts";
import { createTipoCambioCommand } from "../src/commands/tipo-cambio.ts";
import { createWhoamiCommand } from "../src/commands/whoami.ts";

const program = new Command();

Expand All @@ -37,5 +38,6 @@ program.addCommand(createCpeCommand());
program.addCommand(createPadronCommand());
program.addCommand(createSireCommand());
program.addCommand(createTipoCambioCommand());
program.addCommand(createAuditCommand());

program.parse();
3 changes: 1 addition & 2 deletions packages/cli/biome.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
{
"$schema": "https://biomejs.dev/schemas/2.0.0/schema.json",
"organizeImports": { "enabled": true },
"$schema": "https://biomejs.dev/schemas/2.4.14/schema.json",
"linter": { "enabled": true, "rules": { "recommended": true } },
"formatter": { "enabled": true, "indentStyle": "tab", "lineWidth": 120 }
}
1 change: 1 addition & 0 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
"yazl": "^3.3.1"
},
"devDependencies": {
"@biomejs/biome": "^2.4.14",
"@types/bun": "latest",
"@types/node-forge": "^1.3.14",
"@types/yauzl": "^2.10.3",
Expand Down
115 changes: 115 additions & 0 deletions packages/cli/src/commands/audit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import { Command } from "commander";
import {
archivedAuditRecoveryPath,
compactAuditLogs,
DEFAULT_AUTO_COMPACT_AFTER_MONTHS,
DEFAULT_RECOMMENDED_ARCHIVE_MONTHS,
listArchivedAuditMonths,
pruneArchivedAuditLogs,
} from "../data/audit.ts";
import { output, outputError } from "../utils/output.ts";

type Format = "json" | "table" | "auto";

function getFormat(cmd: Command): Format {
let parent: Command | null = cmd;
while (parent) {
const opts = parent.opts();
if (opts.output) return opts.output as Format;
parent = parent.parent;
}
return "auto";
}

function parseMonths(value: string): number {
const months = Number(value);
if (!Number.isInteger(months) || months < 0)
throw new Error(`Invalid months: "${value}". Expected a non-negative integer`);
return months;
}

export function createAuditCommand(): Command {
const audit = new Command("audit").description("Manage local audit log rotation and archives.");

audit
.command("compact")
.description("Compress active audit months older than the retention window into ~/.sunat/audit/archive.")
.option(
"--older-than-months <n>",
`Compact months with age >= n. Default: ${DEFAULT_AUTO_COMPACT_AFTER_MONTHS}`,
String(DEFAULT_AUTO_COMPACT_AFTER_MONTHS),
)
.action((opts, cmd) => {
const format = getFormat(cmd);
try {
const olderThanMonths = parseMonths(opts.olderThanMonths);
const result = compactAuditLogs({ olderThanMonths });
const archivedMonths = listArchivedAuditMonths();
const json = {
success: true,
policy: {
autoCompactAfterMonths: DEFAULT_AUTO_COMPACT_AFTER_MONTHS,
recommendedArchiveMonths: DEFAULT_RECOMMENDED_ARCHIVE_MONTHS,
autoDelete: false,
},
compactedMonths: result.compactedMonths,
compactedFiles: result.compactedFiles,
archivePaths: result.archivePaths,
skippedMonths: result.skippedMonths,
archivedMonths,
recovery: result.compactedMonths.map((month) => ({
month,
archivePath: archivedAuditRecoveryPath(month),
command: `gunzip -c ${archivedAuditRecoveryPath(month)} > ~/.sunat/audit/${month}.jsonl`,
})),
};
output(format, {
json,
table: {
headers: ["Month", "Archive", "Recovery"],
rows:
result.compactedMonths.length > 0
? result.compactedMonths.map((month) => [
month,
archivedAuditRecoveryPath(month),
`gunzip -c .../${month}.jsonl.gz > ~/.sunat/audit/${month}.jsonl`,
])
: [["-", "-", "no months compacted"]],
},
});
} catch (err) {
outputError(err instanceof Error ? err.message : String(err), format);
}
});

audit
.command("prune")
.description("Delete archived audit months before a cutoff. This never runs automatically.")
.requiredOption("--before <YYYY-MM>", "Delete archived months strictly before this month")
.action((opts, cmd) => {
const format = getFormat(cmd);
try {
const result = pruneArchivedAuditLogs(opts.before);
output(format, {
json: {
success: true,
before: opts.before,
prunedMonths: result.prunedMonths,
prunedPaths: result.prunedPaths,
autoDelete: false,
},
table: {
headers: ["Month", "Archive"],
rows:
result.prunedMonths.length > 0
? result.prunedMonths.map((month, i) => [month, result.prunedPaths[i]])
: [["-", "no archived months pruned"]],
},
});
} catch (err) {
outputError(err instanceof Error ? err.message : String(err), format);
}
});

return audit;
}
28 changes: 8 additions & 20 deletions packages/cli/src/cpe/idempotency.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,7 @@
* operator can investigate (likely a crash mid-submit).
*/

import { existsSync, readFileSync, readdirSync } from "fs";
import { join } from "path";
import { audit } from "../data/audit.ts";
import { paths } from "../data/config.ts";
import { audit, iterateActiveAuditEntries } from "../data/audit.ts";
import type { CpeResult } from "./drivers/types.ts";

export type CpeTipo = "01" | "03" | "07" | "08" | "09";
Expand Down Expand Up @@ -84,7 +81,12 @@ export function logPending(key: IdempotencyKey, command: string, args: Record<st
});
}

export function logSuccess(key: IdempotencyKey, command: string, args: Record<string, unknown>, result: CpeResult): void {
export function logSuccess(
key: IdempotencyKey,
command: string,
args: Record<string, unknown>,
result: CpeResult,
): void {
audit({
command,
args,
Expand All @@ -110,19 +112,5 @@ export function logFailure(key: IdempotencyKey, command: string, args: Record<st
}

function* iterateAudit(): Generator<AuditEntry> {
const dir = paths.auditDir;
if (!existsSync(dir)) return;
const files = readdirSync(dir).filter((f) => f.endsWith(".jsonl")).sort();
for (const file of files) {
const path = join(dir, file);
const content = readFileSync(path, "utf-8");
for (const line of content.split("\n")) {
if (!line.trim()) continue;
try {
yield JSON.parse(line) as AuditEntry;
} catch {
// skip malformed line
}
}
}
yield* iterateActiveAuditEntries();
}
Loading
Loading