@blamejs/core 0.4.1

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.
Files changed (160) hide show
  1. package/CHANGELOG.md +230 -0
  2. package/LICENSE +201 -0
  3. package/LTS-CALENDAR.md +29 -0
  4. package/MIGRATING.md +7 -0
  5. package/NOTICE +59 -0
  6. package/README.md +100 -0
  7. package/bin/blamejs.js +13 -0
  8. package/index.js +253 -0
  9. package/lib/api-key.js +705 -0
  10. package/lib/api-snapshot.js +335 -0
  11. package/lib/app-shutdown.js +381 -0
  12. package/lib/app.js +364 -0
  13. package/lib/atomic-file.js +525 -0
  14. package/lib/audit-chain.js +168 -0
  15. package/lib/audit-sign.js +319 -0
  16. package/lib/audit-tools.js +682 -0
  17. package/lib/audit.js +753 -0
  18. package/lib/auth/jwt.js +280 -0
  19. package/lib/auth/oauth.js +691 -0
  20. package/lib/auth/passkey.js +185 -0
  21. package/lib/auth/password.js +139 -0
  22. package/lib/auth/totp.js +17 -0
  23. package/lib/auth-header.js +81 -0
  24. package/lib/backup/bundle.js +219 -0
  25. package/lib/backup/crypto.js +174 -0
  26. package/lib/backup/index.js +490 -0
  27. package/lib/backup/manifest.js +275 -0
  28. package/lib/bundler.js +295 -0
  29. package/lib/cache.js +819 -0
  30. package/lib/chain-writer.js +234 -0
  31. package/lib/cli-helpers.js +201 -0
  32. package/lib/cli.js +1377 -0
  33. package/lib/cluster-provider-db.js +245 -0
  34. package/lib/cluster-storage.js +166 -0
  35. package/lib/cluster.js +691 -0
  36. package/lib/consent.js +222 -0
  37. package/lib/constants.js +186 -0
  38. package/lib/cookies.js +293 -0
  39. package/lib/credential-hash.js +303 -0
  40. package/lib/crypto-field.js +159 -0
  41. package/lib/crypto.js +250 -0
  42. package/lib/db-query.js +297 -0
  43. package/lib/db-schema.js +250 -0
  44. package/lib/db.js +1054 -0
  45. package/lib/deprecate.js +226 -0
  46. package/lib/dev.js +324 -0
  47. package/lib/error-page.js +424 -0
  48. package/lib/events.js +135 -0
  49. package/lib/external-db.js +422 -0
  50. package/lib/forms.js +378 -0
  51. package/lib/framework-error.js +189 -0
  52. package/lib/framework-schema.js +604 -0
  53. package/lib/handlers.js +350 -0
  54. package/lib/html-balance.js +227 -0
  55. package/lib/http-client.js +615 -0
  56. package/lib/i18n.js +780 -0
  57. package/lib/jobs.js +181 -0
  58. package/lib/lazy-require.js +48 -0
  59. package/lib/log-stream-local.js +137 -0
  60. package/lib/log-stream-webhook.js +170 -0
  61. package/lib/log-stream.js +211 -0
  62. package/lib/log.js +355 -0
  63. package/lib/mail-bounce.js +507 -0
  64. package/lib/mail.js +701 -0
  65. package/lib/metrics.js +647 -0
  66. package/lib/middleware/api-encrypt.js +553 -0
  67. package/lib/middleware/attach-user.js +156 -0
  68. package/lib/middleware/body-parser.js +883 -0
  69. package/lib/middleware/bot-guard.js +148 -0
  70. package/lib/middleware/compression.js +436 -0
  71. package/lib/middleware/cors.js +236 -0
  72. package/lib/middleware/csp-nonce.js +332 -0
  73. package/lib/middleware/csrf-protect.js +275 -0
  74. package/lib/middleware/error-handler.js +46 -0
  75. package/lib/middleware/health.js +358 -0
  76. package/lib/middleware/index.js +52 -0
  77. package/lib/middleware/rate-limit.js +319 -0
  78. package/lib/middleware/request-id.js +53 -0
  79. package/lib/middleware/require-auth.js +95 -0
  80. package/lib/middleware/security-headers.js +91 -0
  81. package/lib/migrations.js +353 -0
  82. package/lib/mtls-ca.js +333 -0
  83. package/lib/mtls-engine-default.js +285 -0
  84. package/lib/nonce-store.js +177 -0
  85. package/lib/notify.js +643 -0
  86. package/lib/ntp-check.js +178 -0
  87. package/lib/object-store/azure-blob.js +467 -0
  88. package/lib/object-store/gcs.js +469 -0
  89. package/lib/object-store/http-put.js +153 -0
  90. package/lib/object-store/index.js +140 -0
  91. package/lib/object-store/local.js +163 -0
  92. package/lib/object-store/retry.js +15 -0
  93. package/lib/object-store/sigv4.js +535 -0
  94. package/lib/observability.js +114 -0
  95. package/lib/pagination.js +371 -0
  96. package/lib/parsers/index.js +64 -0
  97. package/lib/parsers/safe-csv.js +224 -0
  98. package/lib/parsers/safe-env.js +614 -0
  99. package/lib/parsers/safe-toml.js +745 -0
  100. package/lib/parsers/safe-xml.js +379 -0
  101. package/lib/parsers/safe-yaml.js +977 -0
  102. package/lib/permissions.js +430 -0
  103. package/lib/pqc-agent.js +85 -0
  104. package/lib/pqc-gate.js +266 -0
  105. package/lib/protocol-dispatcher.js +144 -0
  106. package/lib/queue-local.js +327 -0
  107. package/lib/queue.js +430 -0
  108. package/lib/redact.js +192 -0
  109. package/lib/render.js +193 -0
  110. package/lib/request-helpers.js +178 -0
  111. package/lib/restore-bundle.js +239 -0
  112. package/lib/restore-rollback.js +254 -0
  113. package/lib/restore.js +301 -0
  114. package/lib/retry.js +329 -0
  115. package/lib/router.js +437 -0
  116. package/lib/safe-async.js +520 -0
  117. package/lib/safe-buffer.js +162 -0
  118. package/lib/safe-json.js +532 -0
  119. package/lib/safe-schema.js +1176 -0
  120. package/lib/safe-sql.js +157 -0
  121. package/lib/safe-url.js +109 -0
  122. package/lib/scheduler.js +680 -0
  123. package/lib/seeders.js +622 -0
  124. package/lib/session.js +304 -0
  125. package/lib/slug.js +243 -0
  126. package/lib/static.js +268 -0
  127. package/lib/storage.js +470 -0
  128. package/lib/subject.js +281 -0
  129. package/lib/template.js +781 -0
  130. package/lib/testing.js +621 -0
  131. package/lib/totp.js +285 -0
  132. package/lib/tracing.js +484 -0
  133. package/lib/validate-opts.js +56 -0
  134. package/lib/vault/index.js +299 -0
  135. package/lib/vault/passphrase-ops.js +311 -0
  136. package/lib/vault/passphrase-source.js +198 -0
  137. package/lib/vault/rotate.js +761 -0
  138. package/lib/vault/wrap.js +289 -0
  139. package/lib/vendor/MANIFEST.json +84 -0
  140. package/lib/vendor/argon2/argon2.cjs +466 -0
  141. package/lib/vendor/argon2/argon2.d.cts +62 -0
  142. package/lib/vendor/argon2/package.json +1 -0
  143. package/lib/vendor/argon2/prebuilds/darwin-arm64/argon2.armv8.glibc.node +0 -0
  144. package/lib/vendor/argon2/prebuilds/darwin-x64/argon2.glibc.node +0 -0
  145. package/lib/vendor/argon2/prebuilds/freebsd-arm64/argon2.armv8.glibc.node +0 -0
  146. package/lib/vendor/argon2/prebuilds/freebsd-x64/argon2.glibc.node +0 -0
  147. package/lib/vendor/argon2/prebuilds/linux-arm/argon2.armv7.glibc.node +0 -0
  148. package/lib/vendor/argon2/prebuilds/linux-arm/argon2.armv7.musl.node +0 -0
  149. package/lib/vendor/argon2/prebuilds/linux-arm64/argon2.armv8.glibc.node +0 -0
  150. package/lib/vendor/argon2/prebuilds/linux-arm64/argon2.armv8.musl.node +0 -0
  151. package/lib/vendor/argon2/prebuilds/linux-x64/argon2.glibc.node +0 -0
  152. package/lib/vendor/argon2/prebuilds/linux-x64/argon2.musl.node +0 -0
  153. package/lib/vendor/argon2/prebuilds/win32-x64/argon2.glibc.node +0 -0
  154. package/lib/vendor/noble-ciphers.cjs +9 -0
  155. package/lib/vendor/pki.cjs +181 -0
  156. package/lib/vendor/simplewebauthn-server.cjs +328 -0
  157. package/lib/webhook.js +632 -0
  158. package/lib/websocket-channels.js +413 -0
  159. package/lib/websocket.js +833 -0
  160. package/package.json +39 -0
