@donotdev/cli 0.2.3 → 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.
- package/dependencies-matrix.json +27 -26
- package/dist/bin/commands/build.js +64 -2
- package/dist/bin/commands/bump.js +98 -13
- package/dist/bin/commands/db-check.js +192804 -0
- package/dist/bin/commands/db.js +16 -1
- package/dist/bin/commands/make-admin.js +22 -6
- package/dist/bin/commands/seed.js +313 -236
- package/dist/bin/commands/setup.js +549 -97
- package/dist/bin/dndev.js +23 -7
- package/dist/index.js +64 -2
- package/package.json +1 -1
- package/templates/app-demo/index.html.example +1 -1
- package/templates/app-dndev/index.html.example +1 -1
- package/templates/app-dndev/src/globals.css.example +1 -1
- package/templates/app-next/src/app/AppDocument.tsx.example +3 -2
- package/templates/app-next/src/globals.css.example +1 -1
- package/templates/app-vite/csp.example.json +1 -1
- package/templates/app-vite/index.html.example +1 -1
- package/templates/app-vite/src/globals.css.example +1 -1
- package/templates/deploy-config/vercel.json.example +2 -2
- package/templates/functions-supabase/supabase/migrations/20250101000006_crud_bulk_status_guard.sql +258 -0
- package/templates/functions-supabase/supabase/migrations/20250101000007_rate_limit_check.sql +76 -0
- package/templates/root-consumer/.claude/hooks/guard-bash.sh.example +3 -3
- package/templates/root-consumer/.claude/hooks/typecheck-stop.sh.example +2 -2
- package/templates/root-consumer/.claude/rules/definition-of-done.md.example +2 -2
- package/templates/root-consumer/.claude/rules/framework.md.example +1 -1
- package/templates/root-consumer/.claude/skills/build/SKILL.md.example +1 -1
- package/templates/root-consumer/.claude/skills/polish/SKILL.md.example +1 -1
- package/templates/root-consumer/AGENTS.md.example +25 -2
- package/templates/root-consumer/README.md.example +1 -1
package/dist/bin/dndev.js
CHANGED
|
@@ -750,6 +750,20 @@ var init_command_registry = __esm({
|
|
|
750
750
|
loader: "../cli/db/db.ts",
|
|
751
751
|
exportName: "db"
|
|
752
752
|
},
|
|
753
|
+
{
|
|
754
|
+
name: "db-check [app]",
|
|
755
|
+
description: "List, per generated CHECK constraint (<table>_<column>_<rule>, added NOT VALID), the row ids that violate it (Supabase, read-only)",
|
|
756
|
+
category: "deployment",
|
|
757
|
+
public: true,
|
|
758
|
+
options: [
|
|
759
|
+
{
|
|
760
|
+
flags: "-a, --app <app>",
|
|
761
|
+
description: "App name (for multi-app monorepos)"
|
|
762
|
+
}
|
|
763
|
+
],
|
|
764
|
+
loader: "../cli/db/check.ts",
|
|
765
|
+
exportName: "dbCheck"
|
|
766
|
+
},
|
|
753
767
|
// ---------------------------------------------------------------------------
|
|
754
768
|
// Content
|
|
755
769
|
// ---------------------------------------------------------------------------
|
|
@@ -889,16 +903,18 @@ var init_command_registry = __esm({
|
|
|
889
903
|
},
|
|
890
904
|
{
|
|
891
905
|
name: "test:uat [app]",
|
|
892
|
-
description: "Run Playwright
|
|
906
|
+
description: "Run an app's Playwright e2e suite on a throwaway Supabase stack (own project_id, ports and volumes; torn down afterwards). Works in consumer projects and the monorepo; reads e2e/uat.json",
|
|
893
907
|
category: "other",
|
|
894
908
|
appCommand: true,
|
|
895
909
|
options: [
|
|
896
|
-
{ flags: "--
|
|
897
|
-
{ flags: "--headed", description: "run tests in headed browser" },
|
|
910
|
+
{ flags: "-a, --app <app>", description: "app to test (same as the positional)" },
|
|
898
911
|
{
|
|
899
|
-
flags: "--
|
|
900
|
-
description: "
|
|
901
|
-
}
|
|
912
|
+
flags: "--keep",
|
|
913
|
+
description: "keep the throwaway stack and workdir after the run"
|
|
914
|
+
},
|
|
915
|
+
{ flags: "--headed", description: "run tests in headed browser" },
|
|
916
|
+
{ flags: "--ui", description: "open Playwright UI mode" },
|
|
917
|
+
{ flags: "--grep <pattern>", description: "only run tests matching the pattern" }
|
|
902
918
|
],
|
|
903
919
|
loader: "../quality/test-uat.ts"
|
|
904
920
|
},
|
|
@@ -1003,7 +1019,7 @@ function registerCommand(program2, def, action) {
|
|
|
1003
1019
|
}
|
|
1004
1020
|
|
|
1005
1021
|
// packages/cli/src/bin/dndev.mjs
|
|
1006
|
-
var CLI_VERSION = true ? "0.
|
|
1022
|
+
var CLI_VERSION = true ? "0.3.0" : "0.0.0";
|
|
1007
1023
|
var args = process.argv.slice(2);
|
|
1008
1024
|
if (args.length === 1 && (args[0] === "--version" || args[0] === "-v")) {
|
|
1009
1025
|
console.log(CLI_VERSION);
|
package/dist/index.js
CHANGED
|
@@ -5571,7 +5571,7 @@ var require_tasks = __commonJS({
|
|
|
5571
5571
|
const positivePatterns = getPositivePatterns(patterns);
|
|
5572
5572
|
const negativePatterns = getNegativePatternsAsPositive(patterns, ignore);
|
|
5573
5573
|
const staticPatterns = positivePatterns.filter((pattern) => utils.pattern.isStaticPattern(pattern, settings2));
|
|
5574
|
-
const
|
|
5574
|
+
const dynamicPatterns2 = positivePatterns.filter((pattern) => utils.pattern.isDynamicPattern(pattern, settings2));
|
|
5575
5575
|
const staticTasks = convertPatternsToTasks(
|
|
5576
5576
|
staticPatterns,
|
|
5577
5577
|
negativePatterns,
|
|
@@ -5579,7 +5579,7 @@ var require_tasks = __commonJS({
|
|
|
5579
5579
|
false
|
|
5580
5580
|
);
|
|
5581
5581
|
const dynamicTasks = convertPatternsToTasks(
|
|
5582
|
-
|
|
5582
|
+
dynamicPatterns2,
|
|
5583
5583
|
negativePatterns,
|
|
5584
5584
|
/* dynamic */
|
|
5585
5585
|
true
|
|
@@ -22792,6 +22792,67 @@ function clearFirebaseCache(appDir) {
|
|
|
22792
22792
|
}
|
|
22793
22793
|
}
|
|
22794
22794
|
|
|
22795
|
+
// packages/tooling/src/apps/sitemap-report.ts
|
|
22796
|
+
init_utils2();
|
|
22797
|
+
init_cli_output();
|
|
22798
|
+
init_pathResolver();
|
|
22799
|
+
var SITEMAP_BODY = ".next/server/app/sitemap.xml.body";
|
|
22800
|
+
var PRERENDER_MANIFEST = ".next/prerender-manifest.json";
|
|
22801
|
+
var ROUTE_MANIFEST = "public/route-manifest.json";
|
|
22802
|
+
function dynamicPatterns(appDir) {
|
|
22803
|
+
const manifestPath = joinPath(appDir, ROUTE_MANIFEST);
|
|
22804
|
+
if (!pathExists(manifestPath)) return [];
|
|
22805
|
+
const manifest = readSync(manifestPath, { format: "json" });
|
|
22806
|
+
return (manifest?.routes ?? []).filter(
|
|
22807
|
+
(route) => route.path.includes(":") && (!route.auth || route.auth === false) && route.meta?.seo?.noindex !== true
|
|
22808
|
+
).map((route) => route.path);
|
|
22809
|
+
}
|
|
22810
|
+
function patternRegExp(pattern) {
|
|
22811
|
+
const body = pattern.split("/").map(
|
|
22812
|
+
(segment) => segment.startsWith(":") ? "[^/]+" : segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
|
|
22813
|
+
).join("/");
|
|
22814
|
+
return new RegExp(`^(?:/[^/]+)?${body}/?$`);
|
|
22815
|
+
}
|
|
22816
|
+
function reportSitemap(appDir) {
|
|
22817
|
+
const bodyPath = joinPath(appDir, SITEMAP_BODY);
|
|
22818
|
+
if (!pathExists(bodyPath)) {
|
|
22819
|
+
log2.info(
|
|
22820
|
+
`\u{1F5FA}\uFE0F sitemap: URL count unavailable (no prerendered sitemap at ${SITEMAP_BODY})`
|
|
22821
|
+
);
|
|
22822
|
+
return;
|
|
22823
|
+
}
|
|
22824
|
+
const xml = readSync(bodyPath, { format: "text" });
|
|
22825
|
+
if (typeof xml !== "string") {
|
|
22826
|
+
log2.info(`\u{1F5FA}\uFE0F sitemap: URL count unavailable (${SITEMAP_BODY} unreadable)`);
|
|
22827
|
+
return;
|
|
22828
|
+
}
|
|
22829
|
+
const paths = [...xml.matchAll(/<loc>([^<]+)<\/loc>/g)].map(
|
|
22830
|
+
(match) => new URL(match[1]).pathname
|
|
22831
|
+
);
|
|
22832
|
+
const patterns = dynamicPatterns(appDir).map((pattern) => ({
|
|
22833
|
+
pattern,
|
|
22834
|
+
regExp: patternRegExp(pattern),
|
|
22835
|
+
count: 0
|
|
22836
|
+
}));
|
|
22837
|
+
let staticCount = 0;
|
|
22838
|
+
for (const path of paths) {
|
|
22839
|
+
const dynamic = patterns.find(({ regExp }) => regExp.test(path));
|
|
22840
|
+
if (dynamic) dynamic.count += 1;
|
|
22841
|
+
else staticCount += 1;
|
|
22842
|
+
}
|
|
22843
|
+
const parts = [
|
|
22844
|
+
`${staticCount} static`,
|
|
22845
|
+
...patterns.map(({ pattern, count }) => `${count} from ${pattern}`)
|
|
22846
|
+
];
|
|
22847
|
+
const prerenderPath = joinPath(appDir, PRERENDER_MANIFEST);
|
|
22848
|
+
const manifest = pathExists(prerenderPath) ? readSync(prerenderPath, { format: "json" }) : null;
|
|
22849
|
+
const revalidate = manifest?.routes?.["/sitemap.xml"]?.initialRevalidateSeconds;
|
|
22850
|
+
const refresh = typeof revalidate === "number" ? `; re-read every ${revalidate}s` : "; not re-read until the next build";
|
|
22851
|
+
log2.info(
|
|
22852
|
+
`\u{1F5FA}\uFE0F sitemap: ${paths.length} URLs at build (${parts.join(" + ")})${refresh}`
|
|
22853
|
+
);
|
|
22854
|
+
}
|
|
22855
|
+
|
|
22795
22856
|
// packages/tooling/src/apps/build.ts
|
|
22796
22857
|
init_app_detection();
|
|
22797
22858
|
init_app_selector();
|
|
@@ -22950,6 +23011,7 @@ async function main(options = {}) {
|
|
|
22950
23011
|
if (result.status !== 0) {
|
|
22951
23012
|
return result.status || 1;
|
|
22952
23013
|
}
|
|
23014
|
+
if (app.framework === "nextjs") reportSitemap(appDir);
|
|
22953
23015
|
}
|
|
22954
23016
|
if (buildType === "functions" || buildType === "both") {
|
|
22955
23017
|
if (!hasFunc) {
|
package/package.json
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
10
10
|
<title>DoNotDev Demo</title>
|
|
11
11
|
|
|
12
|
-
<!-- Fonts:
|
|
12
|
+
<!-- Fonts: the theme's framework fonts, bundled from @donotdev/ui/dndev.css (others dropped at build). -->
|
|
13
13
|
|
|
14
14
|
<!-- ✅ CRITICAL CSS: ECG waveform loader -->
|
|
15
15
|
<style>
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
<!-- ✅ DnDev: Asset manifest injection point -->
|
|
14
14
|
<!-- window.__DNDEV_ASSETS__ and __DNDEV_ASSET_MANIFEST__ injected here -->
|
|
15
15
|
|
|
16
|
-
<!-- Fonts:
|
|
16
|
+
<!-- Fonts: the theme's framework fonts, bundled from @donotdev/ui/dndev.css (others dropped at build). -->
|
|
17
17
|
<!-- DNDEV_FONT_PRELOADS -->
|
|
18
18
|
|
|
19
19
|
<!-- ✅ PERFORMANCE: Preconnect to external domains (OAuth providers) -->
|
|
@@ -6,5 +6,5 @@
|
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
8
|
* Font choices (--font-family, --font-sans, etc.) belong in themes.css.
|
|
9
|
-
*
|
|
9
|
+
* Self-hosted: the build keeps only the @donotdev/ui catalogue fonts (Inter, Playfair Display, Space Grotesk, Roboto, Press Start 2P) they name; no external fetch, no public/fonts required.
|
|
10
10
|
*/
|
|
@@ -6,8 +6,9 @@ import { FontPreloadLinks } from '@donotdev/ui/next';
|
|
|
6
6
|
import '../globals.css';
|
|
7
7
|
|
|
8
8
|
/**
|
|
9
|
-
* Framework fonts
|
|
10
|
-
*
|
|
9
|
+
* Framework fonts: only the catalogue families themes.css renders text in, copied to
|
|
10
|
+
* public/ at build. FontPreloadLinks links their stylesheet (renders nothing when the
|
|
11
|
+
* theme uses only the app's own fonts).
|
|
11
12
|
*/
|
|
12
13
|
|
|
13
14
|
/**
|
|
@@ -5,6 +5,6 @@
|
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Font choices (--font-family, --font-sans, etc.) belong in themes.css.
|
|
8
|
-
*
|
|
8
|
+
* The framework fonts they name are served from public/fonts/ (copied by discovery); own fonts ship none.
|
|
9
9
|
* dndev-next.css = font-stripped variant — use this for Next.js, NOT dndev.css.
|
|
10
10
|
*/
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
<!-- ✅ DnDev: Asset manifest injection point -->
|
|
14
14
|
<!-- window.__DNDEV_ASSETS__ and __DNDEV_ASSET_MANIFEST__ injected here -->
|
|
15
15
|
|
|
16
|
-
<!-- Fonts:
|
|
16
|
+
<!-- Fonts: the theme's framework fonts, bundled from @donotdev/ui/dndev.css (others dropped at build). -->
|
|
17
17
|
<!-- DNDEV_FONT_PRELOADS -->
|
|
18
18
|
|
|
19
19
|
<!-- ✅ PERFORMANCE: Preconnect to external domains (OAuth providers) -->
|
|
@@ -5,5 +5,5 @@
|
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Font choices (--font-family, --font-sans, etc.) belong in themes.css.
|
|
8
|
-
*
|
|
8
|
+
* Self-hosted: the build keeps only the @donotdev/ui catalogue fonts (Inter, Playfair Display, Space Grotesk, Roboto, Press Start 2P) they name; no external fetch, no public/fonts required.
|
|
9
9
|
*/
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
"headers": [
|
|
19
19
|
{
|
|
20
20
|
"key": "Content-Security-Policy",
|
|
21
|
-
"value": "default-src 'self'; script-src 'self' 'unsafe-inline'{{#isFirebase}}{{#needsAuth}} https://accounts.google.com https://apis.google.com{{/needsAuth}}{{/isFirebase}}{{#needsBilling}} https://js.stripe.com{{/needsBilling}}; style-src 'self' 'unsafe-inline'
|
|
21
|
+
"value": "default-src 'self'; script-src 'self' 'unsafe-inline'{{#isFirebase}}{{#needsAuth}} https://accounts.google.com https://apis.google.com{{/needsAuth}}{{/isFirebase}}{{#needsBilling}} https://js.stripe.com{{/needsBilling}}; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; connect-src 'self'{{#isFirebase}}{{#needsAuth}} https://identitytoolkit.googleapis.com https://securetoken.googleapis.com https://www.googleapis.com https://*.googleapis.com https://{{firebaseProjectId}}.firebaseio.com{{/needsAuth}}{{/isFirebase}}{{#isSupabase}} https://*.supabase.co wss://*.supabase.co{{/isSupabase}}{{#needsBilling}} https://api.stripe.com{{/needsBilling}}; frame-src 'none'{{#isFirebase}}{{#needsAuth}} https://accounts.google.com{{/needsAuth}}{{/isFirebase}}{{#needsBilling}} https://js.stripe.com https://hooks.stripe.com{{/needsBilling}}; object-src 'none'; base-uri 'self'; form-action 'self'; upgrade-insecure-requests"
|
|
22
22
|
},
|
|
23
23
|
{
|
|
24
24
|
"key": "X-Content-Type-Options",
|
|
@@ -242,7 +242,7 @@
|
|
|
242
242
|
"headers": [
|
|
243
243
|
{
|
|
244
244
|
"key": "Content-Security-Policy",
|
|
245
|
-
"value": "default-src 'self'; script-src 'self' 'unsafe-inline'{{#isFirebase}}{{#needsAuth}} https://accounts.google.com https://apis.google.com{{/needsAuth}}{{/isFirebase}}{{#needsBilling}} https://js.stripe.com{{/needsBilling}}; style-src 'self' 'unsafe-inline'
|
|
245
|
+
"value": "default-src 'self'; script-src 'self' 'unsafe-inline'{{#isFirebase}}{{#needsAuth}} https://accounts.google.com https://apis.google.com{{/needsAuth}}{{/isFirebase}}{{#needsBilling}} https://js.stripe.com{{/needsBilling}}; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; connect-src 'self'{{#isFirebase}}{{#needsAuth}} https://identitytoolkit.googleapis.com https://securetoken.googleapis.com https://www.googleapis.com https://*.googleapis.com https://{{firebaseProjectId}}.firebaseio.com{{/needsAuth}}{{/isFirebase}}{{#isSupabase}} https://*.supabase.co wss://*.supabase.co{{/isSupabase}}{{#needsBilling}} https://api.stripe.com{{/needsBilling}}; frame-src 'none'{{#isFirebase}}{{#needsAuth}} https://accounts.google.com{{/needsAuth}}{{/isFirebase}}{{#needsBilling}} https://js.stripe.com https://hooks.stripe.com{{/needsBilling}}; object-src 'none'; base-uri 'self'; form-action 'self'; upgrade-insecure-requests"
|
|
246
246
|
},
|
|
247
247
|
{
|
|
248
248
|
"key": "X-Content-Type-Options",
|
package/templates/functions-supabase/supabase/migrations/20250101000006_crud_bulk_status_guard.sql
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
-- Migration: crud_bulk re-checks the stored status of updated rows under lock
|
|
2
|
+
-- Generated: 2026-11-17
|
|
3
|
+
-- Purpose: Backs packages/functions/src/supabase/crud/bulk.ts. The handler reads the
|
|
4
|
+
-- stored rows of the updated ids BEFORE the RPC (their status decides each
|
|
5
|
+
-- patch's schema: draft / update / whole-row check on publish). That read is
|
|
6
|
+
-- outside this transaction, so the RPC re-reads every updated row's status
|
|
7
|
+
-- with FOR UPDATE and rejects the whole bulk when it is not the status the
|
|
8
|
+
-- handler validated against (SQLSTATE PT409 (PostgREST: HTTP 409 Conflict, never retried; 40001 is a retryable serialization failure), nothing written).
|
|
9
|
+
--
|
|
10
|
+
-- Replaces the 4-argument crud_bulk of 20250101000004: the new signature takes
|
|
11
|
+
-- p_expected_statuses, so a handler calling with it against a database that never
|
|
12
|
+
-- ran this migration fails loud (function not found) instead of skipping the check.
|
|
13
|
+
-- Also compares ids as literals coerced to the column type (`id = '<id>'`), so
|
|
14
|
+
-- uuid and text id columns both work (the 4-argument version bound the id as
|
|
15
|
+
-- text: `uuid = text` does not exist, every update / delete on a uuid table failed).
|
|
16
|
+
|
|
17
|
+
-- Semantics:
|
|
18
|
+
-- 1. Validate p_collection (length + quote_ident safety).
|
|
19
|
+
-- 2. Reject empty batches (defense in depth — handler short-circuits too).
|
|
20
|
+
-- 3. Status guard: each distinct updated id must be a key of p_expected_statuses
|
|
21
|
+
-- (value: the status read by the handler, JSON null when it was null); the row
|
|
22
|
+
-- is locked (FOR UPDATE) and its status compared. Missing row → raise; status
|
|
23
|
+
-- changed → raise SQLSTATE PT409 (PostgREST: HTTP 409 Conflict, never retried; 40001 is a retryable serialization failure). Runs before any write.
|
|
24
|
+
-- 4. Inserts: use client-provided id if present, else gen_random_uuid().
|
|
25
|
+
-- 5. Updates: apply partial patch — only keys in patch are overwritten.
|
|
26
|
+
-- 6. Deletes: by id.
|
|
27
|
+
-- 7. Any failure raises — Postgres rolls the function back as a unit.
|
|
28
|
+
-- 8. Returns { inserted_ids, updated_ids, deleted_ids } in snake_case.
|
|
29
|
+
|
|
30
|
+
DROP FUNCTION IF EXISTS crud_bulk(TEXT, JSONB, JSONB, JSONB);
|
|
31
|
+
|
|
32
|
+
CREATE OR REPLACE FUNCTION crud_bulk(
|
|
33
|
+
p_collection TEXT,
|
|
34
|
+
p_inserts JSONB,
|
|
35
|
+
p_updates JSONB,
|
|
36
|
+
p_deletes JSONB,
|
|
37
|
+
p_expected_statuses JSONB
|
|
38
|
+
) RETURNS JSONB
|
|
39
|
+
LANGUAGE plpgsql
|
|
40
|
+
SECURITY DEFINER
|
|
41
|
+
SET search_path = public
|
|
42
|
+
AS $$
|
|
43
|
+
DECLARE
|
|
44
|
+
_inserted_ids TEXT[] := ARRAY[]::TEXT[];
|
|
45
|
+
_updated_ids TEXT[] := ARRAY[]::TEXT[];
|
|
46
|
+
_deleted_ids TEXT[] := ARRAY[]::TEXT[];
|
|
47
|
+
|
|
48
|
+
_insert_count INTEGER;
|
|
49
|
+
_update_count INTEGER;
|
|
50
|
+
_delete_count INTEGER;
|
|
51
|
+
|
|
52
|
+
_row JSONB;
|
|
53
|
+
_row_with_id JSONB;
|
|
54
|
+
_update_entry JSONB;
|
|
55
|
+
_patch JSONB;
|
|
56
|
+
_update_id TEXT;
|
|
57
|
+
_delete_id TEXT;
|
|
58
|
+
_inserted_id TEXT;
|
|
59
|
+
_updated_id TEXT;
|
|
60
|
+
_deleted_id TEXT;
|
|
61
|
+
|
|
62
|
+
_guard_id TEXT;
|
|
63
|
+
_expected_status TEXT;
|
|
64
|
+
_found_status TEXT;
|
|
65
|
+
_found BOOLEAN;
|
|
66
|
+
|
|
67
|
+
_set_sql TEXT;
|
|
68
|
+
_patch_key TEXT;
|
|
69
|
+
_patch_value JSONB;
|
|
70
|
+
_first_key BOOLEAN;
|
|
71
|
+
BEGIN
|
|
72
|
+
-- 1. Collection name validation — length-bound and safe for quote_ident.
|
|
73
|
+
IF p_collection IS NULL OR length(p_collection) = 0 THEN
|
|
74
|
+
RAISE EXCEPTION 'crud_bulk: p_collection must be a non-empty text';
|
|
75
|
+
END IF;
|
|
76
|
+
IF length(p_collection) > 63 THEN
|
|
77
|
+
RAISE EXCEPTION 'crud_bulk: p_collection exceeds 63-char Postgres identifier limit';
|
|
78
|
+
END IF;
|
|
79
|
+
|
|
80
|
+
-- 2. Reject empty batches — handler already short-circuits, but we enforce
|
|
81
|
+
-- the same contract at the SQL boundary.
|
|
82
|
+
_insert_count := COALESCE(jsonb_array_length(p_inserts), 0);
|
|
83
|
+
_update_count := COALESCE(jsonb_array_length(p_updates), 0);
|
|
84
|
+
_delete_count := COALESCE(jsonb_array_length(p_deletes), 0);
|
|
85
|
+
|
|
86
|
+
IF _insert_count = 0 AND _update_count = 0 AND _delete_count = 0 THEN
|
|
87
|
+
RAISE EXCEPTION 'crud_bulk: at least one of p_inserts, p_updates, p_deletes must be non-empty';
|
|
88
|
+
END IF;
|
|
89
|
+
|
|
90
|
+
-- 3. Status guard — the handler validated each patch against the status it
|
|
91
|
+
-- read before this transaction. Lock every updated row and compare, before
|
|
92
|
+
-- any write: all patches of one id are checked against the pre-bulk status.
|
|
93
|
+
IF _update_count > 0 THEN
|
|
94
|
+
IF p_expected_statuses IS NULL OR jsonb_typeof(p_expected_statuses) <> 'object' THEN
|
|
95
|
+
RAISE EXCEPTION 'crud_bulk: p_expected_statuses must be an object (id -> status read by the handler)';
|
|
96
|
+
END IF;
|
|
97
|
+
FOR _guard_id IN
|
|
98
|
+
SELECT DISTINCT value ->> 'id' FROM jsonb_array_elements(p_updates)
|
|
99
|
+
LOOP
|
|
100
|
+
IF _guard_id IS NULL THEN
|
|
101
|
+
RAISE EXCEPTION 'crud_bulk: each update entry must carry a string "id"';
|
|
102
|
+
END IF;
|
|
103
|
+
IF NOT (p_expected_statuses ? _guard_id) THEN
|
|
104
|
+
RAISE EXCEPTION 'crud_bulk: no expected status for % id=%', p_collection, _guard_id;
|
|
105
|
+
END IF;
|
|
106
|
+
_expected_status := p_expected_statuses ->> _guard_id;
|
|
107
|
+
|
|
108
|
+
EXECUTE format(
|
|
109
|
+
'SELECT true, status::text FROM %I WHERE id = %L FOR UPDATE',
|
|
110
|
+
p_collection,
|
|
111
|
+
_guard_id
|
|
112
|
+
)
|
|
113
|
+
INTO _found, _found_status;
|
|
114
|
+
|
|
115
|
+
IF _found IS NULL THEN
|
|
116
|
+
RAISE EXCEPTION 'crud_bulk: update on % with id=% matched no row', p_collection, _guard_id;
|
|
117
|
+
END IF;
|
|
118
|
+
IF _found_status IS DISTINCT FROM _expected_status THEN
|
|
119
|
+
RAISE EXCEPTION USING
|
|
120
|
+
ERRCODE = 'PT409',
|
|
121
|
+
MESSAGE = format(
|
|
122
|
+
'crud_bulk: status of %s id=%s changed since it was read (expected %s, found %s)',
|
|
123
|
+
p_collection,
|
|
124
|
+
_guard_id,
|
|
125
|
+
COALESCE(_expected_status, 'null'),
|
|
126
|
+
COALESCE(_found_status, 'null')
|
|
127
|
+
);
|
|
128
|
+
END IF;
|
|
129
|
+
END LOOP;
|
|
130
|
+
END IF;
|
|
131
|
+
|
|
132
|
+
-- 4. Inserts — preserve input order. Client-generated ids win; otherwise
|
|
133
|
+
-- allocate a uuid. jsonb_populate_record handles type coercion against
|
|
134
|
+
-- the real table schema, so unknown keys are ignored and typed columns
|
|
135
|
+
-- are cast correctly.
|
|
136
|
+
IF _insert_count > 0 THEN
|
|
137
|
+
FOR _row IN SELECT value FROM jsonb_array_elements(p_inserts)
|
|
138
|
+
LOOP
|
|
139
|
+
IF _row ? 'id' AND jsonb_typeof(_row -> 'id') = 'string' THEN
|
|
140
|
+
_row_with_id := _row;
|
|
141
|
+
ELSE
|
|
142
|
+
_row_with_id := _row || jsonb_build_object('id', gen_random_uuid()::text);
|
|
143
|
+
END IF;
|
|
144
|
+
|
|
145
|
+
EXECUTE format(
|
|
146
|
+
'INSERT INTO %1$I SELECT * FROM jsonb_populate_record(NULL::%1$I, $1) RETURNING id',
|
|
147
|
+
p_collection
|
|
148
|
+
)
|
|
149
|
+
USING _row_with_id
|
|
150
|
+
INTO _inserted_id;
|
|
151
|
+
|
|
152
|
+
IF _inserted_id IS NULL THEN
|
|
153
|
+
RAISE EXCEPTION 'crud_bulk: insert into % returned no id', p_collection;
|
|
154
|
+
END IF;
|
|
155
|
+
|
|
156
|
+
_inserted_ids := _inserted_ids || _inserted_id;
|
|
157
|
+
END LOOP;
|
|
158
|
+
END IF;
|
|
159
|
+
|
|
160
|
+
-- 5. Updates — partial patches. We build a dynamic SET clause from the
|
|
161
|
+
-- patch keys so unspecified columns are untouched (jsonb_populate_record
|
|
162
|
+
-- would overwrite them with NULLs). Each patch key is quoted via
|
|
163
|
+
-- quote_ident; values are applied as jsonb with -> lookups inside the
|
|
164
|
+
-- generated SQL, binding the whole patch as a single $1 parameter. The id
|
|
165
|
+
-- is a quoted literal (%L), coerced to the id column type.
|
|
166
|
+
IF _update_count > 0 THEN
|
|
167
|
+
FOR _update_entry IN SELECT value FROM jsonb_array_elements(p_updates)
|
|
168
|
+
LOOP
|
|
169
|
+
IF NOT (_update_entry ? 'id') OR jsonb_typeof(_update_entry -> 'id') <> 'string' THEN
|
|
170
|
+
RAISE EXCEPTION 'crud_bulk: each update entry must carry a string "id"';
|
|
171
|
+
END IF;
|
|
172
|
+
IF NOT (_update_entry ? 'patch') OR jsonb_typeof(_update_entry -> 'patch') <> 'object' THEN
|
|
173
|
+
RAISE EXCEPTION 'crud_bulk: each update entry must carry an object "patch"';
|
|
174
|
+
END IF;
|
|
175
|
+
|
|
176
|
+
_update_id := _update_entry ->> 'id';
|
|
177
|
+
_patch := _update_entry -> 'patch';
|
|
178
|
+
|
|
179
|
+
-- Empty patch is a no-op at the app layer; refuse it here too so a
|
|
180
|
+
-- caller mistake surfaces loudly instead of silently "succeeding".
|
|
181
|
+
IF (SELECT count(*) FROM jsonb_object_keys(_patch)) = 0 THEN
|
|
182
|
+
RAISE EXCEPTION 'crud_bulk: update patch for id=% is empty', _update_id;
|
|
183
|
+
END IF;
|
|
184
|
+
|
|
185
|
+
_set_sql := '';
|
|
186
|
+
_first_key := TRUE;
|
|
187
|
+
FOR _patch_key, _patch_value IN SELECT * FROM jsonb_each(_patch)
|
|
188
|
+
LOOP
|
|
189
|
+
IF NOT _first_key THEN
|
|
190
|
+
_set_sql := _set_sql || ', ';
|
|
191
|
+
END IF;
|
|
192
|
+
-- quote_ident keeps the column name safe; the value is bound via
|
|
193
|
+
-- $1 so no user data is ever concatenated into SQL.
|
|
194
|
+
_set_sql := _set_sql
|
|
195
|
+
|| quote_ident(_patch_key)
|
|
196
|
+
|| ' = (jsonb_populate_record(NULL::'
|
|
197
|
+
|| quote_ident(p_collection)
|
|
198
|
+
|| ', $1)).'
|
|
199
|
+
|| quote_ident(_patch_key);
|
|
200
|
+
_first_key := FALSE;
|
|
201
|
+
END LOOP;
|
|
202
|
+
|
|
203
|
+
EXECUTE format(
|
|
204
|
+
'UPDATE %I SET %s WHERE id = %L RETURNING id',
|
|
205
|
+
p_collection,
|
|
206
|
+
_set_sql,
|
|
207
|
+
_update_id
|
|
208
|
+
)
|
|
209
|
+
USING _patch
|
|
210
|
+
INTO _updated_id;
|
|
211
|
+
|
|
212
|
+
IF _updated_id IS NULL THEN
|
|
213
|
+
RAISE EXCEPTION 'crud_bulk: update on % with id=% matched no row', p_collection, _update_id;
|
|
214
|
+
END IF;
|
|
215
|
+
|
|
216
|
+
_updated_ids := _updated_ids || _updated_id;
|
|
217
|
+
END LOOP;
|
|
218
|
+
END IF;
|
|
219
|
+
|
|
220
|
+
-- 6. Deletes — by id, preserve input order.
|
|
221
|
+
IF _delete_count > 0 THEN
|
|
222
|
+
FOR _delete_id IN SELECT value #>> '{}' FROM jsonb_array_elements(p_deletes)
|
|
223
|
+
LOOP
|
|
224
|
+
IF _delete_id IS NULL OR length(_delete_id) = 0 THEN
|
|
225
|
+
RAISE EXCEPTION 'crud_bulk: delete id must be a non-empty string';
|
|
226
|
+
END IF;
|
|
227
|
+
|
|
228
|
+
EXECUTE format(
|
|
229
|
+
'DELETE FROM %I WHERE id = %L RETURNING id',
|
|
230
|
+
p_collection,
|
|
231
|
+
_delete_id
|
|
232
|
+
)
|
|
233
|
+
INTO _deleted_id;
|
|
234
|
+
|
|
235
|
+
IF _deleted_id IS NULL THEN
|
|
236
|
+
RAISE EXCEPTION 'crud_bulk: delete on % with id=% matched no row', p_collection, _delete_id;
|
|
237
|
+
END IF;
|
|
238
|
+
|
|
239
|
+
_deleted_ids := _deleted_ids || _deleted_id;
|
|
240
|
+
END LOOP;
|
|
241
|
+
END IF;
|
|
242
|
+
|
|
243
|
+
-- 7. Snake_case response — handler normalises both cases but SQL-side
|
|
244
|
+
-- consumers see idiomatic keys.
|
|
245
|
+
RETURN jsonb_build_object(
|
|
246
|
+
'inserted_ids', to_jsonb(_inserted_ids),
|
|
247
|
+
'updated_ids', to_jsonb(_updated_ids),
|
|
248
|
+
'deleted_ids', to_jsonb(_deleted_ids)
|
|
249
|
+
);
|
|
250
|
+
END;
|
|
251
|
+
$$;
|
|
252
|
+
|
|
253
|
+
-- Service-role only — edge handlers enforce auth + ACL before invoking.
|
|
254
|
+
REVOKE EXECUTE ON FUNCTION crud_bulk(TEXT, JSONB, JSONB, JSONB, JSONB) FROM PUBLIC;
|
|
255
|
+
REVOKE EXECUTE ON FUNCTION crud_bulk(TEXT, JSONB, JSONB, JSONB, JSONB) FROM anon, authenticated;
|
|
256
|
+
GRANT EXECUTE ON FUNCTION crud_bulk(TEXT, JSONB, JSONB, JSONB, JSONB) TO service_role;
|
|
257
|
+
|
|
258
|
+
COMMENT ON FUNCTION crud_bulk(TEXT, JSONB, JSONB, JSONB, JSONB) IS 'Atomic bulk CRUD for one collection; re-checks the stored status of updated rows under lock. Service-role only — edge handlers enforce auth + ACL before invoking.';
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
-- Migration: atomic rate-limit check RPC for Supabase Edge Functions
|
|
2
|
+
-- Purpose: createSupabaseHandler checks every call's rate limit through public.rate_limit_check
|
|
3
|
+
-- (packages/functions/src/supabase/utils/rateLimiter.ts, RATE_LIMIT_CHECK_SQL). Without this
|
|
4
|
+
-- function the limiter fails closed and every Edge Function call answers 429.
|
|
5
|
+
-- EXECUTE for service_role only; SECURITY DEFINER because rate_limits has RLS on and no policy.
|
|
6
|
+
|
|
7
|
+
CREATE OR REPLACE FUNCTION public.rate_limit_check(
|
|
8
|
+
p_key TEXT,
|
|
9
|
+
p_max_attempts INT,
|
|
10
|
+
p_window_ms BIGINT,
|
|
11
|
+
p_block_duration_ms BIGINT
|
|
12
|
+
)
|
|
13
|
+
RETURNS jsonb
|
|
14
|
+
LANGUAGE plpgsql
|
|
15
|
+
SECURITY DEFINER
|
|
16
|
+
SET search_path = ''
|
|
17
|
+
AS $$
|
|
18
|
+
DECLARE
|
|
19
|
+
v_now TIMESTAMPTZ := clock_timestamp();
|
|
20
|
+
v_window_interval INTERVAL := (p_window_ms || ' milliseconds')::INTERVAL;
|
|
21
|
+
v_block_interval INTERVAL := (p_block_duration_ms || ' milliseconds')::INTERVAL;
|
|
22
|
+
v_row public.rate_limits%ROWTYPE;
|
|
23
|
+
BEGIN
|
|
24
|
+
-- Single atomic upsert: INSERT on first call, conditional UPDATE thereafter (no SELECT → UPDATE race).
|
|
25
|
+
INSERT INTO public.rate_limits (key, attempts, window_start, block_until, last_updated)
|
|
26
|
+
VALUES (p_key, 1, v_now, NULL, v_now)
|
|
27
|
+
ON CONFLICT (key) DO UPDATE SET
|
|
28
|
+
window_start = CASE
|
|
29
|
+
WHEN rate_limits.window_start + v_window_interval <= v_now THEN v_now
|
|
30
|
+
ELSE rate_limits.window_start
|
|
31
|
+
END,
|
|
32
|
+
attempts = CASE
|
|
33
|
+
-- Currently blocked: do not increment (the request is rejected below)
|
|
34
|
+
WHEN rate_limits.block_until IS NOT NULL AND v_now < rate_limits.block_until
|
|
35
|
+
THEN rate_limits.attempts
|
|
36
|
+
-- Window expired: reset the counter
|
|
37
|
+
WHEN rate_limits.window_start + v_window_interval <= v_now
|
|
38
|
+
THEN 1
|
|
39
|
+
-- Within the window: increment
|
|
40
|
+
ELSE rate_limits.attempts + 1
|
|
41
|
+
END,
|
|
42
|
+
block_until = CASE
|
|
43
|
+
-- Keep an existing block
|
|
44
|
+
WHEN rate_limits.block_until IS NOT NULL AND v_now < rate_limits.block_until
|
|
45
|
+
THEN rate_limits.block_until
|
|
46
|
+
-- Window just reset: no block
|
|
47
|
+
WHEN rate_limits.window_start + v_window_interval <= v_now
|
|
48
|
+
THEN NULL
|
|
49
|
+
-- Threshold just exceeded: block
|
|
50
|
+
WHEN rate_limits.attempts + 1 >= p_max_attempts
|
|
51
|
+
THEN v_now + v_block_interval
|
|
52
|
+
ELSE NULL
|
|
53
|
+
END,
|
|
54
|
+
last_updated = v_now
|
|
55
|
+
RETURNING * INTO v_row;
|
|
56
|
+
|
|
57
|
+
IF v_row.block_until IS NOT NULL AND v_now < v_row.block_until THEN
|
|
58
|
+
RETURN jsonb_build_object(
|
|
59
|
+
'allowed', false,
|
|
60
|
+
'remaining', 0,
|
|
61
|
+
'reset_at_epoch_ms', EXTRACT(EPOCH FROM v_row.block_until)::BIGINT * 1000,
|
|
62
|
+
'block_remaining_seconds', CEIL(EXTRACT(EPOCH FROM (v_row.block_until - v_now)))::INT
|
|
63
|
+
);
|
|
64
|
+
END IF;
|
|
65
|
+
|
|
66
|
+
RETURN jsonb_build_object(
|
|
67
|
+
'allowed', true,
|
|
68
|
+
'remaining', GREATEST(0, p_max_attempts - v_row.attempts),
|
|
69
|
+
'reset_at_epoch_ms', EXTRACT(EPOCH FROM (v_row.window_start + v_window_interval))::BIGINT * 1000,
|
|
70
|
+
'block_remaining_seconds', NULL
|
|
71
|
+
);
|
|
72
|
+
END;
|
|
73
|
+
$$;
|
|
74
|
+
|
|
75
|
+
REVOKE ALL ON FUNCTION public.rate_limit_check(TEXT, INT, BIGINT, BIGINT) FROM PUBLIC, anon, authenticated;
|
|
76
|
+
GRANT EXECUTE ON FUNCTION public.rate_limit_check(TEXT, INT, BIGINT, BIGINT) TO service_role;
|
|
@@ -12,13 +12,13 @@ COMMAND=$(echo "$INPUT" | bun -e "process.stdout.write(JSON.parse(await Bun.stdi
|
|
|
12
12
|
|
|
13
13
|
# --- HARD BLOCKS (exit 2) ---
|
|
14
14
|
|
|
15
|
-
# Block raw TypeScript compiler (must use
|
|
15
|
+
# Block raw TypeScript compiler (must use dn tc)
|
|
16
16
|
if echo "$COMMAND" | grep -qE '(^|\s|;|&&|\|)(bunx|npx|pnpx)\s+tsc(\s|$)'; then
|
|
17
|
-
echo "BLOCKED: Use '
|
|
17
|
+
echo "BLOCKED: Use 'dn tc' for type-checking, never bunx/npx tsc." >&2
|
|
18
18
|
exit 2
|
|
19
19
|
fi
|
|
20
20
|
if echo "$COMMAND" | grep -qE '(^|\s|;|&&|\|)tsc(\s|$)'; then
|
|
21
|
-
echo "BLOCKED: Use '
|
|
21
|
+
echo "BLOCKED: Use 'dn tc' for type-checking, never raw tsc." >&2
|
|
22
22
|
exit 2
|
|
23
23
|
fi
|
|
24
24
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/bin/bash
|
|
2
2
|
# .claude/hooks/typecheck-stop.sh
|
|
3
|
-
# Stop hook: run
|
|
3
|
+
# Stop hook: run dn tc before declaring done.
|
|
4
4
|
# Ensures type safety before any work is considered complete.
|
|
5
5
|
|
|
6
6
|
set -euo pipefail
|
|
@@ -10,7 +10,7 @@ DIRTY=$(git status --porcelain 2>/dev/null | wc -l | tr -d ' ')
|
|
|
10
10
|
[ "$DIRTY" -eq 0 ] && exit 0
|
|
11
11
|
|
|
12
12
|
echo "Running typecheck before completion..." >&2
|
|
13
|
-
if !
|
|
13
|
+
if ! dn tc 2>&1; then
|
|
14
14
|
echo '{"decision":"block","reason":"Typecheck failed. Fix type errors before completing."}'
|
|
15
15
|
exit 0
|
|
16
16
|
fi
|
|
@@ -10,7 +10,7 @@ Every change is incomplete until ALL applicable items are done.
|
|
|
10
10
|
## Mandatory (every change)
|
|
11
11
|
|
|
12
12
|
1. **Code** - simple, follows existing patterns, robust, secure
|
|
13
|
-
2. **Typecheck** - `
|
|
13
|
+
2. **Typecheck** - `dn tc` passes
|
|
14
14
|
3. **i18n** - all user-facing strings via `t('key')`. Locale files updated.
|
|
15
15
|
|
|
16
16
|
## Mandatory for new features
|
|
@@ -30,7 +30,7 @@ Every skill output MUST end with:
|
|
|
30
30
|
```
|
|
31
31
|
## Definition of Done
|
|
32
32
|
- [x] Code: <files changed>
|
|
33
|
-
- [x] Typecheck:
|
|
33
|
+
- [x] Typecheck: dn tc - PASS
|
|
34
34
|
- [x] i18n: <locale files updated, or N/A>
|
|
35
35
|
- [x] Tests: <test file, or N/A>
|
|
36
36
|
- [x] Spec compliance: <verified, or N/A>
|
|
@@ -42,4 +42,4 @@ No `.css`, `.scss`, `.less`, `.module.css` files. No Tailwind utility classes. S
|
|
|
42
42
|
- **i18n-first.** All user-facing strings via `t('key')`. No hardcoded text.
|
|
43
43
|
- **Import order.** React, vendors, @donotdev, relative.
|
|
44
44
|
- **No fallbacks.** Fail loud. Never `|| default`.
|
|
45
|
-
- **Typecheck.** `
|
|
45
|
+
- **Typecheck.** `dn tc` only. Never `bunx tsc`, `npx tsc`, or raw `tsc`.
|