instant_record 0.1.0 → 0.3.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.
Files changed (198) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +58 -0
  3. data/README.md +267 -61
  4. data/app/controllers/instant_record/bootstraps_controller.rb +39 -12
  5. data/app/controllers/instant_record/events_controller.rb +58 -6
  6. data/app/controllers/instant_record/files_controller.rb +116 -0
  7. data/app/controllers/instant_record/mutations_controller.rb +84 -5
  8. data/app/controllers/instant_record/native_screens_controller.rb +60 -0
  9. data/app/controllers/instant_record/records_controller.rb +86 -8
  10. data/app/controllers/instant_record/shells_controller.rb +64 -0
  11. data/app/controllers/instant_record/sync_notices_controller.rb +81 -0
  12. data/app/helpers/instant_record/sync_notices_helper.rb +41 -0
  13. data/app/jobs/instant_record/shell_build_job.rb +16 -0
  14. data/app/models/instant_record/change.rb +36 -3
  15. data/app/models/instant_record/mutation_applier.rb +633 -50
  16. data/app/views/instant_record/sync_notices/_notices.html.erb +63 -0
  17. data/compiled/README.md +272 -0
  18. data/compiled/pipeline/browser_migrations.rb +18 -0
  19. data/compiled/pipeline/build.rb +13 -0
  20. data/compiled/pipeline/build_native.rb +14 -0
  21. data/compiled/pipeline/native/host.c +78 -0
  22. data/compiled/pipeline/native/instant_record_native.h +57 -0
  23. data/compiled/pipeline/native_shim.c +149 -0
  24. data/compiled/pipeline/reactor_shim.c +66 -0
  25. data/compiled/pipeline/sqlite/rh_shim.c +5 -0
  26. data/compiled/pipeline/sqlite_release.rb +43 -0
  27. data/compiled/toolchain.env.example +22 -0
  28. data/compiled/web/index.html +20 -0
  29. data/compiled/web/package-lock.json +884 -0
  30. data/compiled/web/package.json +17 -0
  31. data/compiled/web/src/app-host-core.js +556 -0
  32. data/compiled/web/src/app-host.js +16 -0
  33. data/compiled/web/src/branch-manager.js +140 -0
  34. data/compiled/web/src/branch-preview.js +397 -0
  35. data/compiled/web/src/changes.js +191 -0
  36. data/compiled/web/src/faults.js +172 -0
  37. data/compiled/web/src/flight-recorder.js +347 -0
  38. data/compiled/web/src/history-fill.js +68 -0
  39. data/compiled/web/src/http-headers.js +100 -0
  40. data/compiled/web/src/leader-election.js +705 -0
  41. data/compiled/web/src/main.js +608 -0
  42. data/compiled/web/src/manifest.js +112 -0
  43. data/compiled/web/src/opfs-wasi-core.js +109 -0
  44. data/compiled/web/src/opfs-wasi-file.js +8 -0
  45. data/compiled/web/src/reactor-runtime.js +1692 -0
  46. data/compiled/web/src/redactor.js +518 -0
  47. data/compiled/web/src/release-updates.js +48 -0
  48. data/compiled/web/src/replay.js +338 -0
  49. data/compiled/web/src/schema-recovery.js +204 -0
  50. data/compiled/web/src/server-request.js +68 -0
  51. data/compiled/web/src/sha256.js +98 -0
  52. data/compiled/web/src/shell.js +52 -0
  53. data/compiled/web/src/snapshot-store.js +38 -0
  54. data/compiled/web/src/sqlite-redactor.js +111 -0
  55. data/compiled/web/src/storage-backend.js +159 -0
  56. data/compiled/web/src/stream-leader.js +675 -0
  57. data/compiled/web/src/sync-context.js +91 -0
  58. data/compiled/web/src/sync-drain.js +104 -0
  59. data/compiled/web/src/sync-schedule.js +9 -0
  60. data/compiled/web/src/wasi-minimal.js +275 -0
  61. data/compiled/web/src/worker.js +39 -0
  62. data/compiled/web/vite.config.js +27 -0
  63. data/config/routes.rb +25 -0
  64. data/db/migrate/20261119000201_add_scope_to_instant_record_changes.rb +7 -0
  65. data/db/migrate/20261121000001_create_instant_record_sync_notices.rb +21 -0
  66. data/db/migrate/20261121000101_add_partition_to_instant_record_changes.rb +8 -0
  67. data/db/migrate/20261121230300_add_delay_line_to_instant_record_outbox.rb +10 -0
  68. data/exe/instant_record_mcp +6 -0
  69. data/frontend/LiveList.js +67 -0
  70. data/frontend/chord.js +79 -0
  71. data/frontend/file.js +65 -0
  72. data/frontend/files.js +738 -0
  73. data/frontend/focus.js +10 -0
  74. data/frontend/held.js +192 -0
  75. data/frontend/http.js +76 -0
  76. data/frontend/index.js +53 -0
  77. data/frontend/keyboard.js +56 -0
  78. data/frontend/live.js +298 -0
  79. data/frontend/notices.js +118 -0
  80. data/frontend/package.json +15 -0
  81. data/frontend/range.js +10 -0
  82. data/frontend/selection.js +47 -0
  83. data/frontend/shortcuts.js +25 -0
  84. data/frontend/sync-notices.js +130 -0
  85. data/frontend/undo.js +48 -0
  86. data/frontend/window.js +181 -0
  87. data/lib/generators/instant_record/install/install_generator.rb +18 -30
  88. data/lib/generators/instant_record/install/templates/instant_record.rb +34 -0
  89. data/lib/generators/instant_record/ios/ios_generator.rb +71 -0
  90. data/lib/generators/instant_record/ios/templates/App.swift.tt +35 -0
  91. data/lib/generators/instant_record/ios/templates/Info.plist +11 -0
  92. data/lib/generators/instant_record/ios/templates/LibraryEngine.swift +30 -0
  93. data/lib/instant_record/branch/sqlite_store.rb +142 -0
  94. data/lib/instant_record/branch.rb +388 -0
  95. data/lib/instant_record/client/notifier.rb +8 -12
  96. data/lib/instant_record/client/rebaser.rb +565 -0
  97. data/lib/instant_record/client/transport.rb +64 -42
  98. data/lib/instant_record/client.rb +1600 -169
  99. data/lib/instant_record/compiled_site.rb +85 -0
  100. data/lib/instant_record/compiler/app_stage.rb +212 -0
  101. data/lib/instant_record/compiler/ast_lowerer.rb +659 -0
  102. data/lib/instant_record/compiler/browser_migrations.rb +161 -0
  103. data/lib/instant_record/compiler/entry_builder.rb +832 -0
  104. data/lib/instant_record/compiler/fts5_smoke.rb +205 -0
  105. data/lib/instant_record/compiler/gem_vendor.rb +194 -0
  106. data/lib/instant_record/compiler/host_adapters.rb +506 -0
  107. data/lib/instant_record/compiler/kotlin_codegen.rb +209 -0
  108. data/lib/instant_record/compiler/manifest.rb +178 -0
  109. data/lib/instant_record/compiler/native_build.rb +586 -0
  110. data/lib/instant_record/compiler/native_contracts.rb +338 -0
  111. data/lib/instant_record/compiler/path_scrubber.rb +31 -0
  112. data/lib/instant_record/compiler/reachability_tracer.rb +1188 -0
  113. data/lib/instant_record/compiler/route_analyzer.rb +623 -0
  114. data/lib/instant_record/compiler/runner.rb +42 -0
  115. data/lib/instant_record/compiler/schema_lock.rb +606 -0
  116. data/lib/instant_record/compiler/source_pages.rb +77 -0
  117. data/lib/instant_record/compiler/static_linter.rb +770 -0
  118. data/lib/instant_record/compiler/swift_codegen.rb +341 -0
  119. data/lib/instant_record/compiler/toolchain.rb +219 -0
  120. data/lib/instant_record/compiler/wasm_build.rb +704 -0
  121. data/lib/instant_record/compiler/wasm_tree.rb +518 -0
  122. data/lib/instant_record/compiler.rb +277 -0
  123. data/lib/instant_record/configuration.rb +104 -0
  124. data/lib/instant_record/engine.rb +68 -18
  125. data/lib/instant_record/file_store.rb +162 -0
  126. data/lib/instant_record/files.rb +92 -0
  127. data/lib/instant_record/hlc.rb +387 -0
  128. data/lib/instant_record/host.rb +66 -0
  129. data/lib/instant_record/inertia/renderer.rb +52 -0
  130. data/lib/instant_record/inertia.rb +222 -0
  131. data/lib/instant_record/mcp/cli.rb +319 -0
  132. data/lib/instant_record/mcp/host_process.rb +229 -0
  133. data/lib/instant_record/mcp/http_exchange.rb +233 -0
  134. data/lib/instant_record/mcp/replica.rb +556 -0
  135. data/lib/instant_record/mcp/runtime.rb +406 -0
  136. data/lib/instant_record/mcp/server.rb +429 -0
  137. data/lib/instant_record/mcp.rb +47 -0
  138. data/lib/instant_record/native/contract.rb +367 -0
  139. data/lib/instant_record/native/node.rb +125 -0
  140. data/lib/instant_record/native/screen.rb +366 -0
  141. data/lib/instant_record/native/xcode_project.rb +344 -0
  142. data/lib/instant_record/native.rb +41 -0
  143. data/lib/instant_record/outbox_mutation.rb +81 -9
  144. data/lib/instant_record/outbox_upcaster.rb +161 -0
  145. data/lib/instant_record/read_tracker.rb +610 -0
  146. data/lib/instant_record/routing.rb +33 -0
  147. data/lib/instant_record/runtime_scoped.rb +4 -0
  148. data/lib/instant_record/shell.rb +486 -0
  149. data/lib/instant_record/sync_actions.rb +800 -0
  150. data/lib/instant_record/sync_metadata.rb +17 -2
  151. data/lib/instant_record/sync_notice.rb +234 -0
  152. data/lib/instant_record/sync_partition.rb +63 -0
  153. data/lib/instant_record/sync_scope.rb +300 -0
  154. data/lib/instant_record/sync_shape.rb +102 -0
  155. data/lib/instant_record/sync_window.rb +92 -15
  156. data/lib/instant_record/syncable.rb +313 -17
  157. data/lib/instant_record/testing/authoritative_server.rb +547 -0
  158. data/lib/instant_record/testing/chaos_simulator.rb +429 -0
  159. data/lib/instant_record/testing/cruby_host_bridge.rb +370 -0
  160. data/lib/instant_record/testing/fault_network.rb +140 -0
  161. data/lib/instant_record/testing/parity_suite.rb +435 -0
  162. data/lib/instant_record/testing/runtimes/base.rb +184 -0
  163. data/lib/instant_record/testing/runtimes/cruby_runtime.rb +255 -0
  164. data/lib/instant_record/testing/runtimes/native_runtime.rb +346 -0
  165. data/lib/instant_record/testing/runtimes/wasm_runtime.rb +371 -0
  166. data/lib/instant_record/testing/wasm_host_bridge.mjs +240 -0
  167. data/lib/instant_record/testing.rb +333 -0
  168. data/lib/instant_record/trace/redactor.rb +278 -0
  169. data/lib/instant_record/trace/replayer.rb +126 -0
  170. data/lib/instant_record/trace/schema_extractor.rb +37 -0
  171. data/lib/instant_record/trace.rb +22 -0
  172. data/lib/instant_record/version.rb +1 -1
  173. data/lib/instant_record.rb +107 -37
  174. data/lib/tasks/instant_record.rake +299 -47
  175. data/native/ios/InstantRecordNative/Package.swift +12 -0
  176. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/AppHost.swift +706 -0
  177. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Engine.swift +64 -0
  178. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/FileStore.swift +1048 -0
  179. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/HTTPEngine.swift +36 -0
  180. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Icons.swift +19 -0
  181. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Node.swift +64 -0
  182. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/ScreenView.swift +481 -0
  183. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Screens.swift +94 -0
  184. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/StreamClient.swift +74 -0
  185. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/SyncNotice.swift +282 -0
  186. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/SyncSchedule.swift +153 -0
  187. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Theme.swift +140 -0
  188. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Transport.swift +108 -0
  189. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/TypedContracts.swift +237 -0
  190. data/native/ios/README.md +341 -0
  191. data/sig/instant_record/inertia.rbs +47 -0
  192. data/sig/instant_record/native.rbs +38 -0
  193. metadata +194 -18
  194. data/lib/generators/instant_record/install/templates/database.js +0 -32
  195. data/lib/generators/instant_record/install/templates/index.html +0 -69
  196. data/lib/generators/instant_record/install/templates/rails.sw.js +0 -750
  197. data/lib/instant_record/local_schema.rb +0 -75
  198. data/lib/instant_record/pglite_compat.rb +0 -40
