tina4-nodejs 3.13.150 → 3.13.152

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 (71) hide show
  1. package/CLAUDE.md +2 -2
  2. package/package.json +5 -9
  3. package/packages/cli/dist/bin.js +1326 -586
  4. package/packages/cli/src/bin.ts +179 -7
  5. package/packages/cli/src/commands/generate.ts +36 -17
  6. package/packages/cli/src/commands/migrateCreate.ts +15 -3
  7. package/packages/cli/src/commands/queue.ts +8 -0
  8. package/packages/cli/src/util.ts +25 -15
  9. package/packages/core/dist/index.js +1172 -574
  10. package/packages/core/src/aiClient.ts +2 -1
  11. package/packages/core/src/api.ts +2 -1
  12. package/packages/core/src/auth.ts +1 -1
  13. package/packages/core/src/authGate.ts +3 -4
  14. package/packages/core/src/cache.ts +6 -1
  15. package/packages/core/src/devAdmin.ts +180 -123
  16. package/packages/core/src/dispatchPipeline.ts +4 -0
  17. package/packages/core/src/docs.ts +5 -3
  18. package/packages/core/src/errorOverlay.ts +18 -9
  19. package/packages/core/src/index.ts +2 -1
  20. package/packages/core/src/mcp.ts +53 -16
  21. package/packages/core/src/messenger.ts +22 -30
  22. package/packages/core/src/middleware.ts +8 -1
  23. package/packages/core/src/optionalPackage.ts +2 -2
  24. package/packages/core/src/plan.ts +3 -3
  25. package/packages/core/src/push.ts +1 -1
  26. package/packages/core/src/request.ts +185 -25
  27. package/packages/core/src/router.ts +3 -2
  28. package/packages/core/src/server.ts +36 -12
  29. package/packages/core/src/session.ts +44 -0
  30. package/packages/core/src/slashTrim.ts +39 -0
  31. package/packages/core/src/wsdl.ts +66 -48
  32. package/packages/core/templates/crud/form.twig +5 -5
  33. package/packages/core/templates/crud/table.twig +2 -2
  34. package/packages/core/templates/errors/302.twig +4 -3
  35. package/packages/frond/dist/index.js +206 -64
  36. package/packages/frond/src/engine.ts +278 -69
  37. package/packages/frond/src/index.ts +1 -1
  38. package/packages/orm/dist/index.js +1156 -560
  39. package/packages/orm/src/adapters/postgres.ts +79 -19
  40. package/packages/orm/src/crudRender.ts +5 -5
  41. package/packages/orm/src/crudTable.ts +1 -1
  42. package/packages/orm/src/database.ts +15 -29
  43. package/packages/orm/src/databaseResult.ts +11 -1
  44. package/packages/orm/src/docstore.ts +24 -8
  45. package/packages/orm/src/realtime/index.ts +1 -0
  46. package/packages/orm/src/realtime/realtime.ts +2 -1
  47. package/packages/orm/src/realtime/s3Client.ts +276 -0
  48. package/packages/orm/src/realtime/storage.ts +19 -60
  49. package/packages/orm/src/sqlTranslator.ts +58 -42
  50. package/packages/swagger/dist/index.js +25 -4
  51. package/packages/swagger/src/generator.ts +7 -4
  52. package/packages/swagger/src/ui.ts +2 -1
  53. package/types/cli/src/bin.d.ts +16 -0
  54. package/types/cli/src/commands/generate.d.ts +11 -0
  55. package/types/cli/src/commands/migrateCreate.d.ts +2 -0
  56. package/types/cli/src/commands/queue.d.ts +2 -0
  57. package/types/cli/src/util.d.ts +2 -1
  58. package/types/core/src/authGate.d.ts +3 -3
  59. package/types/core/src/devAdmin.d.ts +40 -0
  60. package/types/core/src/index.d.ts +2 -1
  61. package/types/core/src/middleware.d.ts +1 -0
  62. package/types/core/src/optionalPackage.d.ts +2 -2
  63. package/types/core/src/request.d.ts +5 -1
  64. package/types/core/src/session.d.ts +25 -0
  65. package/types/core/src/slashTrim.d.ts +6 -0
  66. package/types/frond/src/engine.d.ts +11 -0
  67. package/types/frond/src/index.d.ts +1 -1
  68. package/types/orm/src/adapters/postgres.d.ts +6 -0
  69. package/types/orm/src/realtime/index.d.ts +1 -0
  70. package/types/orm/src/realtime/s3Client.d.ts +48 -0
  71. package/types/orm/src/realtime/storage.d.ts +9 -7
