@facilis.dev/nitro 0.0.0-stage → 0.1.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 (267) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +18 -2
  3. package/dist/config.d.ts +30 -0
  4. package/dist/config.js +112 -0
  5. package/dist/constants.d.ts +24 -0
  6. package/dist/constants.js +24 -0
  7. package/dist/facade.d.ts +37 -0
  8. package/dist/facade.js +121 -0
  9. package/dist/index.d.ts +17 -0
  10. package/dist/index.js +14 -0
  11. package/dist/middleware/context.d.ts +5 -0
  12. package/dist/middleware/context.js +86 -0
  13. package/dist/middleware/cors.d.ts +10 -0
  14. package/dist/middleware/cors.js +34 -0
  15. package/dist/middleware/session.d.ts +9 -0
  16. package/dist/middleware/session.js +18 -0
  17. package/dist/module.d.ts +7 -0
  18. package/dist/module.js +234 -0
  19. package/dist/rolldown-parser.d.ts +3 -0
  20. package/dist/rolldown-parser.js +66 -0
  21. package/dist/route-metadata.d.ts +22 -0
  22. package/dist/route-metadata.js +161 -0
  23. package/dist/routes/dev-query.post.d.ts +10 -0
  24. package/dist/routes/dev-query.post.js +49 -0
  25. package/dist/routes/dev-schema.get.d.ts +9 -0
  26. package/dist/routes/dev-schema.get.js +34 -0
  27. package/dist/routes/dev-view.post.d.ts +11 -0
  28. package/dist/routes/dev-view.post.js +61 -0
  29. package/dist/routes/health.get.d.ts +8 -0
  30. package/dist/routes/health.get.js +18 -0
  31. package/dist/routes/manifest-revision.get.d.ts +8 -0
  32. package/dist/routes/manifest-revision.get.js +26 -0
  33. package/dist/routes/manifest.get.d.ts +8 -0
  34. package/dist/routes/manifest.get.js +68 -0
  35. package/dist/routes/openapi.get.d.ts +8 -0
  36. package/dist/routes/openapi.get.js +29 -0
  37. package/dist/routes/sso.d.ts +2 -0
  38. package/dist/routes/sso.js +216 -0
  39. package/dist/routes/token.post.d.ts +10 -0
  40. package/dist/routes/token.post.js +75 -0
  41. package/dist/runtime/boot-runtimes.d.ts +21 -0
  42. package/dist/runtime/boot-runtimes.js +38 -0
  43. package/dist/runtime/bootstrap.d.ts +47 -0
  44. package/dist/runtime/bootstrap.js +214 -0
  45. package/dist/runtime/config.d.ts +27 -0
  46. package/dist/runtime/config.js +44 -0
  47. package/dist/runtime/cors-policy.d.ts +16 -0
  48. package/dist/runtime/cors-policy.js +88 -0
  49. package/dist/runtime/db-bootstrap.d.ts +9 -0
  50. package/dist/runtime/db-bootstrap.js +87 -0
  51. package/dist/runtime/db-target.d.ts +21 -0
  52. package/dist/runtime/db-target.js +52 -0
  53. package/dist/runtime/dev-db-persistence.d.ts +39 -0
  54. package/dist/runtime/dev-db-persistence.js +124 -0
  55. package/dist/runtime/dev-query.d.ts +38 -0
  56. package/dist/runtime/dev-query.js +87 -0
  57. package/dist/runtime/env.d.ts +9 -0
  58. package/dist/runtime/env.js +14 -0
  59. package/dist/runtime/http-guard.d.ts +16 -0
  60. package/dist/runtime/http-guard.js +42 -0
  61. package/dist/runtime/http.d.ts +11 -0
  62. package/dist/runtime/http.js +18 -0
  63. package/dist/runtime/jobs/boot.d.ts +20 -0
  64. package/dist/runtime/jobs/boot.js +77 -0
  65. package/dist/runtime/jobs/contracts.d.ts +161 -0
  66. package/dist/runtime/jobs/contracts.js +1 -0
  67. package/dist/runtime/jobs/db-store.d.ts +21 -0
  68. package/dist/runtime/jobs/db-store.js +210 -0
  69. package/dist/runtime/jobs/definitions.d.ts +14 -0
  70. package/dist/runtime/jobs/definitions.js +31 -0
  71. package/dist/runtime/jobs/engine-support.d.ts +22 -0
  72. package/dist/runtime/jobs/engine-support.js +32 -0
  73. package/dist/runtime/jobs/engine.d.ts +6 -0
  74. package/dist/runtime/jobs/engine.js +261 -0
  75. package/dist/runtime/jobs/executor.d.ts +11 -0
  76. package/dist/runtime/jobs/executor.js +27 -0
  77. package/dist/runtime/jobs/memory-store.d.ts +7 -0
  78. package/dist/runtime/jobs/memory-store.js +183 -0
  79. package/dist/runtime/jobs/row-mapping.d.ts +28 -0
  80. package/dist/runtime/jobs/row-mapping.js +61 -0
  81. package/dist/runtime/jobs/runtime.d.ts +24 -0
  82. package/dist/runtime/jobs/runtime.js +86 -0
  83. package/dist/runtime/logging/audit-chain.d.ts +54 -0
  84. package/dist/runtime/logging/audit-chain.js +102 -0
  85. package/dist/runtime/logging/bootstrap-logging.d.ts +28 -0
  86. package/dist/runtime/logging/bootstrap-logging.js +26 -0
  87. package/dist/runtime/logging/entry.d.ts +14 -0
  88. package/dist/runtime/logging/entry.js +85 -0
  89. package/dist/runtime/logging/file-sink.d.ts +24 -0
  90. package/dist/runtime/logging/file-sink.js +128 -0
  91. package/dist/runtime/logging/log-settings.d.ts +52 -0
  92. package/dist/runtime/logging/log-settings.js +93 -0
  93. package/dist/runtime/logging/log-sink.d.ts +18 -0
  94. package/dist/runtime/logging/log-sink.js +22 -0
  95. package/dist/runtime/logging/redact.d.ts +31 -0
  96. package/dist/runtime/logging/redact.js +106 -0
  97. package/dist/runtime/logging/runtime.d.ts +25 -0
  98. package/dist/runtime/logging/runtime.js +114 -0
  99. package/dist/runtime/logging/sudo-bridge.d.ts +13 -0
  100. package/dist/runtime/logging/sudo-bridge.js +38 -0
  101. package/dist/runtime/manifest-data.d.ts +28 -0
  102. package/dist/runtime/manifest-data.js +70 -0
  103. package/dist/runtime/manifest-response.d.ts +45 -0
  104. package/dist/runtime/manifest-response.js +50 -0
  105. package/dist/runtime/manifest-sections.d.ts +20 -0
  106. package/dist/runtime/manifest-sections.js +59 -0
  107. package/dist/runtime/manifest-service.d.ts +16 -0
  108. package/dist/runtime/manifest-service.js +66 -0
  109. package/dist/runtime/project-config.d.ts +8 -0
  110. package/dist/runtime/project-config.js +22 -0
  111. package/dist/runtime/project-files.d.ts +12 -0
  112. package/dist/runtime/project-files.js +99 -0
  113. package/dist/runtime/rate-limit.d.ts +6 -0
  114. package/dist/runtime/rate-limit.js +6 -0
  115. package/dist/runtime/revision-service.d.ts +15 -0
  116. package/dist/runtime/revision-service.js +26 -0
  117. package/dist/runtime/sql.d.ts +8 -0
  118. package/dist/runtime/sql.js +23 -0
  119. package/dist/runtime/sso.d.ts +40 -0
  120. package/dist/runtime/sso.js +98 -0
  121. package/dist/runtime/state.d.ts +7 -0
  122. package/dist/runtime/state.js +7 -0
  123. package/dist/runtime/storage-keys.d.ts +9 -0
  124. package/dist/runtime/storage-keys.js +82 -0
  125. package/dist/runtime/storage-target.d.ts +25 -0
  126. package/dist/runtime/storage-target.js +155 -0
  127. package/dist/runtime/system-role.d.ts +9 -0
  128. package/dist/runtime/system-role.js +21 -0
  129. package/dist/runtime/tasks/boot.d.ts +20 -0
  130. package/dist/runtime/tasks/boot.js +32 -0
  131. package/dist/runtime/tasks/contracts.d.ts +70 -0
  132. package/dist/runtime/tasks/contracts.js +1 -0
  133. package/dist/runtime/tasks/db-store.d.ts +18 -0
  134. package/dist/runtime/tasks/db-store.js +139 -0
  135. package/dist/runtime/tasks/row-mapping.d.ts +11 -0
  136. package/dist/runtime/tasks/row-mapping.js +69 -0
  137. package/dist/runtime/tasks/runtime.d.ts +7 -0
  138. package/dist/runtime/tasks/runtime.js +162 -0
  139. package/dist/runtime/tasks/tasks-test-harness.d.ts +16 -0
  140. package/dist/runtime/tasks/tasks-test-harness.js +70 -0
  141. package/dist/runtime/tenant.d.ts +10 -0
  142. package/dist/runtime/tenant.js +13 -0
  143. package/dist/runtime/workflows/boot.d.ts +25 -0
  144. package/dist/runtime/workflows/boot.js +75 -0
  145. package/dist/runtime/workflows/contracts.d.ts +96 -0
  146. package/dist/runtime/workflows/contracts.js +1 -0
  147. package/dist/runtime/workflows/db-store.d.ts +18 -0
  148. package/dist/runtime/workflows/db-store.js +128 -0
  149. package/dist/runtime/workflows/definitions.d.ts +14 -0
  150. package/dist/runtime/workflows/definitions.js +50 -0
  151. package/dist/runtime/workflows/dispatch.d.ts +4 -0
  152. package/dist/runtime/workflows/dispatch.js +119 -0
  153. package/dist/runtime/workflows/row-mapping.d.ts +5 -0
  154. package/dist/runtime/workflows/row-mapping.js +38 -0
  155. package/dist/runtime/workflows/runner.d.ts +15 -0
  156. package/dist/runtime/workflows/runner.js +89 -0
  157. package/dist/runtime/workflows/runtime.d.ts +14 -0
  158. package/dist/runtime/workflows/runtime.js +129 -0
  159. package/dist/runtime/workflows/steps.d.ts +14 -0
  160. package/dist/runtime/workflows/steps.js +49 -0
  161. package/dist/runtime/workflows/support.d.ts +20 -0
  162. package/dist/runtime/workflows/support.js +36 -0
  163. package/dist/runtime/workflows/transitions.d.ts +8 -0
  164. package/dist/runtime/workflows/transitions.js +184 -0
  165. package/dist/runtime/workflows/workflows-test-harness.d.ts +62 -0
  166. package/dist/runtime/workflows/workflows-test-harness.js +178 -0
  167. package/dist/session-cookie.d.ts +13 -0
  168. package/dist/session-cookie.js +48 -0
  169. package/dist/storage.d.ts +50 -0
  170. package/dist/storage.js +118 -0
  171. package/dist/types.d.ts +44 -0
  172. package/dist/types.js +1 -0
  173. package/dist/virtual-ids.d.ts +17 -0
  174. package/dist/virtual-ids.js +17 -0
  175. package/dist/vite.d.ts +22 -0
  176. package/dist/vite.js +135 -0
  177. package/package.json +61 -4
  178. package/src/config.ts +120 -0
  179. package/src/constants.ts +24 -0
  180. package/src/facade.ts +153 -0
  181. package/src/index.ts +44 -0
  182. package/src/middleware/context.ts +106 -0
  183. package/src/middleware/cors.ts +42 -0
  184. package/src/middleware/session.ts +23 -0
  185. package/src/module.ts +278 -0
  186. package/src/rolldown-parser.ts +79 -0
  187. package/src/route-metadata-test-harness.ts +62 -0
  188. package/src/route-metadata.ts +194 -0
  189. package/src/routes/dev-query.post.ts +53 -0
  190. package/src/routes/dev-schema.get.ts +43 -0
  191. package/src/routes/dev-view.post.ts +66 -0
  192. package/src/routes/health.get.ts +26 -0
  193. package/src/routes/manifest-revision.get.ts +38 -0
  194. package/src/routes/manifest.get.ts +111 -0
  195. package/src/routes/openapi.get.ts +34 -0
  196. package/src/routes/sso.ts +247 -0
  197. package/src/routes/token.post.ts +89 -0
  198. package/src/runtime/boot-runtimes.ts +69 -0
  199. package/src/runtime/bootstrap.ts +300 -0
  200. package/src/runtime/config.ts +60 -0
  201. package/src/runtime/cors-policy.ts +107 -0
  202. package/src/runtime/db-bootstrap.ts +99 -0
  203. package/src/runtime/db-target.ts +87 -0
  204. package/src/runtime/dev-db-persistence.ts +146 -0
  205. package/src/runtime/dev-query.ts +124 -0
  206. package/src/runtime/env.ts +18 -0
  207. package/src/runtime/http-guard.ts +50 -0
  208. package/src/runtime/http.ts +30 -0
  209. package/src/runtime/jobs/boot.ts +97 -0
  210. package/src/runtime/jobs/contracts.ts +165 -0
  211. package/src/runtime/jobs/db-store-test-harness.ts +98 -0
  212. package/src/runtime/jobs/db-store.ts +273 -0
  213. package/src/runtime/jobs/definitions.ts +42 -0
  214. package/src/runtime/jobs/engine-support.ts +44 -0
  215. package/src/runtime/jobs/engine.ts +296 -0
  216. package/src/runtime/jobs/executor.ts +37 -0
  217. package/src/runtime/jobs/memory-store.ts +222 -0
  218. package/src/runtime/jobs/row-mapping.ts +67 -0
  219. package/src/runtime/jobs/runtime.ts +110 -0
  220. package/src/runtime/logging/audit-chain.ts +135 -0
  221. package/src/runtime/logging/bootstrap-logging.ts +62 -0
  222. package/src/runtime/logging/entry.ts +99 -0
  223. package/src/runtime/logging/file-sink.ts +157 -0
  224. package/src/runtime/logging/log-settings.ts +166 -0
  225. package/src/runtime/logging/log-sink.ts +31 -0
  226. package/src/runtime/logging/redact.ts +108 -0
  227. package/src/runtime/logging/runtime.ts +163 -0
  228. package/src/runtime/logging/sudo-bridge.ts +41 -0
  229. package/src/runtime/manifest-data.ts +103 -0
  230. package/src/runtime/manifest-response.ts +95 -0
  231. package/src/runtime/manifest-sections.ts +79 -0
  232. package/src/runtime/manifest-service.ts +83 -0
  233. package/src/runtime/project-config.ts +25 -0
  234. package/src/runtime/project-files.ts +103 -0
  235. package/src/runtime/rate-limit.ts +12 -0
  236. package/src/runtime/revision-service.ts +38 -0
  237. package/src/runtime/sql.ts +24 -0
  238. package/src/runtime/sso.ts +153 -0
  239. package/src/runtime/state.ts +7 -0
  240. package/src/runtime/storage-keys.ts +95 -0
  241. package/src/runtime/storage-target.ts +238 -0
  242. package/src/runtime/system-role.ts +26 -0
  243. package/src/runtime/tasks/boot.ts +49 -0
  244. package/src/runtime/tasks/contracts.ts +77 -0
  245. package/src/runtime/tasks/db-store.ts +191 -0
  246. package/src/runtime/tasks/row-mapping.ts +75 -0
  247. package/src/runtime/tasks/runtime.ts +192 -0
  248. package/src/runtime/tasks/tasks-test-harness.ts +92 -0
  249. package/src/runtime/tenant.ts +15 -0
  250. package/src/runtime/workflows/boot.ts +97 -0
  251. package/src/runtime/workflows/contracts.ts +114 -0
  252. package/src/runtime/workflows/db-store.ts +156 -0
  253. package/src/runtime/workflows/definitions.ts +75 -0
  254. package/src/runtime/workflows/dispatch.ts +148 -0
  255. package/src/runtime/workflows/row-mapping.ts +54 -0
  256. package/src/runtime/workflows/runner.ts +105 -0
  257. package/src/runtime/workflows/runtime.ts +161 -0
  258. package/src/runtime/workflows/steps.ts +74 -0
  259. package/src/runtime/workflows/support.ts +60 -0
  260. package/src/runtime/workflows/transitions.ts +259 -0
  261. package/src/runtime/workflows/workflows-test-harness.ts +238 -0
  262. package/src/session-cookie.ts +69 -0
  263. package/src/storage.ts +173 -0
  264. package/src/types.ts +51 -0
  265. package/src/virtual-ids.ts +18 -0
  266. package/src/virtual-modules.d.ts +53 -0
  267. package/src/vite.ts +175 -0