@@ -0,0 +1,518 @@
1
+ // Schema-aware PII redaction with deterministic per-trace pseudonymization.
2
+ // Preserves structural columns (PKs, FKs, timestamps, sync bookkeeping) and
3
+ // value equality within a trace so replayed bugs keep their exact control flow
4
+ // without leaking emails, credentials, cookies, or personal text.
5
+ import { sha256Hex } from "./sha256.js";
6
+
7
+ const decoder = new TextDecoder();
8
+
9
+ export const STRUCTURAL_SAFE_COLUMNS = new Set([
10
+ "id",
11
+ "created_at",
12
+ "updated_at",
13
+ "deleted_at",
14
+ "server_version",
15
+ "sync_state",
16
+ "cursor",
17
+ "operation",
18
+ "record_type",
19
+ "record_id",
20
+ "mutation_id",
21
+ "base_version",
22
+ "status",
23
+ "kind",
24
+ "type",
25
+ "version",
26
+ "has_more",
27
+ "position",
28
+ "done",
29
+ "completed",
30
+ "archived",
31
+ "unread",
32
+ "starred",
33
+ "read_at",
34
+ "sent_at",
35
+ "published_at",
36
+ "role",
37
+ "state",
38
+ ]);
39
+
40
+ export const DEFAULT_PII_PATTERNS = [
41
+ /(^|_)e?mail(_|$|s$|_address$)/i,
42
+ /(^|_)(phone|mobile|tel|telephone|fax)(_|$)/i,
43
+ /(^|_)(password|passwd|pwd|secret|token|api_key|access_key|private_key|auth|credential|bearer)(_|$)/i,
44
+ /(^|_)(ssn|social_security|tax_id|passport|license_number|national_id)(_|$)/i,
45
+ /(^|_)(credit_card|card_number|cvv|cvc|iban|routing_number|account_number)(_|$)/i,
46
+ /(^|_)(address|street|city|zip|postal|postcode)(_|$)/i,
47
+ /(^|_)(ip|ip_address|user_agent)(_|$)/i,
48
+ /(^|_)(cookie|session|csrf)(_|$)/i,
49
+ /(^|_)(first_name|last_name|full_name|real_name|display_name|username|dob|birth_?date)(_|$)/i,
50
+ /(^|_)(from_address|to_address|cc|bcc|reply_to|sender|recipient|from_email|to_email|author_email)(_|$)/i,
51
+ /^identity$/i,
52
+ ];
53
+
54
+ const SENSITIVE_HEADER_RE = /^(cookie|set-cookie|authorization|proxy-authorization|x-csrf-token|x-api-key|x-auth-token)$/i;
55
+ const SENSITIVE_QUERY_PARAM_RE = /(scope|identity|token|secret|key|password|passwd|email|auth|session|sig|signature)/i;
56
+ const SENSITIVE_ENV_RE = /(secret|token|key|password|passwd|auth|cookie|credential)/i;
57
+ const EMAIL_VALUE_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
58
+
59
+ export function modelNameToTableName(modelName) {
60
+ if (!modelName) return "";
61
+ const base = String(modelName).split("::").pop();
62
+ const snake = base
63
+ .replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2")
64
+ .replace(/([a-z\d])([A-Z])/g, "$1_$2")
65
+ .toLowerCase();
66
+ if (snake.endsWith("y") && !/[aeiou]y$/.test(snake)) return snake.slice(0, -1) + "ies";
67
+ if (/(s|x|z|ch|sh)$/.test(snake)) return snake + "es";
68
+ return snake + "s";
69
+ }
70
+
71
+ function normalizeSchema(schema) {
72
+ const normalized = {};
73
+ if (!schema || typeof schema !== "object") return normalized;
74
+ for (const [table, cols] of Object.entries(schema)) {
75
+ if (Array.isArray(cols)) {
76
+ normalized[table.toLowerCase()] = cols.map((col) =>
77
+ typeof col === "string" ? { name: col, type: "string" } : { name: String(col.name), type: String(col.type || "string") },
78
+ );
79
+ } else if (cols && typeof cols === "object") {
80
+ normalized[table.toLowerCase()] = Object.entries(cols).map(([name, type]) => ({ name, type: String(type || "string") }));
81
+ }
82
+ }
83
+ return normalized;
84
+ }
85
+
86
+ export class Redactor {
87
+ constructor({ schema = {}, piiColumns = {}, safeColumns = {}, salt = null } = {}) {
88
+ this.schema = normalizeSchema(schema);
89
+ this.explicitPii = new Map();
90
+ this.explicitSafe = new Map();
91
+ for (const [table, cols] of Object.entries(piiColumns || {})) {
92
+ this.explicitPii.set(table.toLowerCase(), new Set(Array.from(cols, (c) => String(c).toLowerCase())));
93
+ }
94
+ for (const [table, cols] of Object.entries(safeColumns || {})) {
95
+ this.explicitSafe.set(table.toLowerCase(), new Set(Array.from(cols, (c) => String(c).toLowerCase())));
96
+ }
97
+ this.salt = salt || randomSalt();
98
+ this.redactedFields = new Set();
99
+ this.redactedColumns = {};
100
+ }
101
+
102
+ isPiiColumn(tableOrModel, columnName) {
103
+ const col = String(columnName || "").toLowerCase();
104
+ if (!col) return false;
105
+ const table = this.resolveTableName(tableOrModel);
106
+ if (this.explicitSafe.get(table)?.has(col) || this.explicitSafe.get("*")?.has(col)) return false;
107
+ if (this.explicitPii.get(table)?.has(col) || this.explicitPii.get("*")?.has(col)) return true;
108
+ if (/(^|_)(tax|national)_id$/.test(col)) return true;
109
+ if (STRUCTURAL_SAFE_COLUMNS.has(col) || col.endsWith("_id") || col.endsWith("_at")) return false;
110
+ return DEFAULT_PII_PATTERNS.some((pattern) => pattern.test(col));
111
+ }
112
+
113
+ resolveTableName(tableOrModel) {
114
+ if (!tableOrModel) return "*";
115
+ const lower = String(tableOrModel).toLowerCase();
116
+ if (this.schema[lower] || this.explicitPii.has(lower) || this.explicitSafe.has(lower)) return lower;
117
+ const guessed = modelNameToTableName(tableOrModel);
118
+ if (this.schema[guessed] || this.explicitPii.has(guessed) || this.explicitSafe.has(guessed)) return guessed;
119
+ return guessed || lower;
120
+ }
121
+
122
+ schemaPiiMap(extraSchema = null) {
123
+ const merged = { ...this.schema, ...normalizeSchema(extraSchema) };
124
+ const result = {};
125
+ for (const [table, columns] of Object.entries(merged)) {
126
+ if (table === "schema_migrations" || table === "ar_internal_metadata" || table === "instant_record_sync_metadata") continue;
127
+ const sensitive = columns
128
+ .map((c) => c.name)
129
+ .filter((col) => this.isPiiColumn(table, col));
130
+ if (sensitive.length > 0) result[table] = sensitive;
131
+ }
132
+ for (const [table, cols] of this.explicitPii.entries()) {
133
+ if (table === "*") continue;
134
+ const existing = new Set(result[table] || []);
135
+ for (const col of cols) existing.add(col);
136
+ if (existing.size > 0) result[table] = [...existing];
137
+ }
138
+ return result;
139
+ }
140
+
141
+ hasSchemaPii(extraSchema = null) {
142
+ return Object.keys(this.schemaPiiMap(extraSchema)).length > 0;
143
+ }
144
+
145
+ pseudonymize(value, hint = "") {
146
+ if (value === null || value === undefined || value === "") return value;
147
+ const text = String(value);
148
+ const hash = sha256Hex(`${this.salt}:${hint}:${text}`).slice(0, 12);
149
+ const lowerHint = String(hint).toLowerCase();
150
+ if (lowerHint.includes("email") || EMAIL_VALUE_RE.test(text)) {
151
+ return `redacted-${hash}@redacted.invalid`;
152
+ }
153
+ if (lowerHint.includes("phone") || lowerHint.includes("tel") || lowerHint.includes("mobile")) {
154
+ return `+1-555-${hash.slice(0, 4)}`;
155
+ }
156
+ return `[redacted:${hash}]`;
157
+ }
158
+
159
+ noteRedactedColumn(table, column) {
160
+ const key = table || "*";
161
+ if (!this.redactedColumns[key]) this.redactedColumns[key] = [];
162
+ if (!this.redactedColumns[key].includes(column)) this.redactedColumns[key].push(column);
163
+ this.redactedFields.add(column);
164
+ }
165
+
166
+ redactValueForField(tableOrModel, fieldName, value) {
167
+ if (value === null || value === undefined) return value;
168
+ const table = this.resolveTableName(tableOrModel);
169
+ if (this.isPiiColumn(table, fieldName)) {
170
+ this.noteRedactedColumn(table, fieldName);
171
+ if (typeof value === "string" || typeof value === "number") {
172
+ return this.pseudonymize(value, fieldName);
173
+ }
174
+ if (Array.isArray(value)) {
175
+ return value.map((item) => this.pseudonymize(item, fieldName));
176
+ }
177
+ if (typeof value === "object") {
178
+ return this.pseudonymize(JSON.stringify(value), fieldName);
179
+ }
180
+ return this.pseudonymize(value, fieldName);
181
+ }
182
+ if (typeof value === "string" && EMAIL_VALUE_RE.test(value.trim())) {
183
+ this.redactedFields.add(fieldName);
184
+ return this.pseudonymize(value.trim(), "email");
185
+ }
186
+ if (Array.isArray(value)) {
187
+ return value.map((item) => (item && typeof item === "object" ? this.redactObject(table, item) : item));
188
+ }
189
+ if (value && typeof value === "object") {
190
+ return this.redactObject(table, value);
191
+ }
192
+ return value;
193
+ }
194
+
195
+ redactObject(tableOrModel, obj) {
196
+ if (!obj || typeof obj !== "object" || Array.isArray(obj)) return obj;
197
+ const out = {};
198
+ for (const [key, value] of Object.entries(obj)) {
199
+ out[key] = this.redactValueForField(tableOrModel, key, value);
200
+ }
201
+ return out;
202
+ }
203
+
204
+ redactRecordAttributes(recordType, attributes) {
205
+ if (!attributes || typeof attributes !== "object") return attributes;
206
+ return this.redactObject(recordType, attributes);
207
+ }
208
+
209
+ redactEnv(env) {
210
+ const out = {};
211
+ for (const [key, value] of Object.entries(env || {})) {
212
+ if (SENSITIVE_ENV_RE.test(key)) {
213
+ this.redactedFields.add(key.toLowerCase());
214
+ out[key] = this.pseudonymize(value, key);
215
+ } else {
216
+ out[key] = value;
217
+ }
218
+ }
219
+ return out;
220
+ }
221
+
222
+ redactCookies(cookies) {
223
+ const out = {};
224
+ const entries = cookies instanceof Map ? [...cookies.entries()] : Object.entries(cookies || {});
225
+ for (const [name, value] of entries) {
226
+ this.redactedFields.add("cookie");
227
+ out[name] = this.pseudonymize(value, `cookie:${name}`);
228
+ }
229
+ return out;
230
+ }
231
+
232
+ redactUrl(urlString) {
233
+ if (!urlString || !urlString.includes("?")) return urlString;
234
+ const q = urlString.indexOf("?");
235
+ const base = urlString.slice(0, q);
236
+ const params = new URLSearchParams(urlString.slice(q + 1));
237
+ let changed = false;
238
+ for (const [key, value] of [...params.entries()]) {
239
+ if (SENSITIVE_QUERY_PARAM_RE.test(key) || this.isPiiColumn("*", key)) {
240
+ this.redactedFields.add(key.toLowerCase());
241
+ params.set(key, this.pseudonymize(value, key));
242
+ changed = true;
243
+ }
244
+ }
245
+ return changed ? `${base}?${params.toString()}` : urlString;
246
+ }
247
+
248
+ redactFormBody(body) {
249
+ if (!body) return body;
250
+ const params = new URLSearchParams(body);
251
+ let changed = false;
252
+ for (const [key, value] of [...params.entries()]) {
253
+ // Rails forms nest attributes like "user[email]" or "issue[title]".
254
+ const bracketMatch = /^([^[]+)\[([^\]]+)\]$/.exec(key);
255
+ const table = bracketMatch ? bracketMatch[1] : "*";
256
+ const field = bracketMatch ? bracketMatch[2] : key;
257
+ if (this.isPiiColumn(table, field) || field === "authenticity_token") {
258
+ this.noteRedactedColumn(this.resolveTableName(table), field);
259
+ params.set(key, this.pseudonymize(value, field));
260
+ changed = true;
261
+ }
262
+ }
263
+ return changed ? params.toString() : body;
264
+ }
265
+
266
+ redactJsonBody(body, contextHint = "") {
267
+ if (!body || !body.trim()) return body;
268
+ let parsed;
269
+ try {
270
+ parsed = JSON.parse(body);
271
+ } catch {
272
+ return body;
273
+ }
274
+ const redacted = this.redactSyncPayload(parsed, contextHint);
275
+ return JSON.stringify(redacted);
276
+ }
277
+
278
+ redactSyncPayload(payload, contextHint = "") {
279
+ if (!payload || typeof payload !== "object") return payload;
280
+ if (Array.isArray(payload)) {
281
+ return payload.map((item) => this.redactSyncPayload(item, contextHint));
282
+ }
283
+ const copy = { ...payload };
284
+ if (typeof copy.identity === "string" && copy.identity) {
285
+ this.redactedFields.add("identity");
286
+ copy.identity = this.pseudonymize(copy.identity, "identity");
287
+ }
288
+ if (Array.isArray(copy.records)) {
289
+ copy.records = copy.records.map((record) => {
290
+ if (!record || typeof record !== "object") return record;
291
+ const type = record.type || record.record_type || contextHint;
292
+ return {
293
+ ...record,
294
+ attributes: record.attributes ? this.redactRecordAttributes(type, record.attributes) : record.attributes,
295
+ };
296
+ });
297
+ }
298
+ if (Array.isArray(copy.mutations)) {
299
+ copy.mutations = copy.mutations.map((mutation) => {
300
+ if (!mutation || typeof mutation !== "object") return mutation;
301
+ const type = mutation.record_type || mutation.type || contextHint;
302
+ return {
303
+ ...mutation,
304
+ changes: mutation.changes ? this.redactRecordAttributes(type, mutation.changes) : mutation.changes,
305
+ };
306
+ });
307
+ }
308
+ if (Array.isArray(copy.results)) {
309
+ copy.results = copy.results.map((result) => {
310
+ if (!result || typeof result !== "object") return result;
311
+ const type = result.record_type || result.type || contextHint;
312
+ return {
313
+ ...result,
314
+ server_attributes: result.server_attributes
315
+ ? this.redactRecordAttributes(type, result.server_attributes)
316
+ : result.server_attributes,
317
+ };
318
+ });
319
+ }
320
+ if (copy.attributes && typeof copy.attributes === "object" && (copy.type || copy.record_type)) {
321
+ copy.attributes = this.redactRecordAttributes(copy.type || copy.record_type, copy.attributes);
322
+ }
323
+ if (!copy.records && !copy.mutations && !copy.results && !copy.attributes) {
324
+ return this.redactObject(contextHint || "*", copy);
325
+ }
326
+ return copy;
327
+ }
328
+
329
+ redactSseChunk(chunk) {
330
+ if (!chunk) return chunk;
331
+ return chunk
332
+ .split("\n")
333
+ .map((line) => {
334
+ if (!line.startsWith("data:")) return line;
335
+ const raw = line.slice(5).trim();
336
+ if (!raw) return line;
337
+ return "data: " + this.redactJsonBody(raw);
338
+ })
339
+ .join("\n");
340
+ }
341
+
342
+ redactHttpRequest(rawHttp) {
343
+ const sep = rawHttp.indexOf("\r\n\r\n");
344
+ const headEnd = sep >= 0 ? sep : rawHttp.indexOf("\n\n");
345
+ const lineBreak = sep >= 0 ? "\r\n" : "\n";
346
+ if (headEnd < 0) return rawHttp;
347
+
348
+ const head = rawHttp.slice(0, headEnd);
349
+ const body = rawHttp.slice(headEnd + lineBreak.length * 2);
350
+ const lines = head.split(lineBreak);
351
+ if (lines.length === 0) return rawHttp;
352
+
353
+ // Request line: METHOD PATH HTTP/1.1
354
+ const parts = lines[0].split(" ");
355
+ if (parts.length >= 2) {
356
+ parts[1] = this.redactUrl(parts[1]);
357
+ lines[0] = parts.join(" ");
358
+ }
359
+
360
+ let contentType = "";
361
+ const redactedHeaders = lines.slice(1).map((line) => {
362
+ const colon = line.indexOf(":");
363
+ if (colon < 0) return line;
364
+ const name = line.slice(0, colon).trim();
365
+ const value = line.slice(colon + 1).trim();
366
+ if (name.toLowerCase() === "content-type") contentType = value.toLowerCase();
367
+ if (SENSITIVE_HEADER_RE.test(name)) {
368
+ this.redactedFields.add(name.toLowerCase());
369
+ return `${name}: ${this.pseudonymize(value, name.toLowerCase())}`;
370
+ }
371
+ return line;
372
+ });
373
+
374
+ let redactedBody = body;
375
+ if (body) {
376
+ if (contentType.includes("application/json")) {
377
+ redactedBody = this.redactJsonBody(body);
378
+ } else if (contentType.includes("application/x-www-form-urlencoded") || body.includes("=")) {
379
+ redactedBody = this.redactFormBody(body);
380
+ }
381
+ }
382
+
383
+ // Keep Content-Length accurate so Tep::Parser can parse the redacted request on replay.
384
+ const bodyByteLen = new TextEncoder().encode(redactedBody).length;
385
+ const finalHeaders = redactedHeaders.map((line) =>
386
+ /^content-length:/i.test(line) ? `Content-Length: ${bodyByteLen}` : line,
387
+ );
388
+
389
+ return `${lines[0]}${lineBreak}${finalHeaders.join(lineBreak)}${lineBreak}${lineBreak}${redactedBody}`;
390
+ }
391
+
392
+ redactExchange(exchange) {
393
+ if (!exchange || typeof exchange !== "object") return exchange;
394
+ const method = exchange.method || "GET";
395
+ const url = this.redactUrl(exchange.url || "");
396
+ let requestBody = exchange.requestBody || "";
397
+ let responseBody = exchange.responseBody || "";
398
+
399
+ if (requestBody) requestBody = this.redactJsonBody(requestBody);
400
+ if (responseBody) {
401
+ if (url.includes("/events") || responseBody.startsWith("id:") || responseBody.startsWith("data:")) {
402
+ responseBody = this.redactSseChunk(responseBody);
403
+ } else {
404
+ responseBody = this.redactJsonBody(responseBody);
405
+ }
406
+ }
407
+
408
+ const out = {
409
+ method,
410
+ url,
411
+ requestBody,
412
+ status: exchange.status,
413
+ responseBody,
414
+ };
415
+ if (exchange.requestHeaders && typeof exchange.requestHeaders === "object") {
416
+ const redactedHeaders = {};
417
+ for (const [key, value] of Object.entries(exchange.requestHeaders)) {
418
+ if (SENSITIVE_HEADER_RE.test(key) || /scope/i.test(key)) {
419
+ this.redactedFields.add(key.toLowerCase());
420
+ redactedHeaders[key] = this.pseudonymize(value, `header:${key.toLowerCase()}`);
421
+ } else {
422
+ redactedHeaders[key] = value;
423
+ }
424
+ }
425
+ out.requestHeaders = redactedHeaders;
426
+ }
427
+ return out;
428
+ }
429
+
430
+ redactWasiInput(exportName, inputBytes) {
431
+ const text = typeof inputBytes === "string" ? inputBytes : decoder.decode(inputBytes || new Uint8Array());
432
+ if (!text) return "";
433
+ switch (exportName) {
434
+ case "wasm_request":
435
+ return this.redactHttpRequest(text);
436
+ case "wasm_sync": {
437
+ if (text.trimStart().startsWith("{")) {
438
+ try {
439
+ const parsed = JSON.parse(text);
440
+ const redacted = { ...parsed };
441
+ if (typeof redacted.endpoint === "string") redacted.endpoint = this.redactUrl(redacted.endpoint);
442
+ if (redacted.push && typeof redacted.push === "object") {
443
+ redacted.push = {
444
+ ...redacted.push,
445
+ body: typeof redacted.push.body === "string" ? this.redactJsonBody(redacted.push.body) : redacted.push.body,
446
+ };
447
+ }
448
+ if (redacted.bootstrap && typeof redacted.bootstrap === "object") {
449
+ redacted.bootstrap = {
450
+ ...redacted.bootstrap,
451
+ body: typeof redacted.bootstrap.body === "string" ? this.redactJsonBody(redacted.bootstrap.body) : redacted.bootstrap.body,
452
+ };
453
+ }
454
+ return JSON.stringify(redacted);
455
+ } catch {
456
+ return this.redactJsonBody(text);
457
+ }
458
+ }
459
+ return this.redactUrl(text);
460
+ }
461
+ case "wasm_stream":
462
+ return this.redactSseChunk(text);
463
+ case "wasm_history": {
464
+ try {
465
+ const parsed = JSON.parse(text);
466
+ return JSON.stringify({
467
+ key: parsed.key ? this.redactUrl("?" + parsed.key).slice(1) : parsed.key,
468
+ response: parsed.response ? this.redactJsonBody(parsed.response) : parsed.response,
469
+ });
470
+ } catch {
471
+ return text;
472
+ }
473
+ }
474
+ case "wasm_notices":
475
+ case "wasm_import_outbox":
476
+ case "wasm_branch_replay":
477
+ return this.redactJsonBody(text);
478
+ default:
479
+ return text;
480
+ }
481
+ }
482
+
483
+ redactNotification(event) {
484
+ if (!event || typeof event !== "object") return event;
485
+ return {
486
+ ...event,
487
+ payload: event.payload && typeof event.payload === "object"
488
+ ? this.redactObject("*", event.payload)
489
+ : event.payload,
490
+ };
491
+ }
492
+
493
+ manifest() {
494
+ const schemaSummary = {};
495
+ for (const [table, cols] of Object.entries(this.schema)) {
496
+ schemaSummary[table] = cols.map((c) => c.name);
497
+ }
498
+ return {
499
+ enabled: true,
500
+ strategy: "deterministic_pseudonym",
501
+ schema: schemaSummary,
502
+ redactedColumns: Object.fromEntries(
503
+ Object.entries(this.redactedColumns).map(([k, v]) => [k, [...v].sort()]),
504
+ ),
505
+ redactedFields: [...this.redactedFields].sort(),
506
+ };
507
+ }
508
+ }
509
+
510
+ function randomSalt() {
511
+ const bytes = new Uint8Array(16);
512
+ if (globalThis.crypto?.getRandomValues) {
513
+ globalThis.crypto.getRandomValues(bytes);
514
+ } else {
515
+ for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256);
516
+ }
517
+ return [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
518
+ }
@@ -0,0 +1,48 @@
1
+ // Use the network fetch captured before the Rails request interceptor was installed.
2
+ export function watchRelease(fetchManifest, runningVersion, busy) {
3
+ let checking = false;
4
+ let pending = false;
5
+ let edited = false;
6
+ let notice;
7
+ document.addEventListener("input", () => { edited = true; }, true);
8
+
9
+ function activate() {
10
+ if (!pending || document.hidden || !navigator.onLine || busy()) return;
11
+ if (!edited && window.dispatchEvent(new Event("instant-record:before-update", { cancelable: true }))) {
12
+ location.reload();
13
+ return;
14
+ }
15
+ if (notice?.isConnected) return;
16
+ notice = document.createElement("aside");
17
+ notice.setAttribute("role", "status");
18
+ notice.textContent = "An app update is ready. Finish your edits before reloading. ";
19
+ const button = document.createElement("button");
20
+ button.type = "button";
21
+ button.textContent = "Reload app";
22
+ button.onclick = () => { if (!busy()) location.reload(); };
23
+ notice.append(button);
24
+ document.body.prepend(notice);
25
+ }
26
+
27
+ async function check() {
28
+ if (checking || document.hidden) return;
29
+ if (pending) return activate();
30
+ checking = true;
31
+ try {
32
+ const response = await fetchManifest("/instant-record-release.json", { cache: "no-store" });
33
+ if (!response.ok) return;
34
+ const { version } = await response.json();
35
+ pending = typeof version === "string" && /^[a-f0-9]{64}$/.test(version) && !version.startsWith(runningVersion);
36
+ activate();
37
+ } catch {
38
+ // Offline clients keep running the installed release.
39
+ } finally {
40
+ checking = false;
41
+ }
42
+ }
43
+ window.addEventListener("online", check);
44
+ window.addEventListener("focus", check);
45
+ document.addEventListener("visibilitychange", check);
46
+ setInterval(check, 60000);
47
+ return () => { pending = true; activate(); };
48
+ }