@@ -0,0 +1,276 @@
1
+ /*
2
+ Copyright (c) 2026 Code Infinity
3
+ SPDX-License-Identifier: MPL-2.0
4
+ This Source Code Form is subject to the terms of the Mozilla Public
5
+ License, v. 2.0. If a copy of the MPL was not distributed with this
6
+ file, You can obtain one at https://mozilla.org/MPL/2.0/.
7
+ */
8
+
9
+ import { createHash, createHmac } from "node:crypto";
10
+
11
+ /**
12
+ * Zero-dependency S3 client (AWS Signature Version 4) on the Node standard
13
+ * library — node:crypto for signing, global fetch for transport. Covers exactly
14
+ * what the realtime S3Storage backend needs (PUT, GET, DELETE, HEAD, a presigned
15
+ * GET URL, and create-bucket for provisioning) so the `s3` backend no longer
16
+ * needs @aws-sdk/client-s3 or @aws-sdk/s3-request-presigner.
17
+ *
18
+ * Path-style addressing (<endpoint>/<bucket>/<key>), which S3-compatible servers
19
+ * (MinIO, Garage) require and AWS accepts; with no endpoint it targets
20
+ * https://s3.<region>.amazonaws.com. SigV4 is HMAC-SHA256 canonical signing —
21
+ * the same primitive Tina4's JWT already uses (node:crypto); nothing here is
22
+ * reinvented crypto. Mirrors the Python master, proven against AWS's published
23
+ * SigV4 test vector.
24
+ */
25
+
26
+ const ALGORITHM = "AWS4-HMAC-SHA256";
27
+ const SERVICE = "s3";
28
+ const UNRESERVED = /[A-Za-z0-9\-_.~]/;
29
+
30
+ // Retry policy, as for the AI client (ADR-0053): HTTP 429, any 5xx (S3's
31
+ // SlowDown is a 503) and a dropped connection are sent again, a bounded number
32
+ // of times, honouring Retry-After. Every operation here is idempotent.
33
+ const MAX_RETRIES = 2;
34
+ const BACKOFF_BASE = 0.5; // seconds; retry n waits up to base * 2**n, jittered
35
+ const BACKOFF_CAP = 20.0;
36
+
37
+ /** An S3 request returned a non-2xx status; `status` holds the HTTP code. */
38
+ export class S3Error extends Error {
39
+ /** Seconds from a Retry-After header in its delta-seconds form, else null. */
40
+ retryAfter: number | null = null;
41
+ constructor(public readonly status: number, message: string) {
42
+ super(message);
43
+ this.name = "S3Error";
44
+ }
45
+ }
46
+
47
+ /** The client cannot sign a request: no access key or secret was given. */
48
+ export class S3ConfigError extends Error {
49
+ constructor(message: string) {
50
+ super(message);
51
+ this.name = "S3ConfigError";
52
+ }
53
+ }
54
+
55
+ /** Seconds from a Retry-After header in its delta-seconds form, else null. */
56
+ function retryAfterSeconds(raw: string | null): number | null {
57
+ if (raw == null) return null;
58
+ const n = Number(raw);
59
+ return Number.isFinite(n) ? Math.max(0, n) : null;
60
+ }
61
+
62
+ const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
63
+
64
+ /**
65
+ * SigV4 canonical encoding: keep the RFC 3986 unreserved set literal; keep "/"
66
+ * in a path and encode it in a query; every other byte becomes %XX (upper-case).
67
+ */
68
+ export function uriEncode(value: string, isPath: boolean): string {
69
+ let out = "";
70
+ for (const byte of Buffer.from(value, "utf8")) {
71
+ const ch = String.fromCharCode(byte);
72
+ if (UNRESERVED.test(ch) || (isPath && ch === "/")) out += ch;
73
+ else out += "%" + byte.toString(16).toUpperCase().padStart(2, "0");
74
+ }
75
+ return out;
76
+ }
77
+
78
+ function sha256Hex(data: Buffer | string): string {
79
+ return createHash("sha256").update(data).digest("hex");
80
+ }
81
+
82
+ function hmac(key: Buffer | string, msg: string): Buffer {
83
+ return createHmac("sha256", key).update(msg, "utf8").digest();
84
+ }
85
+
86
+ export class S3Client {
87
+ private readonly scheme: string;
88
+ private readonly host: string; // authority (host[:port]) — matches the Host header
89
+ private readonly prefix: string; // path an endpoint carries (https://host/s3 -> "/s3"), "" if none
90
+ private readonly region: string;
91
+ private readonly accessKey: string;
92
+ private readonly secretKey: string;
93
+ private readonly timeout: number;
94
+
95
+ constructor(opts: {
96
+ endpoint?: string;
97
+ accessKey?: string;
98
+ secretKey?: string;
99
+ region?: string;
100
+ timeout?: number;
101
+ } = {}) {
102
+ this.region = opts.region || "us-east-1";
103
+ this.accessKey = opts.accessKey || "";
104
+ this.secretKey = opts.secretKey || "";
105
+ this.timeout = opts.timeout ?? 30000;
106
+ let base = opts.endpoint || `https://s3.${this.region}.amazonaws.com`;
107
+ while (base.endsWith("/")) base = base.slice(0, -1); // strip trailing slashes without a regex
108
+ // Split scheme :// authority [ / path ]. The authority alone is the Host
109
+ // header and the signed `host:`; an endpoint behind a path (https://host/s3)
110
+ // keeps that path in front of every request path, and in what is signed.
111
+ const m = /^([a-z][a-z0-9+.-]*):\/\/([^/]+)(\/.*)?$/i.exec(base);
112
+ this.scheme = m ? m[1] : "https";
113
+ this.host = m ? m[2] : base;
114
+ let p = m && m[3] ? m[3] : "";
115
+ while (p.endsWith("/")) p = p.slice(0, -1);
116
+ this.prefix = p;
117
+ }
118
+
119
+ // -- public API (the subset S3Storage uses) --------------------------------
120
+
121
+ async putObject(bucket: string, key: string, data: Buffer | string, contentType = "application/octet-stream"): Promise<void> {
122
+ const body = Buffer.isBuffer(data) ? data : Buffer.from(data);
123
+ await this.request("PUT", this.canonicalUri(bucket, key), body, { "content-type": contentType });
124
+ }
125
+
126
+ async getObject(bucket: string, key: string): Promise<Buffer> {
127
+ return (await this.request("GET", this.canonicalUri(bucket, key), Buffer.alloc(0))).body;
128
+ }
129
+
130
+ async deleteObject(bucket: string, key: string): Promise<void> {
131
+ await this.request("DELETE", this.canonicalUri(bucket, key), Buffer.alloc(0));
132
+ }
133
+
134
+ async headObject(bucket: string, key: string): Promise<void> {
135
+ await this.request("HEAD", this.canonicalUri(bucket, key), Buffer.alloc(0));
136
+ }
137
+
138
+ /** Create the bucket (path-style `PUT /<bucket>`); an already-owned bucket (409) is success. */
139
+ async createBucket(bucket: string): Promise<void> {
140
+ try {
141
+ await this.request("PUT", `${this.prefix}/${uriEncode(bucket, true)}`, Buffer.alloc(0));
142
+ } catch (e) {
143
+ if (!(e instanceof S3Error) || e.status !== 409) throw e;
144
+ }
145
+ }
146
+
147
+ /** A URL that fetches the object directly, signed via SigV4 query params. */
148
+ presignedGetUrl(bucket: string, key: string, expires = 3600): string {
149
+ this.requireCredentials();
150
+ const { amzDate, dateStamp } = this.now();
151
+ const uri = this.canonicalUri(bucket, key);
152
+ const scope = `${dateStamp}/${this.region}/${SERVICE}/aws4_request`;
153
+ const query: Record<string, string> = {
154
+ "X-Amz-Algorithm": ALGORITHM,
155
+ "X-Amz-Credential": `${this.accessKey}/${scope}`,
156
+ "X-Amz-Date": amzDate,
157
+ "X-Amz-Expires": String(expires),
158
+ "X-Amz-SignedHeaders": "host",
159
+ };
160
+ const canonicalQs = this.canonicalQuery(query);
161
+ const canonicalRequest = ["GET", uri, canonicalQs, `host:${this.host}\n`, "host", "UNSIGNED-PAYLOAD"].join("\n");
162
+ const signature = this.sign(canonicalRequest, amzDate, dateStamp, scope);
163
+ return `${this.scheme}://${this.host}${uri}?${canonicalQs}&X-Amz-Signature=${signature}`;
164
+ }
165
+
166
+ // -- signing + transport ----------------------------------------------------
167
+
168
+ private requireCredentials(): void {
169
+ // Signing with an empty key only earns a 403 from the server, which says
170
+ // nothing about the cause. Name the settings instead, before sending.
171
+ if (!this.accessKey || !this.secretKey) {
172
+ throw new S3ConfigError(
173
+ "S3 credentials are not set: set TINA4_STORAGE_KEY and TINA4_STORAGE_SECRET",
174
+ );
175
+ }
176
+ }
177
+
178
+ private now(): { amzDate: string; dateStamp: string } {
179
+ const iso = new Date().toISOString().replace(/[:-]|\.\d{3}/g, "");
180
+ return { amzDate: iso, dateStamp: iso.slice(0, 8) };
181
+ }
182
+
183
+ private canonicalUri(bucket: string, key: string): string {
184
+ return `${this.prefix}/${uriEncode(bucket, true)}/${uriEncode(key, true)}`;
185
+ }
186
+
187
+ private canonicalQuery(query: Record<string, string>): string {
188
+ return Object.keys(query)
189
+ .sort()
190
+ .map((k) => `${uriEncode(k, false)}=${uriEncode(query[k], false)}`)
191
+ .join("&");
192
+ }
193
+
194
+ private signingKey(dateStamp: string): Buffer {
195
+ const kDate = hmac(`AWS4${this.secretKey}`, dateStamp);
196
+ const kRegion = hmac(kDate, this.region);
197
+ const kService = hmac(kRegion, SERVICE);
198
+ return hmac(kService, "aws4_request");
199
+ }
200
+
201
+ private sign(canonicalRequest: string, amzDate: string, dateStamp: string, scope: string): string {
202
+ const stringToSign = [ALGORITHM, amzDate, scope, sha256Hex(canonicalRequest)].join("\n");
203
+ return createHmac("sha256", this.signingKey(dateStamp)).update(stringToSign, "utf8").digest("hex");
204
+ }
205
+
206
+ private async request(
207
+ method: string,
208
+ uri: string,
209
+ body: Buffer,
210
+ extraHeaders: Record<string, string> = {},
211
+ ): Promise<{ status: number; body: Buffer }> {
212
+ this.requireCredentials();
213
+ for (let attempt = 0; ; attempt++) {
214
+ const last = attempt === MAX_RETRIES;
215
+ let delay: number | null = null;
216
+ try {
217
+ // Signed afresh each attempt: x-amz-date moves on.
218
+ return await this.send(method, uri, body, extraHeaders);
219
+ } catch (e) {
220
+ if (e instanceof S3Error) {
221
+ if (last || !(e.status === 429 || e.status >= 500)) throw e;
222
+ delay = e.retryAfter;
223
+ } else {
224
+ // Connection refused or dropped, timeout: nothing was answered.
225
+ if (last) throw e;
226
+ delay = null;
227
+ }
228
+ }
229
+ if (delay == null) delay = Math.random() * (BACKOFF_BASE * 2 ** attempt);
230
+ await sleep(Math.min(delay, BACKOFF_CAP) * 1000);
231
+ }
232
+ }
233
+
234
+ private async send(
235
+ method: string,
236
+ uri: string,
237
+ body: Buffer,
238
+ extraHeaders: Record<string, string> = {},
239
+ ): Promise<{ status: number; body: Buffer }> {
240
+ const { amzDate, dateStamp } = this.now();
241
+ const payloadHash = sha256Hex(body);
242
+
243
+ const signed: Record<string, string> = {
244
+ host: this.host,
245
+ "x-amz-content-sha256": payloadHash,
246
+ "x-amz-date": amzDate,
247
+ };
248
+ const signedKeys = Object.keys(signed).sort();
249
+ const canonicalHeaders = signedKeys.map((k) => `${k}:${signed[k]}\n`).join("");
250
+ const signedHeaders = signedKeys.join(";");
251
+ const canonicalRequest = [method, uri, "", canonicalHeaders, signedHeaders, payloadHash].join("\n");
252
+ const scope = `${dateStamp}/${this.region}/${SERVICE}/aws4_request`;
253
+ const signature = this.sign(canonicalRequest, amzDate, dateStamp, scope);
254
+ const authorization = `${ALGORITHM} Credential=${this.accessKey}/${scope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;
255
+
256
+ const headers: Record<string, string> = {
257
+ Authorization: authorization,
258
+ "x-amz-content-sha256": payloadHash,
259
+ "x-amz-date": amzDate,
260
+ ...extraHeaders,
261
+ };
262
+
263
+ const url = `${this.scheme}://${this.host}${uri}`;
264
+ const init: RequestInit = { method, headers, redirect: "manual" };
265
+ if (method === "PUT" || method === "POST") init.body = body;
266
+ if (AbortSignal.timeout) init.signal = AbortSignal.timeout(this.timeout);
267
+
268
+ const response = await fetch(url, init);
269
+ if (response.status < 200 || response.status >= 300) {
270
+ const err = new S3Error(response.status, `${method} ${uri}: HTTP ${response.status}`);
271
+ err.retryAfter = retryAfterSeconds(response.headers.get("retry-after"));
272
+ throw err;
273
+ }
274
+ return { status: response.status, body: Buffer.from(await response.arrayBuffer()) };
275
+ }
276
+ }
@@ -9,38 +9,15 @@ file, You can obtain one at https://mozilla.org/MPL/2.0/.
9
9
  import { randomBytes } from "node:crypto";