package/lib/subject.js ADDED
@@ -0,0 +1,281 @@
1
+ "use strict";
2
+ /**
3
+ * Data subject rights primitives — GDPR Articles 15–22, AU Privacy Act
4
+ * Privacy Act Review (right to erasure), and HIPAA §164.524.
5
+ *
6
+ * App schema declares per-table `subjectField` (the column that points to
7
+ * the subject) and `personalDataCategories` (semantic tag for RoPA). This
8
+ * module then walks every table that knows about a given subject without
9
+ * the app having to plumb subject IDs through repository code.
10
+ *
11
+ * Public API:
12
+ * subject.export(subjectId, opts) → { tableName: [unsealed rows] }
13
+ * subject.rectify(subjectId, { table, id, changes, reason })
14
+ * subject.erase(subjectId, { reason, acknowledgements })
15
+ * subject.restrict(subjectId, { on, reason })
16
+ * subject.recordObjection(subjectId, { purpose, reason })
17
+ * subject.isRestricted(subjectId) → boolean
18
+ *
19
+ * Erasure model: physical row deletion with the audit chain preserved
20
+ * (the subject's data rows are gone; the audit_log entries about them
21
+ * remain hash-linked). This satisfies GDPR Art. 17 in the strict sense
22
+ * (subject data is erased) at the cost of the more granular
23
+ * cryptographic-erasure property (per-subject key destruction) the spec
24
+ * aspires to — that variant requires per-subject derivation keys, which
25
+ * the framework does not currently maintain.
26
+ */
27
+ var { sha3Hash } = require("./crypto");
28
+ var cryptoField = require("./crypto-field");
29
+ var audit = require("./audit");
30
+ var cluster = require("./cluster");
31
+ var lazyRequire = require("./lazy-require");
32
+
33
+ var db = lazyRequire(function () { return require("./db"); });
34
+
35
+ // Required acknowledgements before subject.erase will run. Operator must
36
+ // explicitly attest each one to confirm no statutory retention or active
37
+ // litigation hold blocks the deletion.
38
+ var REQUIRED_ERASE_ACKS = ["no-litigation-hold", "no-statutory-retention-required"];
39
+
40
+ // ---- Export (Art. 15, Art. 20) ----
41
+
42
+ function exportData(subjectId, opts) {
43
+ if (!subjectId) throw new Error("subject.export requires a subjectId");
44
+ opts = opts || {};
45
+ var include = opts.include || "all";
46
+
47
+ var tables = db()._getSubjectTables();
48
+ if (tables.length === 0) {
49
+ return _writeAudit("subject.export", subjectId, "success", { reason: opts.reason || null }, {});
50
+ }
51
+
52
+ var dump = {};
53
+ for (var i = 0; i < tables.length; i++) {
54
+ var t = tables[i];
55
+ if (include !== "all" && include.indexOf(t.name) === -1) continue;
56
+
57
+ // Look up via derivedHash if the subjectField is sealed; otherwise raw equality.
58
+ var rows = _findRowsForSubject(t.name, t.subjectField, subjectId);
59
+ if (rows.length > 0) dump[t.name] = rows;
60
+ }
61
+
62
+ _writeAudit("subject.export", subjectId, "success", { reason: opts.reason || null, tables: Object.keys(dump) });
63
+ return dump;
64
+ }
65
+
66
+ function _findRowsForSubject(tableName, subjectField, subjectId) {
67
+ var hash = db().hashFor(tableName, subjectField, subjectId);
68
+ if (hash) {
69
+ // The schema has a derived hash for the subjectField — look up via that
70
+ var derivedFieldName = _getDerivedFieldName(tableName, subjectField);
71
+ if (derivedFieldName) {
72
+ var pred = {};
73
+ pred[derivedFieldName] = hash;
74
+ return db().from(tableName).where(pred).all();
75
+ }
76
+ }
77
+ // No derived hash — assume subjectField is raw, do direct equality
78
+ var rawPred = {};
79
+ rawPred[subjectField] = subjectId;
80
+ return db().from(tableName).where(rawPred).all();
81
+ }
82
+
83
+ function _getDerivedFieldName(tableName, sourceField) {
84
+ var schema = cryptoField.getSchema(tableName);
85
+ if (!schema || !schema.derivedHashes) return null;
86
+ for (var derivedField in schema.derivedHashes) {
87
+ if (schema.derivedHashes[derivedField].from === sourceField) return derivedField;
88
+ }
89
+ return null;
90
+ }
91
+
92
+ // ---- Rectify (Art. 16) ----
93
+
94
+ function rectify(subjectId, opts) {
95
+ cluster.requireLeader();
96
+ if (!subjectId) throw new Error("subject.rectify requires a subjectId");
97
+ if (!opts || !opts.table || !opts.id || !opts.changes) {
98
+ throw new Error("subject.rectify requires { table, id, changes }");
99
+ }
100
+
101
+ // Read current values for audit metadata
102
+ var before = db().from(opts.table).where({ _id: opts.id }).first();
103
+ if (!before) {
104
+ _writeAudit("subject.rectify", subjectId, "failure", {
105
+ reason: "row not found",
106
+ table: opts.table,
107
+ rowId: opts.id,
108
+ requestReason: opts.reason,
109
+ });
110
+ throw new Error("subject.rectify: row not found in '" + opts.table + "' with _id '" + opts.id + "'");
111
+ }
112
+
113
+ var changedKeys = Object.keys(opts.changes);
114
+ var beforeValues = {};
115
+ for (var i = 0; i < changedKeys.length; i++) beforeValues[changedKeys[i]] = before[changedKeys[i]];
116
+
117
+ var ok = db().from(opts.table).where({ _id: opts.id }).updateOne(opts.changes);
118
+
119
+ _writeAudit("subject.rectify", subjectId, ok ? "success" : "failure", {
120
+ table: opts.table,
121
+ rowId: opts.id,
122
+ fieldsChanged: changedKeys,
123
+ requestReason: opts.reason,
124
+ // before/after values are sealed in the audit metadata too (sealing
125
+ // happens at the audit_log boundary because metadata is in the seal list)
126
+ before: beforeValues,
127
+ after: opts.changes,
128
+ });
129
+
130
+ return ok;
131
+ }
132
+
133
+ // ---- Erase (Art. 17 right to be forgotten) ----
134
+
135
+ function erase(subjectId, opts) {
136
+ cluster.requireLeader();
137
+ if (!subjectId) throw new Error("subject.erase requires a subjectId");
138
+ if (!opts || !opts.reason) {
139
+ throw new Error("subject.erase requires { reason } — e.g. 'GDPR Art. 17 request 2026-04-25 ticket #4471'");
140
+ }
141
+ if (!Array.isArray(opts.acknowledgements)) {
142
+ throw new Error("subject.erase requires { acknowledgements: [...] } — see REQUIRED_ERASE_ACKS");
143
+ }
144
+ for (var i = 0; i < REQUIRED_ERASE_ACKS.length; i++) {
145
+ if (opts.acknowledgements.indexOf(REQUIRED_ERASE_ACKS[i]) === -1) {
146
+ throw new Error(
147
+ "subject.erase: missing required acknowledgement '" + REQUIRED_ERASE_ACKS[i] + "'. " +
148
+ "Operator must attest no litigation hold and no statutory retention before erasure."
149
+ );
150
+ }
151
+ }
152
+
153
+ var tables = db()._getSubjectTables();
154
+ var totalDeleted = 0;
155
+ var perTable = {};
156
+
157
+ for (var t = 0; t < tables.length; t++) {
158
+ var spec = tables[t];
159
+ var hash = db().hashFor(spec.name, spec.subjectField, subjectId);
160
+ var pred;
161
+ if (hash) {
162
+ var derivedField = _getDerivedFieldName(spec.name, spec.subjectField);
163
+ if (derivedField) {
164
+ pred = {}; pred[derivedField] = hash;
165
+ } else {
166
+ pred = {}; pred[spec.subjectField] = subjectId;
167
+ }
168
+ } else {
169
+ pred = {}; pred[spec.subjectField] = subjectId;
170
+ }
171
+ var deleted = db().from(spec.name).where(pred).deleteMany();
172
+ totalDeleted += deleted;
173
+ perTable[spec.name] = deleted;
174
+ }
175
+
176
+ // Mark subject as erased (so future writes refuse to mention them)
177
+ _markErased(subjectId);
178
+
179
+ _writeAudit("subject.erase", subjectId, "success", {
180
+ requestReason: opts.reason,
181
+ rowsDeleted: totalDeleted,
182
+ perTable: perTable,
183
+ acknowledgements: opts.acknowledgements,
184
+ });
185
+
186
+ return { rowsDeleted: totalDeleted, perTable: perTable };
187
+ }
188
+
189
+ // ---- Restrict (Art. 18) ----
190
+
191
+ function restrict(subjectId, opts) {
192
+ cluster.requireLeader();
193
+ if (!subjectId) throw new Error("subject.restrict requires a subjectId");
194
+ if (!opts || typeof opts.on !== "boolean") {
195
+ throw new Error("subject.restrict requires { on: true|false }");
196
+ }
197
+ var existing = db().prepare(
198
+ "SELECT subjectIdHash FROM _blamejs_subject_restrictions WHERE subjectIdHash = ?"
199
+ ).get(_subjectHash(subjectId));
200
+
201
+ if (opts.on) {
202
+ if (!existing) {
203
+ db().prepare(
204
+ "INSERT INTO _blamejs_subject_restrictions (subjectIdHash, since, reason) VALUES (?, ?, ?)"
205
+ ).run(_subjectHash(subjectId), Date.now(), opts.reason || null);
206
+ }
207
+ } else if (existing) {
208
+ db().prepare(
209
+ "DELETE FROM _blamejs_subject_restrictions WHERE subjectIdHash = ?"
210
+ ).run(_subjectHash(subjectId));
211
+ }
212
+
213
+ _writeAudit("subject.restrict", subjectId, "success", {
214
+ on: opts.on,
215
+ reason: opts.reason || null,
216
+ });
217
+ return true;
218
+ }
219
+
220
+ function isRestricted(subjectId) {
221
+ if (!subjectId) return false;
222
+ var row = db().prepare(
223
+ "SELECT 1 FROM _blamejs_subject_restrictions WHERE subjectIdHash = ?"
224
+ ).get(_subjectHash(subjectId));
225
+ return !!row;
226
+ }
227
+
228
+ // ---- Object (Art. 21) ----
229
+
230
+ function recordObjection(subjectId, opts) {
231
+ cluster.requireLeader();
232
+ if (!subjectId) throw new Error("subject.recordObjection requires a subjectId");
233
+ if (!opts || !opts.purpose) throw new Error("subject.recordObjection requires { purpose }");
234
+ _writeAudit("subject.objection", subjectId, "success", {
235
+ purpose: opts.purpose,
236
+ reason: opts.reason || null,
237
+ });
238
+ return true;
239
+ }
240
+
241
+ // ---- Internal helpers ----
242
+
243
+ function _markErased(subjectId) {
244
+ db().prepare(
245
+ "INSERT OR REPLACE INTO _blamejs_subject_erasures (subjectIdHash, erasedAt) VALUES (?, ?)"
246
+ ).run(_subjectHash(subjectId), Date.now());
247
+ }
248
+
249
+ function _subjectHash(subjectId) {
250
+ // Use the framework's email-style namespace; the consistent thing matters,
251
+ // not which prefix. Subject IDs are typically opaque already.
252
+ return sha3Hash("bj-subject:" + String(subjectId));
253
+ }
254
+
255
+ function _writeAudit(action, subjectId, outcome, metadata) {
256
+ // recordSafe — audit failure must not roll back the subject mutation
257
+ // that already touched the database. Best-effort emission with errors
258
+ // swallowed; operators see them in stderr if they fire.
259
+ audit.emit({
260
+ actor: {},
261
+ action: action,
262
+ resource: { kind: "subject", id: subjectId },
263
+ outcome: outcome,
264
+ reason: metadata && metadata.requestReason ? metadata.requestReason : null,
265
+ metadata: metadata || null,
266
+ });
267
+ }
268
+
269
+ function _resetForTest() { db.reset(); }
270
+
271
+ module.exports = {
272
+ export: exportData,
273
+ exportData: exportData, // alias — `export` is a reserved word in some toolchains
274
+ rectify: rectify,
275
+ erase: erase,
276
+ restrict: restrict,
277
+ isRestricted: isRestricted,
278
+ recordObjection: recordObjection,
279
+ REQUIRED_ERASE_ACKS: REQUIRED_ERASE_ACKS,
280
+ _resetForTest: _resetForTest,
281
+ };