@miguelmorales13/nestkit 0.26.0 → 0.29.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +69 -0
- package/dist/alerts/alert-on-failure.decorator.d.ts +5 -0
- package/dist/alerts/alert-sinks.d.ts +29 -0
- package/dist/alerts/alerts.module.d.ts +19 -0
- package/dist/alerts/alerts.options.d.ts +1 -0
- package/dist/alerts/alerts.service.d.ts +28 -0
- package/dist/alerts/alerts.types.d.ts +66 -0
- package/dist/alerts/index.cjs +276 -0
- package/dist/alerts/index.d.ts +10 -0
- package/dist/alerts/index.js +276 -0
- package/dist/alerts/logger-with-alerts.d.ts +18 -0
- package/dist/alerts/process-guards.d.ts +21 -0
- package/dist/alerts/runtime.d.ts +4 -0
- package/dist/audit/index.cjs +13 -13
- package/dist/audit/index.js +2 -2
- package/dist/auth/index.cjs +21 -21
- package/dist/auth/index.js +3 -3
- package/dist/auth/oauth/index.cjs +101 -101
- package/dist/auth/oauth/index.js +3 -3
- package/dist/bootstrap/apply-defaults.d.ts +9 -0
- package/dist/bootstrap/index.cjs +7 -6
- package/dist/bootstrap/index.js +6 -5
- package/dist/chunk-33KFVAUZ.cjs +151 -0
- package/dist/chunk-3TUMVLPJ.js +14 -0
- package/dist/{chunk-PA24P76K.js → chunk-45SW7FBE.js} +1 -1
- package/dist/{chunk-RF75KC63.cjs → chunk-47IYXZHW.cjs} +2 -2
- package/dist/{chunk-TUNDBBQF.js → chunk-4WWOKZIO.js} +4 -4
- package/dist/{chunk-2DUEQKOI.js → chunk-5LVGCTJ3.js} +4 -4
- package/dist/chunk-A6YGIZCQ.cjs +14 -0
- package/dist/chunk-A7FI6HXV.js +40 -0
- package/dist/chunk-CU4FUIVJ.cjs +8 -0
- package/dist/{chunk-FH5UNWWW.cjs → chunk-D35TBVRO.cjs} +4 -4
- package/dist/{chunk-4MGIQFAJ.js → chunk-D3DDJWUD.js} +5 -0
- package/dist/chunk-DVGPEBUL.js +8 -0
- package/dist/{chunk-VKOPDDCC.js → chunk-ENZ7LQRE.js} +1 -1
- package/dist/{chunk-3AUOOEQO.cjs → chunk-F77X4QUN.cjs} +2 -2
- package/dist/chunk-FBNV5X6C.js +61 -0
- package/dist/{chunk-APUFKA4K.cjs → chunk-FDZQCLLK.cjs} +6 -6
- package/dist/{chunk-DYHSOULW.js → chunk-IGSNB5BX.js} +1 -1
- package/dist/chunk-IVWPA6QH.cjs +90 -0
- package/dist/{chunk-LSDY6ETG.cjs → chunk-JJKGQNGD.cjs} +5 -5
- package/dist/{chunk-ALIKVFOV.cjs → chunk-JRFE7NSO.cjs} +12 -4
- package/dist/{chunk-HVHYZXBB.cjs → chunk-KNU5RN3O.cjs} +3 -3
- package/dist/{chunk-52IOOHNX.cjs → chunk-KQPJCVN3.cjs} +26 -26
- package/dist/chunk-LGFHLAY3.cjs +61 -0
- package/dist/{chunk-2REOCMUD.cjs → chunk-LRX7AMSS.cjs} +6 -1
- package/dist/chunk-LU3HO7B3.js +151 -0
- package/dist/{chunk-4PFAKLT3.js → chunk-MUWHGBIB.js} +1 -1
- package/dist/{chunk-ZJMLEP5H.js → chunk-NJYLQDB3.js} +1 -1
- package/dist/{chunk-IFNYRZP2.js → chunk-OSRH6KYZ.js} +4 -4
- package/dist/{chunk-6RAPVLJM.js → chunk-OTE77ONL.js} +1 -1
- package/dist/chunk-UDACUMLO.cjs +40 -0
- package/dist/{chunk-PFHHLB7B.js → chunk-UGAAJRPO.js} +10 -2
- package/dist/{chunk-SPTDXUED.cjs → chunk-URLDTS2Q.cjs} +2 -2
- package/dist/{chunk-W2T2VFLC.cjs → chunk-VALDHJOO.cjs} +5 -5
- package/dist/chunk-WFCQDOSN.js +90 -0
- package/dist/consent/consent.interceptor.d.ts +20 -0
- package/dist/consent/consent.module.d.ts +25 -0
- package/dist/consent/consent.options.d.ts +30 -0
- package/dist/consent/consent.port.d.ts +17 -0
- package/dist/consent/consent.service.d.ts +44 -0
- package/dist/consent/guard/index.cjs +13 -0
- package/dist/consent/guard/index.d.ts +31 -0
- package/dist/consent/guard/index.js +13 -0
- package/dist/consent/index.cjs +271 -0
- package/dist/consent/index.d.ts +13 -0
- package/dist/consent/index.js +271 -0
- package/dist/consent/memory.store.d.ts +7 -0
- package/dist/consent/shared/index.cjs +11 -0
- package/dist/consent/shared/index.d.ts +19 -0
- package/dist/consent/shared/index.js +11 -0
- package/dist/consent/typeorm.store.d.ts +22 -0
- package/dist/crud/index.cjs +4 -4
- package/dist/crud/index.js +3 -3
- package/dist/database/postgres/index.cjs +3 -3
- package/dist/database/postgres/index.js +2 -2
- package/dist/database/supabase/index.cjs +3 -3
- package/dist/database/supabase/index.js +2 -2
- package/dist/database/typeorm/index.cjs +2 -2
- package/dist/database/typeorm/index.js +1 -1
- package/dist/devices/device-check.interceptor.d.ts +20 -0
- package/dist/devices/devices.module.d.ts +28 -0
- package/dist/devices/devices.options.d.ts +53 -0
- package/dist/devices/devices.port.d.ts +62 -0
- package/dist/devices/devices.service.d.ts +58 -0
- package/dist/devices/index.cjs +327 -0
- package/dist/devices/index.d.ts +8 -0
- package/dist/devices/index.js +327 -0
- package/dist/devices/memory.store.d.ts +12 -0
- package/dist/email/index.cjs +2 -2
- package/dist/email/index.js +1 -1
- package/dist/email/nodemailer/index.cjs +2 -2
- package/dist/email/nodemailer/index.js +1 -1
- package/dist/email/resend/index.cjs +2 -2
- package/dist/email/resend/index.js +1 -1
- package/dist/entities/index.cjs +1 -1
- package/dist/entities/index.js +1 -1
- package/dist/errors/index.cjs +7 -7
- package/dist/errors/index.js +7 -7
- package/dist/events/buses.d.ts +27 -0
- package/dist/events/events.controller.d.ts +15 -0
- package/dist/events/events.module.d.ts +29 -0
- package/dist/events/events.options.d.ts +50 -0
- package/dist/events/events.service.d.ts +49 -0
- package/dist/events/events.types.d.ts +77 -0
- package/dist/events/index.cjs +557 -0
- package/dist/events/index.d.ts +10 -0
- package/dist/events/index.js +557 -0
- package/dist/events/memory-ticket.store.d.ts +9 -0
- package/dist/google-business/google-business-http.d.ts +41 -0
- package/dist/google-business/google-business.errors.d.ts +75 -0
- package/dist/google-business/google-business.mappers.d.ts +52 -0
- package/dist/google-business/google-business.module.d.ts +26 -0
- package/dist/google-business/google-business.options.d.ts +40 -0
- package/dist/google-business/google-business.ports.d.ts +18 -0
- package/dist/google-business/google-business.service.d.ts +120 -0
- package/dist/google-business/google-business.types.d.ts +155 -0
- package/dist/google-business/index.cjs +1025 -0
- package/dist/google-business/index.d.ts +15 -0
- package/dist/google-business/index.js +1025 -0
- package/dist/google-business/testing/google-simulator.d.ts +61 -0
- package/dist/hardening/body-limits.d.ts +24 -0
- package/dist/hardening/http.types.d.ts +26 -0
- package/dist/hardening/index.cjs +179 -0
- package/dist/hardening/index.d.ts +19 -0
- package/dist/hardening/index.js +179 -0
- package/dist/hardening/memory-rate-limit.store.d.ts +10 -0
- package/dist/hardening/origin-secret.d.ts +29 -0
- package/dist/hardening/rate-limit.decorator.d.ts +8 -0
- package/dist/hardening/rate-limit.guard.d.ts +18 -0
- package/dist/hardening/rate-limit.module.d.ts +23 -0
- package/dist/hardening/rate-limit.options.d.ts +35 -0
- package/dist/hardening/rate-limit.port.d.ts +11 -0
- package/dist/hardening/redis-rate-limit.store.d.ts +23 -0
- package/dist/hardening/trust-proxy.d.ts +22 -0
- package/dist/health/health.controller.d.ts +32 -0
- package/dist/health/health.module.d.ts +15 -0
- package/dist/health/health.options.d.ts +24 -0
- package/dist/health/index.cjs +103 -0
- package/dist/health/index.d.ts +5 -0
- package/dist/health/index.js +103 -0
- package/dist/i18n/index.cjs +3 -3
- package/dist/i18n/index.js +2 -2
- package/dist/idempotency/idempotency.interceptor.d.ts +1 -0
- package/dist/idempotency/idempotency.options.d.ts +15 -0
- package/dist/idempotency/index.cjs +214 -7
- package/dist/idempotency/index.d.ts +5 -0
- package/dist/idempotency/index.js +210 -3
- package/dist/idempotency/no-idempotency.decorator.d.ts +8 -0
- package/dist/idempotency/postgres.store.d.ts +49 -0
- package/dist/idempotency/redis.store.d.ts +59 -0
- package/dist/index.cjs +21 -20
- package/dist/index.js +33 -32
- package/dist/invoicing/index.cjs +2 -2
- package/dist/invoicing/index.js +1 -1
- package/dist/jobs/defer-job.d.ts +10 -0
- package/dist/jobs/index.cjs +318 -0
- package/dist/jobs/index.d.ts +8 -0
- package/dist/jobs/index.js +318 -0
- package/dist/jobs/jobs-admin.controller.d.ts +18 -0
- package/dist/jobs/jobs.module.d.ts +33 -0
- package/dist/jobs/jobs.options.d.ts +62 -0
- package/dist/jobs/jobs.service.d.ts +53 -0
- package/dist/jobs/jobs.sql.d.ts +11 -0
- package/dist/media/index.cjs +14 -14
- package/dist/media/index.js +1 -1
- package/dist/meta/index.cjs +3 -3
- package/dist/meta/index.js +1 -1
- package/dist/notifications/index.cjs +375 -0
- package/dist/notifications/index.d.ts +8 -0
- package/dist/notifications/index.js +375 -0
- package/dist/notifications/memory.stores.d.ts +23 -0
- package/dist/notifications/notifications.controller.d.ts +11 -0
- package/dist/notifications/notifications.module.d.ts +31 -0
- package/dist/notifications/notifications.options.d.ts +33 -0
- package/dist/notifications/notifications.port.d.ts +97 -0
- package/dist/notifications/notifier.service.d.ts +31 -0
- package/dist/payments/connect/credentials-cipher.d.ts +14 -0
- package/dist/payments/connect/mercadopago-refund.d.ts +118 -0
- package/dist/payments/connect/mercadopago-signature.d.ts +6 -0
- package/dist/payments/connect/online-checkout.d.ts +69 -0
- package/dist/payments/connect/rejection.d.ts +7 -0
- package/dist/payments/connect/status.d.ts +20 -0
- package/dist/payments/connect/terminal-connections.d.ts +291 -0
- package/dist/payments/index.cjs +908 -10
- package/dist/payments/index.d.ts +10 -0
- package/dist/payments/index.js +900 -2
- package/dist/pinterest/index.cjs +3 -3
- package/dist/pinterest/index.js +1 -1
- package/dist/privacy/anonymizer.d.ts +14 -0
- package/dist/privacy/index.cjs +768 -0
- package/dist/privacy/index.d.ts +13 -0
- package/dist/privacy/index.js +768 -0
- package/dist/privacy/memory.store.d.ts +15 -0
- package/dist/privacy/privacy.module.d.ts +30 -0
- package/dist/privacy/privacy.options.d.ts +43 -0
- package/dist/privacy/privacy.port.d.ts +25 -0
- package/dist/privacy/privacy.service.d.ts +69 -0
- package/dist/privacy/privacy.types.d.ts +125 -0
- package/dist/privacy/sql.d.ts +7 -0
- package/dist/privacy/sql.store.d.ts +21 -0
- package/dist/privacy/zip.d.ts +23 -0
- package/dist/push/index.cjs +13 -13
- package/dist/push/index.js +5 -5
- package/dist/resilience/alert-channels.d.ts +39 -0
- package/dist/resilience/alert-errors.interceptor.d.ts +10 -0
- package/dist/resilience/alert-on-failure.decorator.d.ts +10 -0
- package/dist/resilience/alert.service.d.ts +77 -0
- package/dist/resilience/index.cjs +863 -0
- package/dist/resilience/index.d.ts +18 -0
- package/dist/resilience/index.js +863 -0
- package/dist/resilience/memory-alert-store.d.ts +26 -0
- package/dist/resilience/provider-health.controller.d.ts +14 -0
- package/dist/resilience/provider-unavailable.exception.d.ts +11 -0
- package/dist/resilience/resilience.module.d.ts +34 -0
- package/dist/resilience/resilience.options.d.ts +28 -0
- package/dist/resilience/resilience.types.d.ts +167 -0
- package/dist/resilience/resilient-fetch.d.ts +38 -0
- package/dist/resilience/runtime.d.ts +24 -0
- package/dist/resilience/typeorm/alert.entity.d.ts +21 -0
- package/dist/resilience/typeorm/index.cjs +102 -0
- package/dist/resilience/typeorm/index.d.ts +3 -0
- package/dist/resilience/typeorm/index.js +102 -0
- package/dist/resilience/typeorm/typeorm-alert-store.d.ts +39 -0
- package/dist/resilience/validate-destination.d.ts +63 -0
- package/dist/response/index.cjs +3 -3
- package/dist/response/index.js +2 -2
- package/dist/scheduling/cron-lock.service.d.ts +36 -0
- package/dist/scheduling/cron-unico.decorator.d.ts +27 -0
- package/dist/scheduling/fallback.store.d.ts +34 -0
- package/dist/scheduling/index.cjs +392 -0
- package/dist/scheduling/index.d.ts +18 -0
- package/dist/scheduling/index.js +392 -0
- package/dist/scheduling/lock-store.port.d.ts +19 -0
- package/dist/scheduling/memory.store.d.ts +15 -0
- package/dist/scheduling/redis.module.d.ts +31 -0
- package/dist/scheduling/redis.store.d.ts +24 -0
- package/dist/scheduling/scheduling.module.d.ts +24 -0
- package/dist/scheduling/scheduling.options.d.ts +27 -0
- package/dist/scheduling/sql.store.d.ts +26 -0
- package/dist/secrets/index.cjs +274 -0
- package/dist/secrets/index.d.ts +8 -0
- package/dist/secrets/index.js +274 -0
- package/dist/secrets/secrets.errors.d.ts +6 -0
- package/dist/secrets/secrets.module.d.ts +21 -0
- package/dist/secrets/secrets.options.d.ts +32 -0
- package/dist/secrets/secrets.service.d.ts +54 -0
- package/dist/secrets/secrets.transformer.d.ts +33 -0
- package/dist/security/hash.d.ts +8 -0
- package/dist/security/index.cjs +27 -35
- package/dist/security/index.d.ts +5 -0
- package/dist/security/index.js +24 -32
- package/dist/security/mask.d.ts +22 -0
- package/dist/security/signed-grant.d.ts +30 -0
- package/dist/storage/index.cjs +2 -2
- package/dist/storage/index.js +1 -1
- package/dist/stripe/index.cjs +7 -7
- package/dist/stripe/index.js +1 -1
- package/dist/telegram/index.cjs +2 -2
- package/dist/telegram/index.js +1 -1
- package/dist/tenancy/app-role.d.ts +24 -0
- package/dist/tenancy/db-helpers.d.ts +12 -0
- package/dist/tenancy/index.cjs +205 -0
- package/dist/tenancy/index.d.ts +14 -0
- package/dist/tenancy/index.js +205 -0
- package/dist/tenancy/pg/index.cjs +34 -0
- package/dist/tenancy/pg/index.d.ts +2 -0
- package/dist/tenancy/pg/index.js +34 -0
- package/dist/tenancy/pg/with-tenant.d.ts +23 -0
- package/dist/tenancy/request-context.d.ts +18 -0
- package/dist/tenancy/rls-guardrail.d.ts +38 -0
- package/dist/tenancy/scope.d.ts +5 -0
- package/dist/tenancy/tenancy.errors.d.ts +5 -0
- package/dist/tenancy/tenancy.middleware.d.ts +8 -0
- package/dist/tenancy/tenancy.module.d.ts +37 -0
- package/dist/tenancy/tenancy.options.d.ts +34 -0
- package/dist/tenancy/typeorm/index.cjs +41 -0
- package/dist/tenancy/typeorm/index.d.ts +2 -0
- package/dist/tenancy/typeorm/index.js +41 -0
- package/dist/tenancy/typeorm/with-tenant.d.ts +23 -0
- package/dist/tiktok/index.cjs +3 -3
- package/dist/tiktok/index.js +1 -1
- package/dist/tracking/index.cjs +3 -3
- package/dist/tracking/index.js +2 -2
- package/dist/umami/index.cjs +4 -4
- package/dist/umami/index.js +1 -1
- package/dist/whatsapp/index.cjs +2 -2
- package/dist/whatsapp/index.js +1 -1
- package/package.json +108 -3
|
@@ -0,0 +1,768 @@
|
|
|
1
|
+
import {
|
|
2
|
+
__decorateClass,
|
|
3
|
+
__decorateParam
|
|
4
|
+
} from "../chunk-D3DDJWUD.js";
|
|
5
|
+
|
|
6
|
+
// src/privacy/privacy.module.ts
|
|
7
|
+
import { Global, Module } from "@nestjs/common";
|
|
8
|
+
|
|
9
|
+
// src/privacy/memory.store.ts
|
|
10
|
+
var clone = (r) => structuredClone(r);
|
|
11
|
+
var MemoryDeletionStore = class {
|
|
12
|
+
constructor() {
|
|
13
|
+
this.requests = /* @__PURE__ */ new Map();
|
|
14
|
+
this.leases = /* @__PURE__ */ new Map();
|
|
15
|
+
}
|
|
16
|
+
async create(request) {
|
|
17
|
+
this.requests.set(request.id, clone(request));
|
|
18
|
+
}
|
|
19
|
+
async get(id) {
|
|
20
|
+
const r = this.requests.get(id);
|
|
21
|
+
return r ? clone(r) : null;
|
|
22
|
+
}
|
|
23
|
+
async findOpen(subject) {
|
|
24
|
+
for (const r of this.requests.values()) {
|
|
25
|
+
if (r.subject.type === subject.type && r.subject.id === subject.id && r.status !== "done" && r.status !== "cancelled") return clone(r);
|
|
26
|
+
}
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
isDue(r, now, maxAttempts) {
|
|
30
|
+
if (r.status === "pending") return r.dueAt <= now;
|
|
31
|
+
if (r.status === "failed") return r.attempts < maxAttempts && (r.nextAttemptAt ?? r.dueAt) <= now;
|
|
32
|
+
if (r.status === "running") return (this.leases.get(r.id) ?? 0) <= now.getTime();
|
|
33
|
+
return false;
|
|
34
|
+
}
|
|
35
|
+
async listDue(now, limit, maxAttempts) {
|
|
36
|
+
return [...this.requests.values()].filter((r) => this.isDue(r, now, maxAttempts)).sort((a, b) => a.dueAt.getTime() - b.dueAt.getTime()).slice(0, limit).map(clone);
|
|
37
|
+
}
|
|
38
|
+
async claim(id, now, leaseMs, maxAttempts) {
|
|
39
|
+
const r = this.requests.get(id);
|
|
40
|
+
if (!r || !this.isDue(r, now, maxAttempts)) return null;
|
|
41
|
+
r.status = "running";
|
|
42
|
+
this.leases.set(id, now.getTime() + leaseMs);
|
|
43
|
+
return clone(r);
|
|
44
|
+
}
|
|
45
|
+
async saveProgress(id, rule, progress) {
|
|
46
|
+
const r = this.requests.get(id);
|
|
47
|
+
if (r) r.progress[rule] = { ...progress };
|
|
48
|
+
}
|
|
49
|
+
async finish(id, patch) {
|
|
50
|
+
const r = this.requests.get(id);
|
|
51
|
+
if (!r) return;
|
|
52
|
+
Object.assign(r, patch);
|
|
53
|
+
this.leases.delete(id);
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
// src/privacy/privacy.options.ts
|
|
58
|
+
var PRIVACY_OPTIONS = /* @__PURE__ */ Symbol("PRIVACY_OPTIONS");
|
|
59
|
+
var DEFAULT_GRACE_DAYS = 30;
|
|
60
|
+
var DEFAULT_INTERVAL_MS = 36e5;
|
|
61
|
+
var DEFAULT_BATCH_SIZE = 25;
|
|
62
|
+
var DEFAULT_LEASE_MS = 6e5;
|
|
63
|
+
var DEFAULT_MAX_ATTEMPTS = 10;
|
|
64
|
+
var DEFAULT_PAGE_SIZE = 500;
|
|
65
|
+
|
|
66
|
+
// src/privacy/privacy.port.ts
|
|
67
|
+
var PRIVACY_STORE = /* @__PURE__ */ Symbol("PRIVACY_STORE");
|
|
68
|
+
|
|
69
|
+
// src/privacy/privacy.service.ts
|
|
70
|
+
import { randomUUID } from "crypto";
|
|
71
|
+
import { Readable } from "stream";
|
|
72
|
+
import { pipeline } from "stream/promises";
|
|
73
|
+
import { Inject, Injectable, Logger } from "@nestjs/common";
|
|
74
|
+
|
|
75
|
+
// src/privacy/anonymizer.ts
|
|
76
|
+
import { createHmac } from "crypto";
|
|
77
|
+
var DEFAULT_PREFIX = "anon_";
|
|
78
|
+
var DEFAULT_HASH_LENGTH = 24;
|
|
79
|
+
var Anonymizer = class {
|
|
80
|
+
constructor(salt = "") {
|
|
81
|
+
this.salt = salt;
|
|
82
|
+
}
|
|
83
|
+
/** One-way keyed hash. Idempotent: a value already shaped like the output is returned untouched. */
|
|
84
|
+
hash(value, o = {}) {
|
|
85
|
+
if (value === null || value === void 0) return null;
|
|
86
|
+
const prefix = o.prefix ?? DEFAULT_PREFIX;
|
|
87
|
+
const suffix = o.suffix ?? "";
|
|
88
|
+
const length = o.length ?? DEFAULT_HASH_LENGTH;
|
|
89
|
+
const text = String(value);
|
|
90
|
+
if (text.startsWith(prefix) && text.endsWith(suffix) && text.length === prefix.length + length + suffix.length)
|
|
91
|
+
return text;
|
|
92
|
+
const hex = createHmac("sha256", this.salt).update(text).digest("hex").slice(0, length);
|
|
93
|
+
return `${prefix}${hex}${suffix}`;
|
|
94
|
+
}
|
|
95
|
+
/** Keeps the ends, hides the middle (`jo***@acme.com`). Strings only; other values become NULL. */
|
|
96
|
+
mask(value, o = {}) {
|
|
97
|
+
if (value === null || value === void 0) return null;
|
|
98
|
+
const char = o.char ?? "*";
|
|
99
|
+
const text = String(value);
|
|
100
|
+
const at = o.email ? text.lastIndexOf("@") : -1;
|
|
101
|
+
const local = at > 0 ? text.slice(0, at) : text;
|
|
102
|
+
const rest = at > 0 ? text.slice(at) : "";
|
|
103
|
+
const start = Math.min(o.keepStart ?? 1, local.length);
|
|
104
|
+
const end = Math.min(o.keepEnd ?? 0, Math.max(local.length - start, 0));
|
|
105
|
+
const hidden = Math.max(local.length - start - end, 0);
|
|
106
|
+
return local.slice(0, start) + char.repeat(Math.max(hidden, 1)) + local.slice(local.length - end) + rest;
|
|
107
|
+
}
|
|
108
|
+
/** Applies one strategy. `'null'` and `{ value }` are also handled in SQL by the service. */
|
|
109
|
+
apply(strategy, value, row) {
|
|
110
|
+
if (typeof strategy === "function") return strategy(value, row);
|
|
111
|
+
if (strategy === "null") return null;
|
|
112
|
+
if (strategy === "hash") return this.hash(value);
|
|
113
|
+
if (strategy === "mask") return this.mask(value);
|
|
114
|
+
if ("value" in strategy) return strategy.value;
|
|
115
|
+
if ("hash" in strategy) return this.hash(value, strategy.hash);
|
|
116
|
+
return this.mask(value, strategy.mask);
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
function isConstant(strategy) {
|
|
120
|
+
return strategy === "null" || typeof strategy === "object" && "value" in strategy;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// src/privacy/sql.ts
|
|
124
|
+
var IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
125
|
+
function quoteIdent(name) {
|
|
126
|
+
const parts = name.split(".");
|
|
127
|
+
if (parts.length > 2 || parts.some((p) => !IDENT.test(p)))
|
|
128
|
+
throw new Error(`Invalid SQL identifier: ${JSON.stringify(name)}`);
|
|
129
|
+
return parts.map((p) => `"${p}"`).join(".");
|
|
130
|
+
}
|
|
131
|
+
function rowsOf(result) {
|
|
132
|
+
if (Array.isArray(result)) return Array.isArray(result[0]) ? result[0] : result;
|
|
133
|
+
return result?.rows ?? [];
|
|
134
|
+
}
|
|
135
|
+
async function countAffected(db, statement, params) {
|
|
136
|
+
const res = await db.query(
|
|
137
|
+
`WITH affected AS (${statement} RETURNING 1) SELECT count(*)::int AS n FROM affected`,
|
|
138
|
+
params
|
|
139
|
+
);
|
|
140
|
+
return Number(rowsOf(res)[0]?.n ?? 0);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// src/privacy/zip.ts
|
|
144
|
+
import { deflateRawSync } from "zlib";
|
|
145
|
+
var CRC_TABLE = (() => {
|
|
146
|
+
const t = new Uint32Array(256);
|
|
147
|
+
for (let n = 0; n < 256; n++) {
|
|
148
|
+
let c = n;
|
|
149
|
+
for (let k = 0; k < 8; k++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
|
|
150
|
+
t[n] = c >>> 0;
|
|
151
|
+
}
|
|
152
|
+
return t;
|
|
153
|
+
})();
|
|
154
|
+
function crc32(buf) {
|
|
155
|
+
let c = 4294967295;
|
|
156
|
+
for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 255] ^ c >>> 8;
|
|
157
|
+
return (c ^ 4294967295) >>> 0;
|
|
158
|
+
}
|
|
159
|
+
function dosDate(d) {
|
|
160
|
+
const a = Math.max(d.getFullYear(), 1980);
|
|
161
|
+
return {
|
|
162
|
+
date: a - 1980 << 9 | d.getMonth() + 1 << 5 | d.getDate(),
|
|
163
|
+
time: d.getHours() << 11 | d.getMinutes() << 5 | d.getSeconds() >> 1
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
var ZipWriter = class {
|
|
167
|
+
constructor() {
|
|
168
|
+
this.centrals = [];
|
|
169
|
+
this.offset = 0;
|
|
170
|
+
this.entries = 0;
|
|
171
|
+
this.closed = false;
|
|
172
|
+
}
|
|
173
|
+
/** Bytes of the entry, ready to write; the content is not retained. */
|
|
174
|
+
add(e) {
|
|
175
|
+
if (this.closed) throw new Error("The ZIP is already closed.");
|
|
176
|
+
if (this.entries >= 65535) throw new Error("Too many entries for a ZIP without ZIP64.");
|
|
177
|
+
const name = Buffer.from(e.name, "utf8");
|
|
178
|
+
const raw = e.content;
|
|
179
|
+
const deflated = deflateRawSync(raw);
|
|
180
|
+
const useDeflate = deflated.length < raw.length;
|
|
181
|
+
const payload = useDeflate ? deflated : raw;
|
|
182
|
+
const { date, time } = dosDate(e.date ?? /* @__PURE__ */ new Date());
|
|
183
|
+
const crc = crc32(raw);
|
|
184
|
+
const method = useDeflate ? 8 : 0;
|
|
185
|
+
if (this.offset + 30 + name.length + payload.length > 4294967295)
|
|
186
|
+
throw new Error("The ZIP would exceed 4 GB.");
|
|
187
|
+
const local = Buffer.alloc(30);
|
|
188
|
+
local.writeUInt32LE(67324752, 0);
|
|
189
|
+
local.writeUInt16LE(20, 4);
|
|
190
|
+
local.writeUInt16LE(2048, 6);
|
|
191
|
+
local.writeUInt16LE(method, 8);
|
|
192
|
+
local.writeUInt16LE(time, 10);
|
|
193
|
+
local.writeUInt16LE(date, 12);
|
|
194
|
+
local.writeUInt32LE(crc, 14);
|
|
195
|
+
local.writeUInt32LE(payload.length, 18);
|
|
196
|
+
local.writeUInt32LE(raw.length, 22);
|
|
197
|
+
local.writeUInt16LE(name.length, 26);
|
|
198
|
+
local.writeUInt16LE(0, 28);
|
|
199
|
+
const central = Buffer.alloc(46);
|
|
200
|
+
central.writeUInt32LE(33639248, 0);
|
|
201
|
+
central.writeUInt16LE(20, 4);
|
|
202
|
+
central.writeUInt16LE(20, 6);
|
|
203
|
+
central.writeUInt16LE(2048, 8);
|
|
204
|
+
central.writeUInt16LE(method, 10);
|
|
205
|
+
central.writeUInt16LE(time, 12);
|
|
206
|
+
central.writeUInt16LE(date, 14);
|
|
207
|
+
central.writeUInt32LE(crc, 16);
|
|
208
|
+
central.writeUInt32LE(payload.length, 20);
|
|
209
|
+
central.writeUInt32LE(raw.length, 24);
|
|
210
|
+
central.writeUInt16LE(name.length, 28);
|
|
211
|
+
central.writeUInt32LE(this.offset, 42);
|
|
212
|
+
this.centrals.push(central, name);
|
|
213
|
+
this.offset += 30 + name.length + payload.length;
|
|
214
|
+
this.entries++;
|
|
215
|
+
return Buffer.concat([local, name, payload]);
|
|
216
|
+
}
|
|
217
|
+
/** Central directory + end record: the last thing written. */
|
|
218
|
+
close() {
|
|
219
|
+
if (this.closed) throw new Error("The ZIP is already closed.");
|
|
220
|
+
this.closed = true;
|
|
221
|
+
const centralSize = this.centrals.reduce((s, b) => s + b.length, 0);
|
|
222
|
+
const end = Buffer.alloc(22);
|
|
223
|
+
end.writeUInt32LE(101010256, 0);
|
|
224
|
+
end.writeUInt16LE(this.entries, 8);
|
|
225
|
+
end.writeUInt16LE(this.entries, 10);
|
|
226
|
+
end.writeUInt32LE(centralSize, 12);
|
|
227
|
+
end.writeUInt32LE(this.offset, 16);
|
|
228
|
+
return Buffer.concat([...this.centrals, end]);
|
|
229
|
+
}
|
|
230
|
+
};
|
|
231
|
+
function createZip(entries) {
|
|
232
|
+
const z = new ZipWriter();
|
|
233
|
+
const parts = entries.map((e) => z.add(e));
|
|
234
|
+
return Buffer.concat([...parts, z.close()]);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// src/privacy/privacy.service.ts
|
|
238
|
+
var DAY_MS = 864e5;
|
|
239
|
+
var BACKOFF_BASE_MS = 3e5;
|
|
240
|
+
var BACKOFF_MAX_MS = 6 * 36e5;
|
|
241
|
+
var ruleName = (r) => r.name ?? r.table ?? "";
|
|
242
|
+
function planRegistry(registry) {
|
|
243
|
+
const plans = /* @__PURE__ */ new Map();
|
|
244
|
+
for (const [type, rules] of Object.entries(registry)) {
|
|
245
|
+
const byName = /* @__PURE__ */ new Map();
|
|
246
|
+
for (const r of rules) {
|
|
247
|
+
const name = ruleName(r);
|
|
248
|
+
if (!name) throw new Error(`privacy: a rule of "${type}" needs a name or a table`);
|
|
249
|
+
if (byName.has(name)) throw new Error(`privacy: duplicate rule "${name}" in "${type}"`);
|
|
250
|
+
if (r.table) quoteIdent(r.table);
|
|
251
|
+
if (r.pk) quoteIdent(r.pk);
|
|
252
|
+
if (r.action === "custom" && !r.run) throw new Error(`privacy: rule "${name}" is custom and has no run()`);
|
|
253
|
+
if (r.action === "delete" && (!r.table || !r.where))
|
|
254
|
+
throw new Error(`privacy: delete rule "${name}" needs table and where`);
|
|
255
|
+
if (r.action === "anonymize") {
|
|
256
|
+
if (!r.table || !r.where || !r.columns || Object.keys(r.columns).length === 0)
|
|
257
|
+
throw new Error(`privacy: anonymize rule "${name}" needs table, where and columns`);
|
|
258
|
+
Object.keys(r.columns).forEach(quoteIdent);
|
|
259
|
+
}
|
|
260
|
+
byName.set(name, { ...r, name });
|
|
261
|
+
}
|
|
262
|
+
const ordered = [];
|
|
263
|
+
const state = /* @__PURE__ */ new Map();
|
|
264
|
+
const visit = (name, from) => {
|
|
265
|
+
const rule = byName.get(name);
|
|
266
|
+
if (!rule) throw new Error(`privacy: "${from}" requires unknown rule "${name}" in "${type}"`);
|
|
267
|
+
const s = state.get(name);
|
|
268
|
+
if (s === 2) return;
|
|
269
|
+
if (s === 1) throw new Error(`privacy: dependency cycle at "${name}" in "${type}"`);
|
|
270
|
+
state.set(name, 1);
|
|
271
|
+
for (const dep of rule.requires ?? []) visit(dep, name);
|
|
272
|
+
state.set(name, 2);
|
|
273
|
+
ordered.push(rule);
|
|
274
|
+
};
|
|
275
|
+
for (const name of byName.keys()) visit(name, name);
|
|
276
|
+
plans.set(type, ordered);
|
|
277
|
+
}
|
|
278
|
+
return plans;
|
|
279
|
+
}
|
|
280
|
+
function safePath(name) {
|
|
281
|
+
return name.replace(/\\/g, "/").split("/").filter((p) => p && p !== "." && p !== "..").join("/");
|
|
282
|
+
}
|
|
283
|
+
function jsonReplacer(_k, v) {
|
|
284
|
+
if (typeof v === "bigint") return v.toString();
|
|
285
|
+
if (v instanceof Uint8Array) return Buffer.from(v).toString("base64");
|
|
286
|
+
if (v && typeof v === "object" && v.type === "Buffer" && Array.isArray(v.data))
|
|
287
|
+
return Buffer.from(v.data).toString("base64");
|
|
288
|
+
return v;
|
|
289
|
+
}
|
|
290
|
+
var PrivacyService = class {
|
|
291
|
+
constructor(options, store) {
|
|
292
|
+
this.options = options;
|
|
293
|
+
this.store = store;
|
|
294
|
+
this.log = new Logger("Privacy");
|
|
295
|
+
this.running = false;
|
|
296
|
+
this.plans = planRegistry(options.registry);
|
|
297
|
+
this.anonymizer = new Anonymizer(options.anonymizeSalt);
|
|
298
|
+
}
|
|
299
|
+
onModuleInit() {
|
|
300
|
+
if (this.options.runner !== "cron") return;
|
|
301
|
+
this.timer = setInterval(() => {
|
|
302
|
+
void this.runDue().catch((e) => this.log.error(`runDue: ${e.message}`));
|
|
303
|
+
void this.runRetention().catch((e) => this.log.error(`runRetention: ${e.message}`));
|
|
304
|
+
}, this.options.intervalMs ?? DEFAULT_INTERVAL_MS);
|
|
305
|
+
this.timer.unref?.();
|
|
306
|
+
}
|
|
307
|
+
onModuleDestroy() {
|
|
308
|
+
if (this.timer) clearInterval(this.timer);
|
|
309
|
+
}
|
|
310
|
+
// ---- requests ----------------------------------------------------------------------------------------------
|
|
311
|
+
now() {
|
|
312
|
+
return this.options.now?.() ?? /* @__PURE__ */ new Date();
|
|
313
|
+
}
|
|
314
|
+
async audit(action, req, metadata) {
|
|
315
|
+
try {
|
|
316
|
+
await this.options.audit?.record({
|
|
317
|
+
action,
|
|
318
|
+
resource: `privacy.${req.subject.type}`,
|
|
319
|
+
resourceId: req.subject.id,
|
|
320
|
+
metadata: { requestId: req.id, ...metadata }
|
|
321
|
+
});
|
|
322
|
+
} catch (e) {
|
|
323
|
+
this.log.warn(`audit ${action}: ${e.message}`);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
/** Idempotent: a subject with an open request gets that one back (`created: false`). */
|
|
327
|
+
async requestDeletion(subject, opts = {}) {
|
|
328
|
+
if (!this.plans.has(subject.type)) throw new Error(`privacy: unknown subject type "${subject.type}"`);
|
|
329
|
+
const open = await this.store.findOpen(subject);
|
|
330
|
+
if (open) return { request: open, created: false };
|
|
331
|
+
const now = this.now();
|
|
332
|
+
const request = {
|
|
333
|
+
id: randomUUID(),
|
|
334
|
+
subject,
|
|
335
|
+
reason: opts.reason,
|
|
336
|
+
status: "pending",
|
|
337
|
+
requestedAt: now,
|
|
338
|
+
dueAt: new Date(now.getTime() + (this.options.graceDays ?? DEFAULT_GRACE_DAYS) * DAY_MS),
|
|
339
|
+
attempts: 0,
|
|
340
|
+
progress: {}
|
|
341
|
+
};
|
|
342
|
+
await this.store.create(request);
|
|
343
|
+
await this.audit("privacy.deletion.requested", request, { dueAt: request.dueAt.toISOString() });
|
|
344
|
+
return { request, created: true };
|
|
345
|
+
}
|
|
346
|
+
/**
|
|
347
|
+
* Cancel by request id or by subject. Only while nothing has been erased: once a step finished the erasure is
|
|
348
|
+
* irreversible and cancelling is refused (`reason: 'irreversible'`).
|
|
349
|
+
*/
|
|
350
|
+
async cancel(ref) {
|
|
351
|
+
const req = typeof ref === "string" ? await this.store.get(ref) : await this.store.findOpen(ref);
|
|
352
|
+
if (!req) return { cancelled: false, reason: "not_found" };
|
|
353
|
+
if (req.status === "done" || req.status === "cancelled") return { cancelled: false, reason: "closed", request: req };
|
|
354
|
+
if (req.status === "running") return { cancelled: false, reason: "running", request: req };
|
|
355
|
+
if (Object.values(req.progress).some((p) => p.done)) return { cancelled: false, reason: "irreversible", request: req };
|
|
356
|
+
await this.store.finish(req.id, { status: "cancelled" });
|
|
357
|
+
await this.audit("privacy.deletion.cancelled", req);
|
|
358
|
+
return { cancelled: true, request: { ...req, status: "cancelled" } };
|
|
359
|
+
}
|
|
360
|
+
/** The open request of a subject (pending, running or failed), if any. */
|
|
361
|
+
status(subject) {
|
|
362
|
+
return this.store.findOpen(subject);
|
|
363
|
+
}
|
|
364
|
+
/** A request with its step-by-step progress: what was erased or anonymized, and how many rows. The audit trail. */
|
|
365
|
+
report(id) {
|
|
366
|
+
return this.store.get(id);
|
|
367
|
+
}
|
|
368
|
+
// ---- erasure -----------------------------------------------------------------------------------------------
|
|
369
|
+
/** Process every due request. Safe to call from several instances and to call again after a crash. */
|
|
370
|
+
async runDue() {
|
|
371
|
+
if (this.running) return [];
|
|
372
|
+
this.running = true;
|
|
373
|
+
try {
|
|
374
|
+
const max = this.options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
|
|
375
|
+
const due = await this.store.listDue(this.now(), this.options.batchSize ?? DEFAULT_BATCH_SIZE, max);
|
|
376
|
+
const reports = [];
|
|
377
|
+
for (const candidate of due) {
|
|
378
|
+
const claimed = await this.store.claim(candidate.id, this.now(), this.options.leaseMs ?? DEFAULT_LEASE_MS, max);
|
|
379
|
+
if (!claimed) continue;
|
|
380
|
+
try {
|
|
381
|
+
reports.push(await this.process(claimed));
|
|
382
|
+
} catch (e) {
|
|
383
|
+
this.log.error(`request ${claimed.id}: ${e.message}`);
|
|
384
|
+
await this.store.finish(claimed.id, {
|
|
385
|
+
status: "failed",
|
|
386
|
+
lastError: e.message.slice(0, 500),
|
|
387
|
+
attempts: claimed.attempts + 1,
|
|
388
|
+
nextAttemptAt: new Date(this.now().getTime() + BACKOFF_BASE_MS)
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
return reports;
|
|
393
|
+
} finally {
|
|
394
|
+
this.running = false;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
async process(req) {
|
|
398
|
+
const rules = this.plans.get(req.subject.type);
|
|
399
|
+
const report = { requestId: req.id, subject: req.subject, status: "running", rows: {}, failed: [] };
|
|
400
|
+
if (!rules) throw new Error(`no rules for subject type "${req.subject.type}"`);
|
|
401
|
+
const done = new Set(Object.entries(req.progress).filter(([, p]) => p.done).map(([n]) => n));
|
|
402
|
+
for (const rule of rules) {
|
|
403
|
+
if (done.has(rule.name)) continue;
|
|
404
|
+
if ((rule.requires ?? []).some((r) => !done.has(r))) continue;
|
|
405
|
+
const previous = req.progress[rule.name];
|
|
406
|
+
const attempts2 = (previous?.attempts ?? 0) + 1;
|
|
407
|
+
try {
|
|
408
|
+
const rows = await this.runRule(rule, req.subject);
|
|
409
|
+
const entry = { done: true, rows, attempts: attempts2, at: this.now() };
|
|
410
|
+
await this.store.saveProgress(req.id, rule.name, entry);
|
|
411
|
+
req.progress[rule.name] = entry;
|
|
412
|
+
done.add(rule.name);
|
|
413
|
+
report.rows[rule.name] = rows;
|
|
414
|
+
await this.audit("privacy.step.done", req, { step: rule.name, action: rule.action, rows });
|
|
415
|
+
} catch (e) {
|
|
416
|
+
const message = e.message.slice(0, 500);
|
|
417
|
+
const entry = { done: false, rows: 0, attempts: attempts2, error: message, at: this.now() };
|
|
418
|
+
await this.store.saveProgress(req.id, rule.name, entry);
|
|
419
|
+
req.progress[rule.name] = entry;
|
|
420
|
+
report.failed.push(rule.name);
|
|
421
|
+
this.log.error(`request ${req.id} step ${rule.name}: ${message}`);
|
|
422
|
+
await this.audit("privacy.step.failed", req, { step: rule.name, attempts: attempts2 });
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
if (done.size === rules.length) {
|
|
426
|
+
const completedAt = this.now();
|
|
427
|
+
await this.store.finish(req.id, { status: "done", completedAt, attempts: req.attempts + 1 });
|
|
428
|
+
report.status = "done";
|
|
429
|
+
const finished = { ...req, status: "done", completedAt, attempts: req.attempts + 1 };
|
|
430
|
+
await this.audit("privacy.deletion.done", finished);
|
|
431
|
+
try {
|
|
432
|
+
await this.options.onDone?.(finished);
|
|
433
|
+
} catch (e) {
|
|
434
|
+
this.log.error(`onDone ${req.id}: ${e.message}`);
|
|
435
|
+
}
|
|
436
|
+
return report;
|
|
437
|
+
}
|
|
438
|
+
const attempts = req.attempts + 1;
|
|
439
|
+
const backoff = Math.min(BACKOFF_BASE_MS * 2 ** (attempts - 1), BACKOFF_MAX_MS);
|
|
440
|
+
const lastError = report.failed.map((n) => `${n}: ${req.progress[n]?.error ?? "failed"}`).join("; ").slice(0, 500);
|
|
441
|
+
await this.store.finish(req.id, {
|
|
442
|
+
status: "failed",
|
|
443
|
+
attempts,
|
|
444
|
+
lastError,
|
|
445
|
+
nextAttemptAt: new Date(this.now().getTime() + backoff)
|
|
446
|
+
});
|
|
447
|
+
report.status = "failed";
|
|
448
|
+
if (attempts >= (this.options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS)) {
|
|
449
|
+
try {
|
|
450
|
+
await this.options.onFailed?.({ ...req, status: "failed", attempts, lastError });
|
|
451
|
+
} catch (e) {
|
|
452
|
+
this.log.error(`onFailed ${req.id}: ${e.message}`);
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
return report;
|
|
456
|
+
}
|
|
457
|
+
async runRule(rule, subject) {
|
|
458
|
+
const exec = (tx) => this.execRule(tx, rule, subject);
|
|
459
|
+
const db = this.options.db;
|
|
460
|
+
return db.transaction ? db.transaction(exec) : exec(db);
|
|
461
|
+
}
|
|
462
|
+
async execRule(tx, rule, subject) {
|
|
463
|
+
if (rule.action === "custom") return rule.run(tx, subject);
|
|
464
|
+
const table = quoteIdent(rule.table);
|
|
465
|
+
if (rule.action === "delete") {
|
|
466
|
+
return countAffected(tx, `DELETE FROM ${table} WHERE (${rule.where})`, [subject.id]);
|
|
467
|
+
}
|
|
468
|
+
const columns = Object.entries(rule.columns);
|
|
469
|
+
const constants = columns.filter(([, s]) => isConstant(s));
|
|
470
|
+
const dynamic = columns.filter(([, s]) => !isConstant(s));
|
|
471
|
+
let touched = 0;
|
|
472
|
+
if (constants.length) {
|
|
473
|
+
const sets = constants.map(([c], i) => `${quoteIdent(c)} = $${i + 2}`).join(", ");
|
|
474
|
+
const values = constants.map(([, s]) => s === "null" ? null : s.value);
|
|
475
|
+
touched = await countAffected(tx, `UPDATE ${table} SET ${sets} WHERE (${rule.where})`, [subject.id, ...values]);
|
|
476
|
+
}
|
|
477
|
+
if (dynamic.length) {
|
|
478
|
+
const pk = quoteIdent(rule.pk ?? "id");
|
|
479
|
+
const selectCols = [pk, ...dynamic.map(([c]) => quoteIdent(c))].join(", ");
|
|
480
|
+
const pageSize = this.options.pageSize ?? DEFAULT_PAGE_SIZE;
|
|
481
|
+
let cursor;
|
|
482
|
+
let rows = 0;
|
|
483
|
+
for (; ; ) {
|
|
484
|
+
const page = rowsOf(
|
|
485
|
+
await tx.query(
|
|
486
|
+
`SELECT ${selectCols} FROM ${table} WHERE (${rule.where})${cursor === void 0 ? "" : ` AND ${pk} > $2`} ORDER BY ${pk} LIMIT ${pageSize}`,
|
|
487
|
+
cursor === void 0 ? [subject.id] : [subject.id, cursor]
|
|
488
|
+
)
|
|
489
|
+
);
|
|
490
|
+
if (page.length === 0) break;
|
|
491
|
+
for (const row of page) {
|
|
492
|
+
const changes = dynamic.map(([c, s]) => [c, this.anonymizer.apply(s, row[c], row)]).filter(([c, v]) => v !== row[c]);
|
|
493
|
+
if (changes.length)
|
|
494
|
+
await tx.query(
|
|
495
|
+
`UPDATE ${table} SET ${changes.map(([c], i) => `${quoteIdent(c)} = $${i + 2}`).join(", ")} WHERE ${pk} = $1`,
|
|
496
|
+
[row[rule.pk ?? "id"], ...changes.map(([, v]) => v)]
|
|
497
|
+
);
|
|
498
|
+
rows++;
|
|
499
|
+
}
|
|
500
|
+
cursor = page[page.length - 1][rule.pk ?? "id"];
|
|
501
|
+
if (page.length < pageSize) break;
|
|
502
|
+
}
|
|
503
|
+
touched = Math.max(touched, rows);
|
|
504
|
+
}
|
|
505
|
+
return touched;
|
|
506
|
+
}
|
|
507
|
+
// ---- retention ---------------------------------------------------------------------------------------------
|
|
508
|
+
/** Delete data that outlived its retention period. A failing rule does not stop the others. */
|
|
509
|
+
async runRetention() {
|
|
510
|
+
const out = {};
|
|
511
|
+
for (const r of this.options.retention ?? []) {
|
|
512
|
+
try {
|
|
513
|
+
const cutoff = new Date(this.now().getTime() - r.maxAgeDays * DAY_MS);
|
|
514
|
+
const extra = r.where ? ` AND (${r.where})` : "";
|
|
515
|
+
out[r.name] = await countAffected(
|
|
516
|
+
this.options.db,
|
|
517
|
+
`DELETE FROM ${quoteIdent(r.table)} WHERE ${quoteIdent(r.column)} < $1${extra}`,
|
|
518
|
+
[cutoff]
|
|
519
|
+
);
|
|
520
|
+
} catch (e) {
|
|
521
|
+
this.log.error(`retention ${r.name}: ${e.message}`);
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
return out;
|
|
525
|
+
}
|
|
526
|
+
// ---- export ------------------------------------------------------------------------------------------------
|
|
527
|
+
/**
|
|
528
|
+
* ZIP of the subject's data: `<step>/part-0001.json`… (one file per page of rows), extra files of each rule, and a
|
|
529
|
+
* `manifest.json`. Built entry by entry as a stream, so memory is bounded by `pageSize`, not by the data.
|
|
530
|
+
*/
|
|
531
|
+
exportStream(subject) {
|
|
532
|
+
const rules = this.plans.get(subject.type);
|
|
533
|
+
if (!rules) throw new Error(`privacy: unknown subject type "${subject.type}"`);
|
|
534
|
+
return Readable.from(this.exportChunks(subject, rules), { objectMode: false });
|
|
535
|
+
}
|
|
536
|
+
/** Pipe the export into any writable (an HTTP response, a file, an upload). Resolves when it is flushed. */
|
|
537
|
+
async exportTo(subject, out) {
|
|
538
|
+
await pipeline(this.exportStream(subject), out);
|
|
539
|
+
try {
|
|
540
|
+
await this.options.audit?.record({
|
|
541
|
+
action: "privacy.export",
|
|
542
|
+
resource: `privacy.${subject.type}`,
|
|
543
|
+
resourceId: subject.id
|
|
544
|
+
});
|
|
545
|
+
} catch (e) {
|
|
546
|
+
this.log.warn(`audit privacy.export: ${e.message}`);
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
async *exportChunks(subject, rules) {
|
|
550
|
+
const zip = new ZipWriter();
|
|
551
|
+
const now = this.now();
|
|
552
|
+
const pageSize = this.options.pageSize ?? DEFAULT_PAGE_SIZE;
|
|
553
|
+
const manifest = {};
|
|
554
|
+
for (const rule of rules) {
|
|
555
|
+
if (rule.export === false || rule.action === "custom" && !rule.export) continue;
|
|
556
|
+
const spec = rule.export || {};
|
|
557
|
+
const entry = manifest[rule.name] = { rows: 0, parts: 0, files: 0 };
|
|
558
|
+
if (rule.table && rule.where) {
|
|
559
|
+
const pkName = rule.pk ?? "id";
|
|
560
|
+
const pk = quoteIdent(pkName);
|
|
561
|
+
const select = spec.columns ? [.../* @__PURE__ */ new Set([pkName, ...spec.columns])].map(quoteIdent).join(", ") : "*";
|
|
562
|
+
let cursor;
|
|
563
|
+
for (; ; ) {
|
|
564
|
+
const page = rowsOf(
|
|
565
|
+
await this.options.db.query(
|
|
566
|
+
`SELECT ${select} FROM ${quoteIdent(rule.table)} WHERE (${rule.where})${cursor === void 0 ? "" : ` AND ${pk} > $2`} ORDER BY ${pk} LIMIT ${pageSize}`,
|
|
567
|
+
cursor === void 0 ? [subject.id] : [subject.id, cursor]
|
|
568
|
+
)
|
|
569
|
+
);
|
|
570
|
+
if (page.length === 0) break;
|
|
571
|
+
cursor = page[page.length - 1][pkName];
|
|
572
|
+
const clean = page.map((row) => {
|
|
573
|
+
const o = { ...row };
|
|
574
|
+
if (spec.columns && !spec.columns.includes(pkName)) delete o[pkName];
|
|
575
|
+
for (const c of spec.exclude ?? []) delete o[c];
|
|
576
|
+
return o;
|
|
577
|
+
});
|
|
578
|
+
entry.rows += clean.length;
|
|
579
|
+
entry.parts++;
|
|
580
|
+
yield zip.add({
|
|
581
|
+
name: `${rule.name}/part-${String(entry.parts).padStart(4, "0")}.json`,
|
|
582
|
+
content: Buffer.from(JSON.stringify(clean, jsonReplacer, 2), "utf8"),
|
|
583
|
+
date: now
|
|
584
|
+
});
|
|
585
|
+
if (page.length < pageSize) break;
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
if (spec.files) {
|
|
589
|
+
for await (const f of spec.files(subject)) {
|
|
590
|
+
entry.files++;
|
|
591
|
+
yield zip.add({ name: `${rule.name}/files/${safePath(f.name)}`, content: Buffer.from(f.content), date: now });
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
yield zip.add({
|
|
596
|
+
name: "manifest.json",
|
|
597
|
+
content: Buffer.from(
|
|
598
|
+
JSON.stringify({ subject, generatedAt: now.toISOString(), steps: manifest }, null, 2),
|
|
599
|
+
"utf8"
|
|
600
|
+
),
|
|
601
|
+
date: now
|
|
602
|
+
});
|
|
603
|
+
yield zip.close();
|
|
604
|
+
}
|
|
605
|
+
};
|
|
606
|
+
PrivacyService = __decorateClass([
|
|
607
|
+
Injectable(),
|
|
608
|
+
__decorateParam(0, Inject(PRIVACY_OPTIONS)),
|
|
609
|
+
__decorateParam(1, Inject(PRIVACY_STORE))
|
|
610
|
+
], PrivacyService);
|
|
611
|
+
|
|
612
|
+
// src/privacy/privacy.module.ts
|
|
613
|
+
var PrivacyModule = class {
|
|
614
|
+
static forRoot(options) {
|
|
615
|
+
const providers = [
|
|
616
|
+
{ provide: PRIVACY_OPTIONS, useValue: options },
|
|
617
|
+
{ provide: PRIVACY_STORE, useValue: options.store ?? new MemoryDeletionStore() },
|
|
618
|
+
PrivacyService
|
|
619
|
+
];
|
|
620
|
+
return { module: PrivacyModule, providers, exports: [PRIVACY_OPTIONS, PRIVACY_STORE, PrivacyService] };
|
|
621
|
+
}
|
|
622
|
+
static forRootAsync(config) {
|
|
623
|
+
const providers = [
|
|
624
|
+
{ provide: PRIVACY_OPTIONS, useFactory: config.useFactory, inject: config.inject ?? [] },
|
|
625
|
+
{
|
|
626
|
+
provide: PRIVACY_STORE,
|
|
627
|
+
useFactory: (o) => o.store ?? new MemoryDeletionStore(),
|
|
628
|
+
inject: [PRIVACY_OPTIONS]
|
|
629
|
+
},
|
|
630
|
+
PrivacyService
|
|
631
|
+
];
|
|
632
|
+
return {
|
|
633
|
+
module: PrivacyModule,
|
|
634
|
+
imports: config.imports ?? [],
|
|
635
|
+
providers,
|
|
636
|
+
exports: [PRIVACY_OPTIONS, PRIVACY_STORE, PrivacyService]
|
|
637
|
+
};
|
|
638
|
+
}
|
|
639
|
+
};
|
|
640
|
+
PrivacyModule = __decorateClass([
|
|
641
|
+
Global(),
|
|
642
|
+
Module({})
|
|
643
|
+
], PrivacyModule);
|
|
644
|
+
|
|
645
|
+
// src/privacy/sql.store.ts
|
|
646
|
+
function privacyTableSql(table = "privacy_deletion_request") {
|
|
647
|
+
const t = quoteIdent(table);
|
|
648
|
+
return `CREATE TABLE IF NOT EXISTS ${t} (
|
|
649
|
+
id text PRIMARY KEY,
|
|
650
|
+
subject_type text NOT NULL,
|
|
651
|
+
subject_id text NOT NULL,
|
|
652
|
+
reason text,
|
|
653
|
+
status text NOT NULL,
|
|
654
|
+
requested_at timestamptz NOT NULL,
|
|
655
|
+
due_at timestamptz NOT NULL,
|
|
656
|
+
attempts int NOT NULL DEFAULT 0,
|
|
657
|
+
last_error text,
|
|
658
|
+
next_attempt_at timestamptz,
|
|
659
|
+
lease_until timestamptz,
|
|
660
|
+
progress jsonb NOT NULL DEFAULT '{}'::jsonb,
|
|
661
|
+
completed_at timestamptz
|
|
662
|
+
);
|
|
663
|
+
CREATE UNIQUE INDEX IF NOT EXISTS ${quoteIdent(`${table}_open_uq`)}
|
|
664
|
+
ON ${t} (subject_type, subject_id) WHERE status NOT IN ('done', 'cancelled');
|
|
665
|
+
CREATE INDEX IF NOT EXISTS ${quoteIdent(`${table}_due_ix`)} ON ${t} (due_at) WHERE status IN ('pending', 'failed', 'running');`;
|
|
666
|
+
}
|
|
667
|
+
var COLS = "id, subject_type, subject_id, reason, status, requested_at, due_at, attempts, last_error, next_attempt_at, progress, completed_at";
|
|
668
|
+
function toDate(v) {
|
|
669
|
+
if (v === null || v === void 0) return void 0;
|
|
670
|
+
return v instanceof Date ? v : new Date(v);
|
|
671
|
+
}
|
|
672
|
+
function fromRow(r) {
|
|
673
|
+
const raw = typeof r.progress === "string" ? JSON.parse(r.progress) : r.progress ?? {};
|
|
674
|
+
const progress = {};
|
|
675
|
+
for (const [k, v] of Object.entries(raw)) progress[k] = { ...v, at: toDate(v.at) };
|
|
676
|
+
return {
|
|
677
|
+
id: r.id,
|
|
678
|
+
subject: { type: r.subject_type, id: r.subject_id },
|
|
679
|
+
reason: r.reason ?? void 0,
|
|
680
|
+
status: r.status,
|
|
681
|
+
requestedAt: toDate(r.requested_at),
|
|
682
|
+
dueAt: toDate(r.due_at),
|
|
683
|
+
attempts: Number(r.attempts),
|
|
684
|
+
lastError: r.last_error ?? void 0,
|
|
685
|
+
nextAttemptAt: toDate(r.next_attempt_at),
|
|
686
|
+
progress,
|
|
687
|
+
completedAt: toDate(r.completed_at)
|
|
688
|
+
};
|
|
689
|
+
}
|
|
690
|
+
var SqlDeletionRequestStore = class {
|
|
691
|
+
constructor(db, options = {}) {
|
|
692
|
+
this.db = db;
|
|
693
|
+
this.t = quoteIdent(options.table ?? "privacy_deletion_request");
|
|
694
|
+
}
|
|
695
|
+
async create(r) {
|
|
696
|
+
await this.db.query(
|
|
697
|
+
`INSERT INTO ${this.t} (id, subject_type, subject_id, reason, status, requested_at, due_at, attempts, progress)
|
|
698
|
+
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9::jsonb)`,
|
|
699
|
+
[r.id, r.subject.type, r.subject.id, r.reason ?? null, r.status, r.requestedAt, r.dueAt, r.attempts, JSON.stringify(r.progress)]
|
|
700
|
+
);
|
|
701
|
+
}
|
|
702
|
+
async get(id) {
|
|
703
|
+
const rows = rowsOf(await this.db.query(`SELECT ${COLS} FROM ${this.t} WHERE id = $1`, [id]));
|
|
704
|
+
return rows[0] ? fromRow(rows[0]) : null;
|
|
705
|
+
}
|
|
706
|
+
async findOpen(subject) {
|
|
707
|
+
const rows = rowsOf(
|
|
708
|
+
await this.db.query(
|
|
709
|
+
`SELECT ${COLS} FROM ${this.t} WHERE subject_type = $1 AND subject_id = $2 AND status NOT IN ('done','cancelled') LIMIT 1`,
|
|
710
|
+
[subject.type, subject.id]
|
|
711
|
+
)
|
|
712
|
+
);
|
|
713
|
+
return rows[0] ? fromRow(rows[0]) : null;
|
|
714
|
+
}
|
|
715
|
+
async listDue(now, limit, maxAttempts) {
|
|
716
|
+
const rows = rowsOf(
|
|
717
|
+
await this.db.query(
|
|
718
|
+
`SELECT ${COLS} FROM ${this.t}
|
|
719
|
+
WHERE (status = 'pending' AND due_at <= $1)
|
|
720
|
+
OR (status = 'failed' AND attempts < $3 AND coalesce(next_attempt_at, due_at) <= $1)
|
|
721
|
+
OR (status = 'running' AND coalesce(lease_until, $1) <= $1)
|
|
722
|
+
ORDER BY due_at LIMIT $2`,
|
|
723
|
+
[now, limit, maxAttempts]
|
|
724
|
+
)
|
|
725
|
+
);
|
|
726
|
+
return rows.map(fromRow);
|
|
727
|
+
}
|
|
728
|
+
async claim(id, now, leaseMs, maxAttempts) {
|
|
729
|
+
const rows = rowsOf(
|
|
730
|
+
await this.db.query(
|
|
731
|
+
`UPDATE ${this.t} SET status = 'running', lease_until = $2
|
|
732
|
+
WHERE id = $1 AND (
|
|
733
|
+
(status = 'pending' AND due_at <= $3)
|
|
734
|
+
OR (status = 'failed' AND attempts < $4 AND coalesce(next_attempt_at, due_at) <= $3)
|
|
735
|
+
OR (status = 'running' AND coalesce(lease_until, $3) <= $3))
|
|
736
|
+
RETURNING ${COLS}`,
|
|
737
|
+
[id, new Date(now.getTime() + leaseMs), now, maxAttempts]
|
|
738
|
+
)
|
|
739
|
+
);
|
|
740
|
+
return rows[0] ? fromRow(rows[0]) : null;
|
|
741
|
+
}
|
|
742
|
+
async saveProgress(id, rule, progress) {
|
|
743
|
+
await this.db.query(
|
|
744
|
+
`UPDATE ${this.t} SET progress = jsonb_set(progress, ARRAY[$2::text], $3::jsonb, true) WHERE id = $1`,
|
|
745
|
+
[id, rule, JSON.stringify(progress)]
|
|
746
|
+
);
|
|
747
|
+
}
|
|
748
|
+
async finish(id, patch) {
|
|
749
|
+
await this.db.query(
|
|
750
|
+
`UPDATE ${this.t} SET status = $2, last_error = $3, next_attempt_at = $4, completed_at = $5,
|
|
751
|
+
attempts = coalesce($6, attempts), lease_until = NULL WHERE id = $1`,
|
|
752
|
+
[id, patch.status, patch.lastError ?? null, patch.nextAttemptAt ?? null, patch.completedAt ?? null, patch.attempts ?? null]
|
|
753
|
+
);
|
|
754
|
+
}
|
|
755
|
+
};
|
|
756
|
+
export {
|
|
757
|
+
Anonymizer,
|
|
758
|
+
MemoryDeletionStore,
|
|
759
|
+
PRIVACY_OPTIONS,
|
|
760
|
+
PRIVACY_STORE,
|
|
761
|
+
PrivacyModule,
|
|
762
|
+
PrivacyService,
|
|
763
|
+
SqlDeletionRequestStore,
|
|
764
|
+
ZipWriter,
|
|
765
|
+
createZip,
|
|
766
|
+
planRegistry,
|
|
767
|
+
privacyTableSql
|
|
768
|
+
};
|