10
10
  import { mkdirSync, readFileSync, writeFileSync, unlinkSync, statSync } from "node:fs";
11
11
  import { resolve, sep } from "node:path";
12
- import { createRequire } from "node:module";
13
12
  import { Log } from "../../../core/src/index.js";
14
- import { optionalPackageMissing } from "../../../core/src/optionalPackage.js";
15
-
16
- // ESM has no global `require`; create one so the OPTIONAL aws-sdk can be loaded
17
- // synchronously in S3Storage's constructor.
18
- const require = createRequire(import.meta.url);
19
-
20
- /** S3 needs both SDK packages, so a missing one names the command for both. */
21
- const S3_PACKAGES = ["@aws-sdk/client-s3", "@aws-sdk/s3-request-presigner"];
22
-
23
- /**
24
- * Load an @aws-sdk package (an optional peer, ADR-0067). A missing one throws
25
- * the actionable install error; selectStorage() catches it and logs it while
26
- * degrading to local storage. Any OTHER load failure is re-thrown untouched,
27
- * so an installed-but-broken SDK is never mislabelled "not installed".
28
- */
29
- function loadAwsSdk(packageName: string): any {
30
- try {
31
- return require(packageName);
32
- } catch (error: any) {
33
- const missing = error?.code === "MODULE_NOT_FOUND" && String(error?.message ?? "").includes(`'${packageName}'`);
34
- if (!missing) throw error;
35
- throw optionalPackageMissing("S3Storage", S3_PACKAGES);
36
- }
37
- }
13
+ import { S3Client } from "./s3Client.js";
38
14
 