@@ -0,0 +1,110 @@
1
+ import {
2
+ JobError,
3
+ type EnqueueJobOptions,
4
+ type JobDefinition,
5
+ type JobQueueStats,
6
+ type JobRecord,
7
+ type JobsApi,
8
+ } from "@facilis.dev/core";
9
+
10
+ import type { PolicyScopedDatabase } from "@facilis.dev/db";
11
+
12
+ import type { JobEngine, StoredJob } from "./contracts.ts";
13
+
14
+ /** The booted job runtime carried by `BootstrapState` (D-107). */
15
+ export interface JobsRuntime {
16
+ readonly api: JobsApi;
17
+ /** Internal seam for the workflow runner: dispatch step jobs, read and cancel them. */
18
+ readonly engine: JobEngine;
19
+ /** The project's definitions, so workflows can reject a dangling job step at boot. */
20
+ readonly definitions: ReadonlyMap<string, JobDefinition<unknown, unknown>>;
21
+ start(): Promise<void>;
22
+ stop(): Promise<void>;
23
+ }
24
+
25
+ /**
26
+ * The API returns `JobRecord`s: the store's `Date`s are JSON-unfriendly and the queue is
27
+ * persisted/serialized data, so every instant crosses the boundary as ISO-8601 (docs/JOBS.md §6).
28
+ */
29
+ export function toJobRecord(job: StoredJob): JobRecord {
30
+ return {
31
+ id: job.id,
32
+ name: job.name,
33
+ status: job.status,
34
+ input: job.input,
35
+ output: job.output,
36
+ error: job.error,
37
+ attempts: job.attempts,
38
+ maxAttempts: job.maxAttempts,
39
+ timeoutMs: job.timeoutMs,
40
+ runAt: job.runAt.toISOString(),
41
+ createdAt: job.createdAt.toISOString(),
42
+ startedAt: job.startedAt === null ? null : job.startedAt.toISOString(),
43
+ finishedAt: job.finishedAt === null ? null : job.finishedAt.toISOString(),
44
+ };
45
+ }
46
+
47
+ /**
48
+ * Adapts the engine to the server-only `ctx.jobs` surface (D-107, docs/JOBS.md §6).
49
+ *
50
+ * The relative `delayMs` form is resolved here, not in the engine: the engine only knows
51
+ * absolute instants, which keeps its scheduling deterministic and its tests clock-free.
52
+ */
53
+ export function createJobsApi(engine: JobEngine, maxConcurrent: number): JobsApi {
54
+ return {
55
+ async enqueue(name, data, options) {
56
+ const runAt = resolveRunAt(options);
57
+ const engineOptions = runAt === undefined ? undefined : { runAt };
58
+ return await engine.enqueue(name, data, engineOptions);
59
+ },
60
+ async get(id) {
61
+ const job = await engine.get(id);
62
+ return job === null ? null : toJobRecord(job);
63
+ },
64
+ async list(options) {
65
+ return (await engine.list(options)).map(toJobRecord);
66
+ },
67
+ async queue() {
68
+ return (await engine.queue()).map(toJobRecord);
69
+ },
70
+ async running() {
71
+ return (await engine.running()).map(toJobRecord);
72
+ },
73
+ cancel(id) {
74
+ return engine.cancel(id);
75
+ },
76
+ async stats() {
77
+ const counts = await engine.stats();
78
+ return { ...counts, maxConcurrent } satisfies JobQueueStats;
79
+ },
80
+ // Framework plumbing (D-107, docs/JOBS.md §8): the route wrapper binds the API to the
81
+ // request's policy transaction so queue calls join it instead of opening a nested one.
82
+ bindScope(scope: PolicyScopedDatabase): JobsApi {
83
+ const scopedEngine = engine.scoped?.(scope) ?? engine;
84
+ return createJobsApi(scopedEngine, maxConcurrent);
85
+ },
86
+ };
87
+ }
88
+
89
+ /** Validates the author-facing schedule options and resolves them to one instant. */
90
+ function resolveRunAt(options: EnqueueJobOptions | undefined): Date | undefined {
91
+ if (options === undefined) return undefined;
92
+ const { runAt, delayMs } = options;
93
+ if (runAt !== undefined && delayMs !== undefined) {
94
+ throw new JobError("job_invalid_schedule", '"runAt" and "delayMs" are mutually exclusive.');
95
+ }
96
+ if (runAt !== undefined) {
97
+ const instant = runAt instanceof Date ? runAt : new Date(runAt);
98
+ if (Number.isNaN(instant.getTime())) {
99
+ throw new JobError("job_invalid_schedule", '"runAt" is not a valid ISO-8601 instant.');
100
+ }
101
+ return instant;
102
+ }
103
+ if (delayMs !== undefined) {
104
+ if (!Number.isFinite(delayMs) || delayMs < 0) {
105
+ throw new JobError("job_invalid_schedule", '"delayMs" must be a finite number >= 0.');
106
+ }
107
+ return new Date(Date.now() + delayMs);
108
+ }
109
+ return undefined;
110
+ }
@@ -0,0 +1,135 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ import type { AuditLogEntry } from "@facilis.dev/core";
4
+
5
+ /**
6
+ * Tamper-evident audit chain (D-119, O-014).
7
+ *
8
+ * File-written audit entries carry a sequence number, the previous entry's hash and their own
9
+ * SHA-256 hash over a canonical JSON rendering. The chain is tamper-EVIDENT, not tamper-proof:
10
+ * it has no secret key, so a writer who can rewrite the file can rebuild the chain. WORM or
11
+ * external retention is the deploy's responsibility (stdout/file shipped to a store it cannot
12
+ * rewrite). The chain restarts at seq 1 in a fresh file so a rotated file is still verifiable
13
+ * on its own, from its first entry's `prevHash` onward.
14
+ */
15
+
16
+ export const AUDIT_CHAIN_HASH_ALGORITHM = "sha256";
17
+ const HASH_PATTERN = /^[a-f0-9]{64}$/;
18
+
19
+ /** Where the next chained entry starts: the last entry of the active file. */
20
+ export interface AuditChainHead {
21
+ readonly seq: number;
22
+ readonly hash: string;
23
+ }
24
+
25
+ export interface ChainedAuditEntry extends AuditLogEntry {
26
+ /** 1-based position in the stream; continues across rotations and restarts. */
27
+ readonly seq: number;
28
+ /** Hash of the previous entry; absent only on the first entry of a fresh chain. */
29
+ readonly prevHash?: string;
30
+ /** SHA-256 of the canonical entry without this field (it covers `seq` and `prevHash`). */
31
+ readonly hash: string;
32
+ }
33
+
34
+ /** Everything the hash covers: the entry plus its chain position, minus the hash itself. */
35
+ export type AuditChainPayload = Omit<ChainedAuditEntry, "hash">;
36
+
37
+ export interface AuditChainVerification {
38
+ readonly ok: boolean;
39
+ readonly entries: number;
40
+ /** 0-based index of the first broken entry; absent when `ok`. */
41
+ readonly brokenAt?: number;
42
+ /** Stable reason code for the first break, e.g. `hash-mismatch`. */
43
+ readonly reason?: string;
44
+ }
45
+
46
+ /**
47
+ * Stable JSON rendering: object keys sorted, no whitespace, `undefined` fields absent.
48
+ * Two entries with the same field values always hash the same, regardless of key order.
49
+ */
50
+ export function canonicalJson(value: unknown): string {
51
+ if (value === null) return "null";
52
+ if (typeof value === "bigint") return JSON.stringify(value.toString());
53
+ if (typeof value !== "object") return JSON.stringify(value) ?? "null";
54
+ if (Array.isArray(value)) {
55
+ return `[${value.map((item) => canonicalJson(item)).join(",")}]`;
56
+ }
57
+ const object = value as Record<string, unknown>;
58
+ const parts: string[] = [];
59
+ for (const key of Object.keys(object).sort()) {
60
+ const item = object[key];
61
+ if (item === undefined) continue;
62
+ parts.push(`${JSON.stringify(key)}:${canonicalJson(item)}`);
63
+ }
64
+ return `{${parts.join(",")}}`;
65
+ }
66
+
67
+ /** Canonical hash of an entry position; exported so a readback tool can recompute it. */
68
+ export function computeAuditHash(payload: AuditChainPayload): string {
69
+ return createHash(AUDIT_CHAIN_HASH_ALGORITHM)
70
+ .update(canonicalJson(payload), "utf8")
71
+ .digest("hex");
72
+ }
73
+
74
+ /** Appends one entry to the chain; `head` is null for the first entry of a fresh file. */
75
+ export function chainAuditEntry(
76
+ entry: AuditLogEntry,
77
+ head: AuditChainHead | null,
78
+ ): ChainedAuditEntry {
79
+ const seq = head === null ? 1 : head.seq + 1;
80
+ const payload: AuditChainPayload = {
81
+ ...entry,
82
+ seq,
83
+ ...(head === null ? {} : { prevHash: head.hash }),
84
+ };
85
+ return { ...payload, hash: computeAuditHash(payload) };
86
+ }
87
+
88
+ /** Structural check used when reading a file back; malformed hashes fail the check. */
89
+ export function isChainedAuditEntry(value: unknown): value is ChainedAuditEntry {
90
+ if (value === null || typeof value !== "object") return false;
91
+ const candidate = value as Record<string, unknown>;
92
+ return (
93
+ candidate["kind"] === "audit" &&
94
+ Number.isSafeInteger(candidate["seq"]) &&
95
+ typeof candidate["hash"] === "string" &&
96
+ HASH_PATTERN.test(candidate["hash"]) &&
97
+ (candidate["prevHash"] === undefined ||
98
+ (typeof candidate["prevHash"] === "string" && HASH_PATTERN.test(candidate["prevHash"])))
99
+ );
100
+ }
101
+
102
+ /**
103
+ * Verifies a readback: every entry's hash and every consecutive link.
104
+ *
105
+ * The first entry may start at any `seq` (a rotated file starts mid-stream); when it starts at
106
+ * seq 1 it must not carry a `prevHash`. Only entries given are verified, so verifying
107
+ * `access.1.jsonl` (rotated) checks the links inside that file, not the link to the active one.
108
+ */
109
+ export function verifyAuditChain(entries: readonly unknown[]): AuditChainVerification {
110
+ let previous: ChainedAuditEntry | null = null;
111
+ for (const [index, entry] of entries.entries()) {
112
+ if (!isChainedAuditEntry(entry)) {
113
+ return broken(index, "not-a-chained-audit-entry");
114
+ }
115
+ if (index === 0) {
116
+ if (entry.seq === 1 && entry.prevHash !== undefined) {
117
+ return broken(index, "unexpected-prev-hash");
118
+ }
119
+ if (entry.seq > 1 && entry.prevHash === undefined) {
120
+ return broken(index, "missing-prev-hash");
121
+ }
122
+ } else if (previous !== null) {
123
+ if (entry.seq !== previous.seq + 1) return broken(index, "unexpected-sequence");
124
+ if (entry.prevHash !== previous.hash) return broken(index, "prev-hash-mismatch");
125
+ }
126
+ const { hash, ...payload } = entry;
127
+ if (computeAuditHash(payload) !== hash) return broken(index, "hash-mismatch");
128
+ previous = entry;
129
+ }
130
+ return { ok: true, entries: entries.length };
131
+ }
132
+
133
+ function broken(brokenAt: number, reason: string): AuditChainVerification {
134
+ return { ok: false, entries: brokenAt, brokenAt, reason };
135
+ }
@@ -0,0 +1,62 @@
1
+ import {
2
+ DEFAULT_LOGGING_CONFIG,
3
+ type FacilisLoggingConfig,
4
+ type LogLevel,
5
+ type ManifestWarning,
6
+ } from "@facilis.dev/core";
7
+
8
+ import { resolveLogSettings } from "./log-settings.ts";
9
+ import { createLoggingRuntime, type LoggingRuntime } from "./runtime.ts";
10
+
11
+ /**
12
+ * Boot-time logging construction (D-119).
13
+ *
14
+ * Logging is built from the project config plus the environment BEFORE the database is opened:
15
+ * a database boot failure must still leave the process with a working access/error stream, and
16
+ * logging itself must never be the reason a project fails to boot. When `facilis.config.ts`
17
+ * did not load, the documented defaults are used.
18
+ */
19
+ export interface BootstrapLoggingInput {
20
+ /** The project's `logging` section, or null when the project config failed to load. */
21
+ readonly loggingConfig: FacilisLoggingConfig | null;
22
+ readonly env: NodeJS.ProcessEnv;
23
+ readonly projectRoot: string;
24
+ /** Test seam: override the NODE_ENV-derived production detection. */
25
+ readonly production?: boolean;
26
+ /** Test seam: collect stdout lines instead of writing to the process stream. */
27
+ readonly writeStdout?: (line: string) => void;
28
+ }
29
+
30
+ export interface BootstrapLogging {
31
+ readonly logging: LoggingRuntime;
32
+ readonly config: FacilisLoggingConfig;
33
+ readonly warnings: readonly ManifestWarning[];
34
+ }
35
+
36
+ export function createBootstrapLogging(input: BootstrapLoggingInput): BootstrapLogging {
37
+ const resolved = resolveLogSettings({
38
+ env: input.env,
39
+ projectRoot: input.projectRoot,
40
+ ...(input.production === undefined ? {} : { production: input.production }),
41
+ });
42
+ const config = effectiveLoggingConfig(input.loggingConfig, resolved.settings.level);
43
+ const runtime = createLoggingRuntime({
44
+ config,
45
+ settings: resolved.settings,
46
+ ...(input.writeStdout === undefined ? {} : { writeStdout: input.writeStdout }),
47
+ });
48
+ return {
49
+ logging: runtime,
50
+ config,
51
+ warnings: [...resolved.warnings, ...runtime.warnings],
52
+ };
53
+ }
54
+
55
+ /** `logging.level` is the one config value the environment may override. */
56
+ export function effectiveLoggingConfig(
57
+ loggingConfig: FacilisLoggingConfig | null,
58
+ levelOverride: LogLevel | null,
59
+ ): FacilisLoggingConfig {
60
+ const base = loggingConfig ?? DEFAULT_LOGGING_CONFIG;
61
+ return levelOverride === null ? base : { ...base, level: levelOverride };
62
+ }
@@ -0,0 +1,99 @@
1
+ import type {
2
+ AccessLogEntry,
3
+ AppLogEntry,
4
+ AuditLogEntry,
5
+ ErrorLogEntry,
6
+ LogEntry,
7
+ } from "@facilis.dev/core";
8
+
9
+ import { capString, redactRecord } from "./redact.ts";
10
+
11
+ /**
12
+ * Entry sanitization at the sink boundary (D-119).
13
+ *
14
+ * Core builds the entry shapes; this pass makes them safe to serialize: every free-text field
15
+ * is capped, and the only arbitrary payloads (`data`/`details`) are redacted. Strings are
16
+ * capped rather than truncated with a marker so a hostile value cannot grow a line.
17
+ */
18
+ export const MAX_LOG_MESSAGE = 1000;
19
+ export const MAX_LOG_STACK = 4000;
20
+ export const MAX_LOG_FIELD = 1000;
21
+ export const MAX_LOG_SHORT = 200;
22
+ export const MAX_LOG_ARRAY = 50;
23
+
24
+ export function sanitizeEntry(entry: LogEntry): LogEntry {
25
+ switch (entry.kind) {
26
+ case "access":
27
+ return sanitizeAccess(entry);
28
+ case "error":
29
+ return sanitizeError(entry);
30
+ case "audit":
31
+ return sanitizeAudit(entry);
32
+ case "app":
33
+ return sanitizeApp(entry);
34
+ }
35
+ }
36
+
37
+ function sanitizeAccess(entry: AccessLogEntry): AccessLogEntry {
38
+ return {
39
+ ...entry,
40
+ path: capString(entry.path, MAX_LOG_FIELD),
41
+ ...(entry.userAgent === undefined
42
+ ? {}
43
+ : { userAgent: capString(entry.userAgent, MAX_LOG_FIELD) }),
44
+ // The client IP comes from an attacker-controlled header when trustProxy is on: cap it
45
+ // or a multi-KB x-forwarded-for would inflate every access line and the file.
46
+ ...(entry.ip === undefined ? {} : { ip: capString(entry.ip, MAX_LOG_SHORT) }),
47
+ };
48
+ }
49
+
50
+ function sanitizeError(entry: ErrorLogEntry): ErrorLogEntry {
51
+ return {
52
+ ...entry,
53
+ code: capString(entry.code, MAX_LOG_SHORT),
54
+ name: capString(entry.name, MAX_LOG_SHORT),
55
+ message: capString(entry.message, MAX_LOG_MESSAGE),
56
+ ...(entry.stack === undefined ? {} : { stack: capString(entry.stack, MAX_LOG_STACK) }),
57
+ ...(entry.method === undefined ? {} : { method: capString(entry.method, MAX_LOG_SHORT) }),
58
+ ...(entry.path === undefined ? {} : { path: capString(entry.path, MAX_LOG_FIELD) }),
59
+ requestId: capString(entry.requestId, MAX_LOG_SHORT),
60
+ ...(entry.ip === undefined ? {} : { ip: capString(entry.ip, MAX_LOG_SHORT) }),
61
+ };
62
+ }
63
+
64
+ function sanitizeAudit(entry: AuditLogEntry): AuditLogEntry {
65
+ return {
66
+ ...entry,
67
+ event: capString(entry.event, MAX_LOG_SHORT),
68
+ actor: capString(entry.actor, MAX_LOG_SHORT),
69
+ ...(entry.operation === undefined
70
+ ? {}
71
+ : { operation: capString(entry.operation, MAX_LOG_FIELD) }),
72
+ ...(entry.errorCode === undefined
73
+ ? {}
74
+ : { errorCode: capString(entry.errorCode, MAX_LOG_SHORT) }),
75
+ ...(entry.reason === undefined ? {} : { reason: capString(entry.reason, MAX_LOG_MESSAGE) }),
76
+ ...(entry.method === undefined ? {} : { method: capString(entry.method, MAX_LOG_SHORT) }),
77
+ ...(entry.path === undefined ? {} : { path: capString(entry.path, MAX_LOG_FIELD) }),
78
+ ...(entry.tables === undefined ? {} : { tables: capList(entry.tables) }),
79
+ ...(entry.roles === undefined ? {} : { roles: capList(entry.roles) }),
80
+ ...(entry.details === undefined ? {} : { details: redactRecord(entry.details) }),
81
+ ...(entry.ip === undefined ? {} : { ip: capString(entry.ip, MAX_LOG_SHORT) }),
82
+ };
83
+ }
84
+
85
+ function sanitizeApp(entry: AppLogEntry): AppLogEntry {
86
+ return {
87
+ ...entry,
88
+ message: capString(entry.message, MAX_LOG_MESSAGE),
89
+ ...(entry.data === undefined ? {} : { data: redactRecord(entry.data) }),
90
+ ...(entry.method === undefined ? {} : { method: capString(entry.method, MAX_LOG_SHORT) }),
91
+ ...(entry.path === undefined ? {} : { path: capString(entry.path, MAX_LOG_FIELD) }),
92
+ ...(entry.ip === undefined ? {} : { ip: capString(entry.ip, MAX_LOG_SHORT) }),
93
+ };
94
+ }
95
+
96
+ function capList(values: readonly string[] | undefined): readonly string[] | undefined {
97
+ if (values === undefined) return undefined;
98
+ return values.slice(0, MAX_LOG_ARRAY).map((value) => capString(value, MAX_LOG_FIELD));
99
+ }
@@ -0,0 +1,157 @@
1
+ import { appendFileSync, mkdirSync, readFileSync, renameSync, rmSync, statSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ import type { AuditLogEntry, LogEntry } from "@facilis.dev/core";
5
+
6
+ import { chainAuditEntry, isChainedAuditEntry, type AuditChainHead } from "./audit-chain.ts";
7
+ import type { LogSettingsWarning } from "./log-settings.ts";
8
+ import type { LogSink, LogStream } from "./log-sink.ts";
9
+
10
+ /**
11
+ * JSONL file sink with size-based rotation (D-119).
12
+ *
13
+ * Writes are synchronous and serialized by construction (one file writer per process), which
14
+ * is what makes the audit chain's `prevHash` exact. A file is rotated before an append that
15
+ * would pass the cap: the active file becomes `.1`, older files shift by one and the oldest is
16
+ * deleted, keeping exactly `keep` rotated files. Retention beyond that is the deploy's job.
17
+ *
18
+ * `append` throws on any filesystem failure. The runtime turns that into a dropped
19
+ * access/error/app entry (best effort) or a failed request for audit (fail closed, D-099).
20
+ */
21
+ export interface FileLogSinkOptions {
22
+ readonly dir: string;
23
+ readonly maxBytes: number;
24
+ readonly keep: number;
25
+ }
26
+
27
+ export interface FileLogSinkSetup {
28
+ readonly sink: LogSink;
29
+ readonly warnings: readonly LogSettingsWarning[];
30
+ }
31
+
32
+ const LOG_FILE_EXTENSION = ".jsonl";
33
+
34
+ export function logFilePath(dir: string, stream: LogStream, index?: number): string {
35
+ const suffix = index === undefined ? LOG_FILE_EXTENSION : `.${index}${LOG_FILE_EXTENSION}`;
36
+ return join(dir, `${stream}${suffix}`);
37
+ }
38
+
39
+ export function createFileLogSink(options: FileLogSinkOptions): FileLogSinkSetup {
40
+ const warnings: LogSettingsWarning[] = [];
41
+ let directoryReady = tryCreateDirectory(options.dir, warnings);
42
+ let auditHead: AuditChainHead | null = directoryReady
43
+ ? readAuditHead(options.dir, warnings)
44
+ : null;
45
+
46
+ const append = (stream: LogStream, entry: LogEntry): void => {
47
+ if (!directoryReady) directoryReady = createDirectory(options.dir);
48
+ const path = logFilePath(options.dir, stream);
49
+ const chained = stream === "audit" ? chainAuditEntry(entry as AuditLogEntry, auditHead) : null;
50
+ const line = `${JSON.stringify(chained ?? entry)}\n`;
51
+ rotateIfNeeded(path, Buffer.byteLength(line, "utf8"), options);
52
+ appendFileSync(path, line, "utf8");
53
+ // The chain only advances after the bytes are on disk, so a failed append cannot leave a
54
+ // gap the next entry would silently hash over.
55
+ if (chained !== null) auditHead = { seq: chained.seq, hash: chained.hash };
56
+ };
57
+
58
+ return { sink: { append }, warnings };
59
+ }
60
+
61
+ function readAuditHead(dir: string, warnings: LogSettingsWarning[]): AuditChainHead | null {
62
+ const path = logFilePath(dir, "audit");
63
+ let content: string;
64
+ try {
65
+ content = readFileSync(path, "utf8");
66
+ } catch (error) {
67
+ if (isMissingFile(error)) return null;
68
+ warnings.push({
69
+ code: "logging_audit_chain_unreadable",
70
+ message: `Could not read the audit chain ${path}: ${describe(error)}. Starting a new chain.`,
71
+ });
72
+ return null;
73
+ }
74
+ const lines = content.split("\n").filter((line) => line.trim().length > 0);
75
+ const last = lines[lines.length - 1];
76
+ if (last === undefined) return null;
77
+ try {
78
+ const parsed: unknown = JSON.parse(last);
79
+ if (!isChainedAuditEntry(parsed)) throw new Error("the last line is not a chained audit entry");
80
+ return { seq: parsed.seq, hash: parsed.hash };
81
+ } catch (error) {
82
+ // A corrupt/truncated tail must not make the audit stream unwritable (the app would keep
83
+ // booting) nor pretend the chain is intact: warn and restart, the tamper is visible.
84
+ warnings.push({
85
+ code: "logging_audit_chain_reset",
86
+ message: `The audit chain in ${path} could not be continued (${describe(error)}); starting a new chain.`,
87
+ });
88
+ return null;
89
+ }
90
+ }
91
+
92
+ function rotateIfNeeded(path: string, incomingBytes: number, options: FileLogSinkOptions): void {
93
+ const size = fileSize(path);
94
+ // `size > 0` keeps a single over-cap entry writable instead of rotating an empty file
95
+ // forever: a line larger than the cap is written once and rotated by the next append.
96
+ if (size === 0 || size + incomingBytes <= options.maxBytes) return;
97
+ rotate(path, options.keep);
98
+ }
99
+
100
+ function rotate(path: string, keep: number): void {
101
+ if (keep <= 0) {
102
+ rmSync(path, { force: true });
103
+ return;
104
+ }
105
+ rmSync(rotatedPath(path, keep), { force: true });
106
+ for (let index = keep - 1; index >= 1; index -= 1) {
107
+ renameIfExists(rotatedPath(path, index), rotatedPath(path, index + 1));
108
+ }
109
+ renameSync(path, rotatedPath(path, 1));
110
+ }
111
+
112
+ function rotatedPath(path: string, index: number): string {
113
+ return `${path.slice(0, -LOG_FILE_EXTENSION.length)}.${index}${LOG_FILE_EXTENSION}`;
114
+ }
115
+
116
+ function fileSize(path: string): number {
117
+ try {
118
+ return statSync(path).size;
119
+ } catch (error) {
120
+ if (isMissingFile(error)) return 0;
121
+ throw error;
122
+ }
123
+ }
124
+
125
+ function renameIfExists(from: string, to: string): void {
126
+ try {
127
+ renameSync(from, to);
128
+ } catch (error) {
129
+ if (isMissingFile(error)) return;
130
+ throw error;
131
+ }
132
+ }
133
+
134
+ function createDirectory(dir: string): boolean {
135
+ mkdirSync(dir, { recursive: true });
136
+ return true;
137
+ }
138
+
139
+ function tryCreateDirectory(dir: string, warnings: LogSettingsWarning[]): boolean {
140
+ try {
141
+ return createDirectory(dir);
142
+ } catch (error) {
143
+ warnings.push({
144
+ code: "logging_dir_unwritable",
145
+ message: `Could not create the log directory ${dir}: ${describe(error)}. Access/error/app entries will be dropped; audit writes will fail closed.`,
146
+ });
147
+ return false;
148
+ }
149
+ }
150
+
151
+ function isMissingFile(error: unknown): boolean {
152
+ return error instanceof Error && (error as NodeJS.ErrnoException).code === "ENOENT";
153
+ }
154
+
155
+ function describe(error: unknown): string {
156
+ return error instanceof Error ? error.message : String(error);
157
+ }