39
15
  /**
40
16
  * Pluggable file storage for the realtime "files" feature. StorageBackend is
41
17
  * the interface; LocalStorage (default, zero-dependency, filesystem) and
42
- * S3Storage (opt-in, S3-compatible via @aws-sdk/client-s3) are the shipped
43
- * implementations. Selection mirrors the cache/session/queue backend pattern:
18
+ * S3Storage (opt-in, S3-compatible, also zero-dependency — it uses Tina4's own
19
+ * stdlib SigV4 client, not @aws-sdk) are the shipped implementations.
20
+ * Selection mirrors the cache/session/queue backend pattern:
44
21
  * TINA4_STORAGE_BACKEND (local default | s3) plus per-backend env vars, with a
45
22
  * graceful fallback to local if an s3 backend cannot be constructed - a real
46
23
  * persistent store, never a silent no-op. Parity with Python's storage.py.
@@ -124,63 +101,46 @@ export class LocalStorage implements StorageBackend {
124
101
  }
125
102
 
126
103
  /**
127
- * S3-compatible store (AWS S3, MinIO, ...). Opt-in; the app installs the SDK:
128
- * `npm install @aws-sdk/client-s3 @aws-sdk/s3-request-presigner`.
129
- * Presigned GET URLs let clients fetch large blobs straight from object
130
- * storage instead of streaming through the app.
104
+ * S3-compatible store (AWS S3, MinIO, Garage, ...). Opt-in, zero dependencies.
105
+ *
106
+ * Talks to S3 through Tina4's own stdlib SigV4 client (S3Client, node:crypto +
107
+ * global fetch) — no @aws-sdk packages. Presigned GET URLs let clients fetch
108
+ * large blobs straight from object storage instead of streaming through the app.
131
109
  */
132
110
  export class S3Storage implements StorageBackend {
133
- private client: any;
111
+ private client: S3Client;
134
112
  private bucket: string;
135
113
 
136
114
  constructor(opts: { endpoint?: string; key?: string; secret?: string; bucket?: string; region?: string } = {}) {
137
115
  this.bucket = opts.bucket || process.env.TINA4_STORAGE_BUCKET || "";
138
116
  if (!this.bucket) throw new Error("S3Storage requires TINA4_STORAGE_BUCKET");
139
- // Loaded lazily; a missing SDK throws the install command here, and
140
- // selectStorage() logs it and falls back to local storage.
141
- const { S3Client } = loadAwsSdk("@aws-sdk/client-s3");
142
- // url() needs the presigner; check it now so a half-installed SDK refuses
143
- // at construction instead of failing on the first download link.
144
- loadAwsSdk("@aws-sdk/s3-request-presigner");
145
- const endpoint = opts.endpoint || process.env.TINA4_STORAGE_URL;
146
117
  this.client = new S3Client({
147
- endpoint: endpoint || undefined,
148
- forcePathStyle: true,
118
+ endpoint: opts.endpoint || process.env.TINA4_STORAGE_URL || undefined,
149
119
  region: opts.region || process.env.TINA4_STORAGE_REGION || "us-east-1",
150
- credentials: {
151
- accessKeyId: opts.key || process.env.TINA4_STORAGE_KEY || "",
152
- secretAccessKey: opts.secret || process.env.TINA4_STORAGE_SECRET || "",
153
- },
120
+ accessKey: opts.key || process.env.TINA4_STORAGE_KEY || "",
121
+ secretKey: opts.secret || process.env.TINA4_STORAGE_SECRET || "",
154
122
  });
155
123
  }
156
124
 
157
125
  async put(key: string, data: Buffer | string, mime = "application/octet-stream"): Promise<void> {
158
- const { PutObjectCommand } = loadAwsSdk("@aws-sdk/client-s3");
159
- await this.client.send(new PutObjectCommand({ Bucket: this.bucket, Key: key, Body: data, ContentType: mime }));
126
+ await this.client.putObject(this.bucket, key, data, mime);
160
127
  }
161
128
 
162
129
  async get(key: string): Promise<Buffer | null> {
163
130
  try {
164
- const { GetObjectCommand } = loadAwsSdk("@aws-sdk/client-s3");
165
- const res = await this.client.send(new GetObjectCommand({ Bucket: this.bucket, Key: key }));
166
- const chunks: Buffer[] = [];
167
- for await (const chunk of res.Body as AsyncIterable<Buffer>) chunks.push(Buffer.from(chunk));
168
- return Buffer.concat(chunks);
131
+ return await this.client.getObject(this.bucket, key);
169
132
  } catch {
170
133
  return null;
171
134
  }
172
135
  }
173
136
 
174
137
  async url(key: string, ttl = 3600): Promise<string | null> {
175
- const { GetObjectCommand } = loadAwsSdk("@aws-sdk/client-s3");
176
- const { getSignedUrl } = loadAwsSdk("@aws-sdk/s3-request-presigner");
177
- return getSignedUrl(this.client, new GetObjectCommand({ Bucket: this.bucket, Key: key }), { expiresIn: ttl });
138
+ return this.client.presignedGetUrl(this.bucket, key, ttl);
178
139
  }
179
140
 
180
141
  async delete(key: string): Promise<void> {
181
142
  try {
182
- const { DeleteObjectCommand } = loadAwsSdk("@aws-sdk/client-s3");
183
- await this.client.send(new DeleteObjectCommand({ Bucket: this.bucket, Key: key }));
143
+ await this.client.deleteObject(this.bucket, key);
184
144
  } catch (e) {
185
145
  Log.error(`S3Storage delete failed for ${key}: ${(e as Error).message}`);
186
146
  }
@@ -188,8 +148,7 @@ export class S3Storage implements StorageBackend {
188
148
 
189
149
  async exists(key: string): Promise<boolean> {
190
150
  try {
191
- const { HeadObjectCommand } = loadAwsSdk("@aws-sdk/client-s3");
192
- await this.client.send(new HeadObjectCommand({ Bucket: this.bucket, Key: key }));
151
+ await this.client.headObject(this.bucket, key);
193
152
  return true;
194
153
  } catch {
195
154
  return false;
@@ -200,7 +159,7 @@ export class S3Storage implements StorageBackend {
200
159
  /**
201
160
  * Resolve the storage backend from an explicit instance or the environment.
202
161
  * Falls back to LocalStorage (logging why) when an s3 backend cannot be built
203
- * (driver missing or config incomplete) - a real store, never a silent no-op.
162
+ * (config incomplete, e.g. no bucket) - a real store, never a silent no-op.
204
163
  */
205
164
  export function selectStorage(storage?: StorageBackend): StorageBackend {
206
165
  if (storage) return storage;
@@ -29,6 +29,53 @@ file, You can obtain one at https://mozilla.org/MPL/2.0/.
29
29
 
30
30
  import { DatabaseUrl } from "./databaseUrl.js";
31
31
  import { DEFAULT_SRID, SpatialNotSupportedError } from "./point.js";
32
+
33
+ // ── placeholder-scan helpers ─────────────────────────────────
34
+ // The `?`-placeholder scanner skips over literals/comments it must not count.
35
+ // Each span-skip is a pure "return the index just past this span" helper so the
36
+ // scan loop itself stays flat (keeps placeholderPositions' complexity down).
37
+ const isIdentChar = (ch: string | undefined): boolean => !!ch && /[A-Za-z0-9_]/.test(ch);
38
+
39
+ /** Index just past the quoted string/identifier opening at i (sql[i] is the quote). */
40
+ function skipQuoted(sql: string, i: number, backslashEscapes: boolean): number {
41
+ const c = sql[i];
42
+ // E'...' (Postgres escape string) honours backslash escapes; so does every
43
+ // quoted string when the engine does (MySQL).
44
+ const escapeString = c === "'" && (sql[i - 1] === "E" || sql[i - 1] === "e") && !isIdentChar(sql[i - 2]);
45
+ const backslash = c !== "`" && (escapeString || backslashEscapes);
46
+ const n = sql.length;
47
+ i++;
48
+ while (i < n) {
49
+ if (backslash && sql[i] === "\\") { i += 2; continue; }
50
+ if (sql[i] === c) {
51
+ if (sql[i + 1] === c) { i += 2; continue; } // doubled quote = escaped quote
52
+ return i + 1;
53
+ }
54
+ i++;
55
+ }
56
+ return i;
57
+ }
58
+
59
+ /** Index just past the `-- ...` line comment opening at i. */
60
+ function skipLineComment(sql: string, i: number): number {
61
+ while (i < sql.length && sql[i] !== "\n") i++;
62
+ return i;
63
+ }
64
+
65
+ /** Index just past the block comment opening at i. */
66
+ function skipBlockComment(sql: string, i: number): number {
67
+ const end = sql.indexOf("*/", i + 2);
68
+ return end === -1 ? sql.length : end + 2;
69
+ }
70
+
71
+ /** Index just past the `$tag$ ... $tag$` dollar-quoted block opening at i, or i if none opens here. */
72
+ function skipDollarQuote(sql: string, i: number): number {
73
+ const tag = sql.slice(i).match(/^\$([A-Za-z_][A-Za-z0-9_]*)?\$/);
74
+ if (!tag) return i;
75
+ const end = sql.indexOf(tag[0], i + tag[0].length);
76
+ return end === -1 ? sql.length : end + tag[0].length;
77
+ }
78
+
32
79
  export class SQLTranslator {
33
80
  private static readonly SPATIAL_ENGINES = new Set(["postgres", "postgresql"]);
34
81
  private static readonly SPATIAL_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$/;
@@ -357,51 +404,17 @@ export class SQLTranslator {
357
404
  static placeholderPositions(sql: string, options: { backslashEscapes?: boolean } = {}): number[] {
358
405
  const positions: number[] = [];
359
406
  const n = sql.length;
360
- const isIdent = (ch: string | undefined): boolean => !!ch && /[A-Za-z0-9_]/.test(ch);
361
407
  let i = 0;
362
408
  while (i < n) {
363
409
  const c = sql[i];
364
410
  const next = sql[i + 1];
365
-
366
- if (c === "'" || c === '"' || c === "`") {
367
- // E'...' (Postgres escape string) honours backslash escapes; so does
368
- // every quoted string when the engine does (MySQL).
369
- const prev = sql[i - 1];
370
- const escapeString = c === "'" && (prev === "E" || prev === "e") && !isIdent(sql[i - 2]);
371
- const backslash = c !== "`" && (escapeString || options.backslashEscapes === true);
372
- i++;
373
- while (i < n) {
374
- if (backslash && sql[i] === "\\") { i += 2; continue; }
375
- if (sql[i] === c) {
376
- if (sql[i + 1] === c) { i += 2; continue; }
377
- i++;
378
- break;
379
- }
380
- i++;
381
- }
382
- continue;
383
- }
384
-
385
- if (c === "-" && next === "-") {
386
- while (i < n && sql[i] !== "\n") i++;
387
- continue;
388
- }
389
-
390
- if (c === "/" && next === "*") {
391
- const end = sql.indexOf("*/", i + 2);
392
- i = end === -1 ? n : end + 2;
393
- continue;
411
+ if (c === "'" || c === '"' || c === "`") { i = skipQuoted(sql, i, options.backslashEscapes === true); continue; }
412
+ if (c === "-" && next === "-") { i = skipLineComment(sql, i); continue; }
413
+ if (c === "/" && next === "*") { i = skipBlockComment(sql, i); continue; }
414
+ if (c === "$" && !isIdentChar(sql[i - 1])) {
415
+ const past = skipDollarQuote(sql, i);
416
+ if (past !== i) { i = past; continue; }
394
417
  }
395
-
396
- if (c === "$" && !isIdent(sql[i - 1])) {
397
- const tag = sql.slice(i).match(/^\$([A-Za-z_][A-Za-z0-9_]*)?\$/);
398
- if (tag) {
399
- const end = sql.indexOf(tag[0], i + tag[0].length);
400
- i = end === -1 ? n : end + tag[0].length;
401
- continue;
402
- }
403
- }
404
-
405
418
  if (c === "?") positions.push(i);
406
419
  i++;
407
420
  }
@@ -437,7 +450,7 @@ export class SQLTranslator {
437
450
  * → { sql: "INSERT INTO t (x) VALUES (1)", columns: ["id", "name"] }
438
451
  */
439
452
  static parseReturning(sql: string): { sql: string; columns: string[] } {
440
- const m = sql.match(/\bRETURNING\s+(.+)$/i);
453
+ const m = sql.match(/\bRETURNING\s+(\S.*)$/i);
441
454
  if (!m) return { sql, columns: [] };
442
455
  const columns = m[1].split(",").map((c) => c.trim());
443
456
  return {
@@ -496,7 +509,10 @@ export class SQLTranslator {
496
509
  // start of the VALUES group rather than by hunting for a parenthesis (the
497
510
  // column list has parentheses too).
498
511
  private static readonly INSERT_VALUES =
499
- /^\s*INSERT\s+INTO\s+.+?\s+VALUES\s*\(([^()]*)\)\s*$/dis;
512
+ // ReDoS-safe: the table ref matches `\S(?:[\s\S]*?\S)?` (bounded by non-space
513
+ // at both ends) so the separator `\s+` before VALUES can't overlap it the way
514
+ // the old `.+?\s+` did (polynomial on `INSERT INTO ` + a long space run).
515
+ /^\s*INSERT\s+INTO\s+\S(?:[\s\S]*?\S)?\s+VALUES\s*\(([^()]*)\)\s*$/dis;
500
516
 
501
517
  /**
502
518
  * Engines whose lastInsertId reports the FIRST generated id of a multi-row
@@ -1,3 +1,21 @@
1
+ // ../core/src/slashTrim.ts
2
+ var SLASH = 47;
3
+ function rtrimSlashes(s) {
4
+ let end = s.length;
5
+ while (end > 0 && s.charCodeAt(end - 1) === SLASH) end--;
6
+ return end === s.length ? s : s.slice(0, end);
7
+ }
8
+ function trimChar(s, code) {
9
+ let start = 0;
10
+ let end = s.length;
11
+ while (start < end && s.charCodeAt(start) === code) start++;
12
+ while (end > start && s.charCodeAt(end - 1) === code) end--;
13
+ return start === 0 && end === s.length ? s : s.slice(start, end);
14
+ }
15
+ function trimSlashes(s) {
16
+ return trimChar(s, SLASH);
17
+ }
18
+
1
19
  // src/generator.ts
2
20
  var WRITE_METHODS = /* @__PURE__ */ new Set(["post", "put", "patch", "delete"]);
3
21
  var INTERNAL_PREFIXES = ["/swagger", "/__dev", "/__feedback", "/ai", "/rag", "/vision", "/embed", "/image"];
@@ -85,7 +103,10 @@ function generate(routes, models = []) {
85
103
  openapi: resolveOpenApiVersion(),
86
104
  info: buildInfo(),
87
105
  servers: resolveServers(),
88
- paths: {},
106
+ // Prototype-less: route paths are developer-defined, but a null prototype
107
+ // makes `spec.paths[path][method] = op` structurally pollution-proof
108
+ // regardless (js/prototype-polluting-assignment). Serialises to JSON the same.
109
+ paths: /* @__PURE__ */ Object.create(null),
89
110
  components: {
90
111
  schemas: {},
91
112
  // Configurable security schemes (v3.13.42): bearerFormat via env, optional
@@ -150,7 +171,7 @@ function buildOperation(route, spec, ctx) {
150
171
  const openApiPath = patternToOpenAPI(route.pattern);
151
172
  const method = route.method.toLowerCase();
152
173
  if (!spec.paths[openApiPath]) {
153
- spec.paths[openApiPath] = {};
174
+ spec.paths[openApiPath] = /* @__PURE__ */ Object.create(null);
154
175
  }
155
176
  const tags = route.meta?.tags ?? inferTags(route.pattern);
156
177
  for (const t of tags) {
@@ -468,7 +489,7 @@ function inferModelFromPath(pattern) {
468
489
  return null;
469
490
  }
470
491
  function operationIdBase(method, openApiPath) {
471
- const clean = openApiPath.replace(/^\/+|\/+$/g, "").replace(/\//g, "_").replace(/\.\.\./g, "").replace(/[{}]/g, "").replace(/\*/g, "wildcard");
492
+ const clean = trimSlashes(openApiPath).replace(/\//g, "_").replace(/\.\.\./g, "").replace(/[{}]/g, "").replace(/\*/g, "wildcard");
472
493
  return clean ? `${method}_${clean}` : method;
473
494
  }
474
495
  function uniqueOperationId(method, openApiPath, seen) {
@@ -485,7 +506,7 @@ function uniqueOperationId(method, openApiPath, seen) {
485
506
 
486
507
  // src/ui.ts
487
508
  function swaggerUiCdn() {
488
- return (process.env.TINA4_SWAGGER_UI_CDN ?? "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5").replace(/\/+$/, "");
509
+ return rtrimSlashes(process.env.TINA4_SWAGGER_UI_CDN ?? "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5");
489
510
  }
490
511
  var SWAGGER_UI_HTML = (specUrl, nonce) => `<!DOCTYPE html>
491
512
  <html lang="en">
@@ -7,6 +7,7 @@ file, You can obtain one at https://mozilla.org/MPL/2.0/.
7
7
  */
8
8
 
9
9
  import type { RouteDefinition } from "../../core/src/index.js";
10
+ import { trimSlashes } from "../../core/src/slashTrim.js";
10
11
  import type { ModelDefinition, FieldDefinition } from "../../orm/src/index.js";
11
12
 
12
13
  interface OpenAPISpecInfo {
@@ -191,7 +192,10 @@ export function generate(
191
192
  openapi: resolveOpenApiVersion(),
192
193
  info: buildInfo(),
193
194
  servers: resolveServers(),
194
- paths: {},
195
+ // Prototype-less: route paths are developer-defined, but a null prototype
196
+ // makes `spec.paths[path][method] = op` structurally pollution-proof
197
+ // regardless (js/prototype-polluting-assignment). Serialises to JSON the same.
198
+ paths: Object.create(null),
195
199
  components: {
196
200
  schemas: {},
197
201
  // Configurable security schemes (v3.13.42): bearerFormat via env, optional
@@ -297,7 +301,7 @@ function buildOperation(route: RouteDefinition, spec: OpenAPISpec, ctx: BuildCon
297
301
  const method = route.method.toLowerCase();
298
302
 
299
303
  if (!spec.paths[openApiPath]) {
300
- spec.paths[openApiPath] = {};
304
+ spec.paths[openApiPath] = Object.create(null);
301
305
  }
302
306
 
303
307
  const tags = route.meta?.tags ?? inferTags(route.pattern);
@@ -793,8 +797,7 @@ function inferModelFromPath(pattern: string): string | null {
793
797
  * distinct ids straight from the two distinct paths.
794
798
  */
795
799
  function operationIdBase(method: string, openApiPath: string): string {
796
- const clean = openApiPath
797
- .replace(/^\/+|\/+$/g, "") // strip leading/trailing slashes (Python .strip("/"))
800
+ const clean = trimSlashes(openApiPath) // strip leading/trailing slashes (ReDoS-safe)
798
801
  .replace(/\//g, "_") // internal slash -> underscore
799
802
  .replace(/\.\.\./g, "") // catch-all '...' inside braces -> nothing ({...slug} -> slug)
800
803
  .replace(/[{}]/g, "") // drop braces
@@ -7,6 +7,7 @@ file, You can obtain one at https://mozilla.org/MPL/2.0/.
7
7
  */
8
8
 
9
9
  import type { Tina4Request, Tina4Response, RouteDefinition } from "../../core/src/index.js";
10
+ import { rtrimSlashes } from "../../core/src/slashTrim.js";
10
11
 
11
12
  // The UI assets load from a CDN by default (a documented architecture decision —
12
13
  // we don't vendor ~1.4MB of swagger-ui-dist, to stay small). jsdelivr
@@ -15,7 +16,7 @@ import type { Tina4Request, Tina4Response, RouteDefinition } from "../../core/sr
15
16
  // splitting jsdelivr/unpkg. Air-gapped deployments point TINA4_SWAGGER_UI_CDN
16
17
  // at a self-hosted mirror (a base URL serving swagger-ui.css + swagger-ui-bundle.js).
17
18
  function swaggerUiCdn(): string {
18
- return (process.env.TINA4_SWAGGER_UI_CDN ?? "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5").replace(/\/+$/, "");
19
+ return rtrimSlashes(process.env.TINA4_SWAGGER_UI_CDN ?? "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5");
19
20
  }
20
21
 
21
22
  // The inline <style> and the inline SwaggerUIBundle(...) <script> carry this