@supacloud/cli 0.129.6 → 0.130.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/dist/index.js CHANGED
@@ -30177,7 +30177,7 @@ var starter_metadata_default = {
30177
30177
  generatedBy: "supacloud/starter-metadata-v1",
30178
30178
  packages: {
30179
30179
  compiler: {
30180
- version: "0.67.3"
30180
+ version: "0.68.0"
30181
30181
  },
30182
30182
  app: {
30183
30183
  version: "0.40.1",
@@ -30186,16 +30186,16 @@ var starter_metadata_default = {
30186
30186
  }
30187
30187
  },
30188
30188
  elysia: {
30189
- version: "0.43.2"
30189
+ version: "0.44.0"
30190
30190
  },
30191
30191
  commands: {
30192
- version: "0.13.0"
30192
+ version: "0.14.0"
30193
30193
  },
30194
30194
  contracts: {
30195
30195
  version: "0.17.0"
30196
30196
  },
30197
30197
  db: {
30198
- version: "0.27.1",
30198
+ version: "0.28.0",
30199
30199
  dependencies: {},
30200
30200
  devDependencies: {},
30201
30201
  peerDependencies: {
@@ -30203,7 +30203,7 @@ var starter_metadata_default = {
30203
30203
  }
30204
30204
  },
30205
30205
  dbZenstack: {
30206
- version: "0.4.0",
30206
+ version: "0.5.0",
30207
30207
  dependencies: {
30208
30208
  "@zenstackhq/orm": "3.10.0",
30209
30209
  "@zenstackhq/schema": "3.10.0",
@@ -31391,6 +31391,9 @@ DROP POLICY IF EXISTS "model_orders_insert" ON "public"."model_orders";
31391
31391
  CREATE POLICY "model_orders_insert" ON "public"."model_orders" FOR INSERT TO "authenticated" WITH CHECK (((((((auth.jwt() IS NOT NULL) AND ((auth.jwt() ->> 'canCreate') = 'true')) AND ("tenant_id" = (auth.jwt() ->> 'tenantId'))) AND ("owner_id" = (auth.jwt() ->> 'id'))) AND ("state" = 'draft')) AND ("version" = 1)));
31392
31392
  DROP POLICY IF EXISTS "model_orders_update" ON "public"."model_orders";
31393
31393
  CREATE POLICY "model_orders_update" ON "public"."model_orders" FOR UPDATE TO "authenticated" USING ((((auth.jwt() IS NOT NULL) AND ((auth.jwt() ->> 'canApprove') = 'true')) AND ("tenant_id" = (auth.jwt() ->> 'tenantId')))) WITH CHECK ((((auth.jwt() IS NOT NULL) AND ((auth.jwt() ->> 'canApprove') = 'true')) AND ("tenant_id" = (auth.jwt() ->> 'tenantId'))));
31394
+ REVOKE UPDATE ("tenant_id") ON "public"."model_orders" FROM "authenticated";
31395
+ REVOKE UPDATE ("id") ON "public"."model_orders" FROM "authenticated";
31396
+ REVOKE UPDATE ("owner_id") ON "public"."model_orders" FROM "authenticated";
31394
31397
  GRANT USAGE ON SCHEMA public, supacloud_commands TO model_orders_app;
31395
31398
  GRANT SELECT, INSERT, UPDATE ON public.model_orders TO model_orders_app;
31396
31399
  GRANT SELECT, INSERT, UPDATE ON supacloud_commands.execution_receipts TO model_orders_app;
@@ -31739,6 +31742,10 @@ CREATE TABLE public.starter_attachment_results (
31739
31742
  );
31740
31743
  ALTER TABLE public.starter_attachments ENABLE ROW LEVEL SECURITY;
31741
31744
  ALTER TABLE public.starter_attachment_results ENABLE ROW LEVEL SECURITY;
31745
+ DROP POLICY IF EXISTS "starter_attachments_select" ON "public"."starter_attachments";
31746
+ CREATE POLICY "starter_attachments_select" ON "public"."starter_attachments" FOR SELECT TO "authenticated" USING (((auth.jwt() IS NOT NULL) AND ("owner_id" = (auth.jwt() ->> 'id'))));
31747
+ DROP POLICY IF EXISTS "starter_attachment_results_select" ON "public"."starter_attachment_results";
31748
+ CREATE POLICY "starter_attachment_results_select" ON "public"."starter_attachment_results" FOR SELECT TO "authenticated" USING (((auth.jwt() IS NOT NULL) AND EXISTS (SELECT 1 FROM "public"."starter_reviews" AS "_rel_0" WHERE ("_rel_0"."id" = "public"."starter_attachment_results"."review_id") AND ("_rel_0"."owner_id" = (auth.jwt() ->> 'id')))));
31742
31749
  `;
31743
31750
  var STARTER_ATTACHMENT_POSTGRES = `import { SupaCloudArtifactsClient } from "@supacloud/js";
31744
31751
  import type { SupabaseClient } from "@supabase/supabase-js";
@@ -32150,6 +32157,9 @@ GRANT SELECT (subject,enabled,can_approve,storage_subject) ON public.starter_mem
32150
32157
  DROP POLICY IF EXISTS starter_member_read ON public.starter_members;
32151
32158
  CREATE POLICY starter_member_read ON public.starter_members FOR SELECT TO authenticated
32152
32159
  USING (subject=COALESCE(NULLIF(auth.jwt()->>'external_sub',''),auth.jwt()->>'sub') AND storage_subject=auth.uid());
32160
+ DROP POLICY IF EXISTS starter_member_storage_fence ON public.starter_members;
32161
+ CREATE POLICY starter_member_storage_fence ON public.starter_members AS RESTRICTIVE FOR SELECT TO authenticated
32162
+ USING (subject=COALESCE(NULLIF(auth.jwt()->>'external_sub',''),auth.jwt()->>'sub') AND storage_subject=auth.uid());
32153
32163
  GRANT SELECT ON public.starter_reviews TO authenticated;
32154
32164
  DROP POLICY IF EXISTS starter_review_read ON public.starter_reviews;
32155
32165
  CREATE POLICY starter_review_read ON public.starter_reviews FOR SELECT TO authenticated
@@ -32157,6 +32167,12 @@ CREATE POLICY starter_review_read ON public.starter_reviews FOR SELECT TO authen
32157
32167
  SELECT 1 FROM public.starter_members m WHERE m.subject=owner_id
32158
32168
  AND m.enabled AND m.can_approve AND m.storage_subject=auth.uid()
32159
32169
  ));
32170
+ DROP POLICY IF EXISTS starter_review_storage_fence ON public.starter_reviews;
32171
+ CREATE POLICY starter_review_storage_fence ON public.starter_reviews AS RESTRICTIVE FOR SELECT TO authenticated
32172
+ USING (owner_id=COALESCE(NULLIF(auth.jwt()->>'external_sub',''),auth.jwt()->>'sub') AND EXISTS (
32173
+ SELECT 1 FROM public.starter_members m WHERE m.subject=owner_id
32174
+ AND m.enabled AND m.can_approve AND m.storage_subject=auth.uid()
32175
+ ));
32160
32176
  INSERT INTO storage.buckets(id,name,public,file_size_limit,allowed_mime_types)
32161
32177
  VALUES ('review-attachments','review-attachments',false,1048576,ARRAY['text/plain']);
32162
32178
  DROP POLICY IF EXISTS starter_attachment_read ON storage.objects;
@@ -32443,6 +32459,13 @@ CREATE TABLE public.starter_members (
32443
32459
  ALTER TABLE public.starter_application ENABLE ROW LEVEL SECURITY;
32444
32460
  ALTER TABLE public.starter_reviews ENABLE ROW LEVEL SECURITY;
32445
32461
  ALTER TABLE public.starter_members ENABLE ROW LEVEL SECURITY;
32462
+ DO $supacloud_policy_rls$ BEGIN IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'authenticated') THEN CREATE ROLE "authenticated" NOLOGIN; END IF; END $supacloud_policy_rls$;
32463
+ DROP POLICY IF EXISTS "starter_application_select" ON "public"."starter_application";
32464
+ CREATE POLICY "starter_application_select" ON "public"."starter_application" FOR SELECT TO "authenticated" USING ((auth.jwt() IS NOT NULL));
32465
+ DROP POLICY IF EXISTS "starter_reviews_select" ON "public"."starter_reviews";
32466
+ CREATE POLICY "starter_reviews_select" ON "public"."starter_reviews" FOR SELECT TO "authenticated" USING (((auth.jwt() IS NOT NULL) AND (("owner_id" = (auth.jwt() ->> 'id')) OR ((auth.jwt() ->> 'canApprove') = 'true'))));
32467
+ DROP POLICY IF EXISTS "starter_members_select" ON "public"."starter_members";
32468
+ CREATE POLICY "starter_members_select" ON "public"."starter_members" FOR SELECT TO "authenticated" USING (((auth.jwt() IS NOT NULL) AND ("subject" = (auth.jwt() ->> 'id'))));
32446
32469
  `;
32447
32470
  var STARTER_REVIEW_POSTGRES = `import { createTransactionalCommand, plaintextCommandInput } from "@supacloud/commands";
32448
32471
  import { CommandError } from "@supacloud/contracts";
@@ -32723,8 +32746,7 @@ var STARTER_DATABASE_CONFIG = {
32723
32746
  consumers: ["src", "scripts", "tests"],
32724
32747
  auditConsumers: [],
32725
32748
  trustedHosts: ["src/host", "src/delivery-host.ts", "src/delivery-worker.ts"],
32726
- role: "starter_review_http",
32727
- policyRls: "deferred"
32749
+ role: "starter_review_http"
32728
32750
  };
32729
32751
  var STARTER_DATABASE_MODEL = `datasource db {
32730
32752
  provider = "postgresql"
@@ -32836,16 +32858,56 @@ export default defineDatabaseModule({
32836
32858
  name, table, operation, roles: [...roles], source: "migrations/004-review-runtime-roles.sql",
32837
32859
  tests: ["tests/database-governance.sql"],
32838
32860
  })),
32861
+ {
32862
+ name: "starter_application_select", table: "public.starter_application", operation: "select",
32863
+ roles: ["authenticated"], source: "migrations/001-review.sql",
32864
+ tests: ["tests/database-governance.sql"],
32865
+ },
32866
+ {
32867
+ name: "starter_reviews_select", table: "public.starter_reviews", operation: "select",
32868
+ roles: ["authenticated"], source: "migrations/001-review.sql",
32869
+ tests: ["tests/database-governance.sql"],
32870
+ },
32871
+ {
32872
+ name: "starter_members_select", table: "public.starter_members", operation: "select",
32873
+ roles: ["authenticated"], source: "migrations/001-review.sql",
32874
+ tests: ["tests/database-governance.sql"],
32875
+ },
32876
+ {
32877
+ name: "starter_attachments_select", table: "public.starter_attachments", operation: "select",
32878
+ roles: ["authenticated"], source: "migrations/002-review-attachments.sql",
32879
+ tests: ["tests/database-governance.sql"],
32880
+ },
32881
+ {
32882
+ name: "starter_attachment_results_select", table: "public.starter_attachment_results", operation: "select",
32883
+ roles: ["authenticated"], source: "migrations/002-review-attachments.sql",
32884
+ tests: ["tests/database-governance.sql"],
32885
+ },
32886
+ {
32887
+ name: "starter_attachment_retries_select", table: "public.starter_attachment_retries", operation: "select",
32888
+ roles: ["authenticated"], source: "migrations/005-review-task-recovery.sql",
32889
+ tests: ["tests/database-governance.sql"],
32890
+ },
32839
32891
  {
32840
32892
  name: "starter_member_read", table: "public.starter_members", operation: "select",
32841
32893
  roles: ["authenticated"], source: "migrations/003-review-uploads.sql",
32842
32894
  tests: ["tests/database-governance.sql"],
32843
32895
  },
32896
+ {
32897
+ name: "starter_member_storage_fence", table: "public.starter_members", operation: "select",
32898
+ roles: ["authenticated"], source: "migrations/003-review-uploads.sql",
32899
+ tests: ["tests/database-governance.sql"],
32900
+ },
32844
32901
  {
32845
32902
  name: "starter_review_read", table: "public.starter_reviews", operation: "select",
32846
32903
  roles: ["authenticated"], source: "migrations/003-review-uploads.sql",
32847
32904
  tests: ["tests/database-governance.sql"],
32848
32905
  },
32906
+ {
32907
+ name: "starter_review_storage_fence", table: "public.starter_reviews", operation: "select",
32908
+ roles: ["authenticated"], source: "migrations/003-review-uploads.sql",
32909
+ tests: ["tests/database-governance.sql"],
32910
+ },
32849
32911
  ],
32850
32912
  });
32851
32913
  `;
@@ -32862,7 +32924,7 @@ BEGIN
32862
32924
  END IF;
32863
32925
  IF (SELECT count(*) FROM pg_policy p JOIN pg_class c ON c.oid=p.polrelid
32864
32926
  JOIN pg_namespace n ON n.oid=c.relnamespace
32865
- WHERE n.nspname='public' AND c.relname=ANY(owned)) <> 20 THEN
32927
+ WHERE n.nspname='public' AND c.relname=ANY(owned)) <> 28 THEN
32866
32928
  RAISE EXCEPTION 'Starter policy inventory changed; reconcile db/modules.ts';
32867
32929
  END IF;
32868
32930
  IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname IN ('starter_review_http','starter_review_worker')
@@ -32882,11 +32944,13 @@ var STARTER_DATABASE_GUIDE = `
32882
32944
  Maintain zenstack/schema.zmodel. Run \`bun run db:generate\` to compile model and RPC
32883
32945
  contracts; commit generated types with their sources. Do not introduce any/@ts-ignore
32884
32946
  to bypass model or contract diagnostics. \`bun run db:check\` compares
32885
- fresh generation without writing files or opening a database. This starter sets
32886
- \`policyRls\` to \`deferred\` because relation predicates and storage fences are reviewed
32887
- SQL, not the authenticated row-policy projection. Command writes still use the shared
32947
+ fresh generation without writing files or opening a database. This starter projects
32948
+ ZModel row policies (including explicit \`@relation(fields, references)\` EXISTS
32949
+ predicates) into \`authenticated\` RLS statements and checks them against the
32950
+ migration ledger, while storage fences and runtime-role policies remain explicit
32951
+ reviewed migrations. Command writes still use the shared
32888
32952
  transaction, receipt and audit boundary, not unrestricted CRUD. SQL constraints, RPCs
32889
- and RLS remain explicit reviewed migrations when the model language cannot express them.
32953
+ and additional restrictive fences remain explicit reviewed migrations.
32890
32954
 
32891
32955
  Use \`bun run db:plan\` to send the reviewed migration directory to the
32892
32956
  Management API for a remote, read-only plan. Review the returned digest, then run
@@ -34039,6 +34103,8 @@ CREATE POLICY starter_http_retry_insert ON public.starter_attachment_retries
34039
34103
  DROP POLICY IF EXISTS starter_worker_retry_read ON public.starter_attachment_retries;
34040
34104
  CREATE POLICY starter_worker_retry_read ON public.starter_attachment_retries
34041
34105
  FOR SELECT TO starter_review_worker USING (true);
34106
+ DROP POLICY IF EXISTS "starter_attachment_retries_select" ON "public"."starter_attachment_retries";
34107
+ CREATE POLICY "starter_attachment_retries_select" ON "public"."starter_attachment_retries" FOR SELECT TO "authenticated" USING (((auth.jwt() IS NOT NULL) AND EXISTS (SELECT 1 FROM "public"."starter_attachments" AS "_rel_0" WHERE ("_rel_0"."review_id" = "public"."starter_attachment_retries"."review_id") AND ("_rel_0"."owner_id" = (auth.jwt() ->> 'id')))));
34042
34108
  -- Trusted HTTP adapters authorize the review before inspecting its bound run.
34043
34109
  GRANT EXECUTE ON FUNCTION supacloud_workflows.snapshot(uuid,boolean) TO starter_review_http;
34044
34110
  `;
@@ -37157,10 +37223,28 @@ export const ${prefix}Body = t.Object({});
37157
37223
  export const ${prefix}Response = t.Object({});
37158
37224
  `;
37159
37225
  }
37226
+ function aspectScaffold(moduleName, name) {
37227
+ const prefix = pascalName(name);
37228
+ return `import { defineOperationAspect } from "@supacloud/app/core";
37229
+
37230
+ /**
37231
+ * Explicit static operation aspect for ${moduleName}.${camelName(name)}.
37232
+ * Keep capabilities minimal, return the actual continuation result unchanged,
37233
+ * preserve failures, and never start another transaction or automatic write retry.
37234
+ */
37235
+ export const ${prefix}Aspect = defineOperationAspect({
37236
+ name: ${JSON.stringify(`${moduleName}.${camelName(name)}.aspect`)},
37237
+ capabilities: [],
37238
+ around(context, next) {
37239
+ return next(context);
37240
+ },
37241
+ });
37242
+ `;
37243
+ }
37160
37244
  async function generateScaffold(args) {
37161
37245
  const kind = args.kind;
37162
- if (!kind || !["module", "command", "query", "controller", "job", "contract", "resource", "feature"].includes(kind)) {
37163
- throw new ScaffoldError("SCAFFOLD_KIND_INVALID", "app generate requires --kind (module|command|query|controller|job|contract|resource|feature)");
37246
+ if (!kind || !["module", "command", "query", "controller", "job", "contract", "aspect", "resource", "feature"].includes(kind)) {
37247
+ throw new ScaffoldError("SCAFFOLD_KIND_INVALID", "app generate requires --kind (module|command|query|controller|job|contract|aspect|resource|feature)");
37164
37248
  }
37165
37249
  for (const flag of ["dry_run", "force"]) {
37166
37250
  if (args[flag] !== undefined && typeof args[flag] !== "boolean") {
@@ -37261,12 +37345,12 @@ async function generateScaffold(args) {
37261
37345
  }
37262
37346
  const targetModule = requireIdentifier(moduleName, "module");
37263
37347
  const name = kind === "controller" ? targetModule : requireIdentifier(args.name, "name");
37264
- const subdir = kind === "command" ? "commands" : kind === "query" ? "queries" : kind === "job" ? "jobs" : kind === "contract" ? "contracts" : "";
37348
+ const subdir = kind === "command" ? "commands" : kind === "query" ? "queries" : kind === "job" ? "jobs" : kind === "contract" ? "contracts" : kind === "aspect" ? "aspects" : "";
37265
37349
  const path = join15(dir, targetModule, subdir, `${name}.${kind}.ts`).replaceAll("\\", "/");
37266
37350
  if (kind === "controller" && existsSync13(scaffoldPath(root, path))) {
37267
37351
  throw new ScaffoldError("SCAFFOLD_EXISTS", `Controller already exists: ${path}(请手工合并路由到现有 controller)`);
37268
37352
  }
37269
- const content = kind === "command" ? commandScaffold(targetModule, name) : kind === "query" ? queryScaffold(targetModule, name) : kind === "job" ? jobScaffold(targetModule, name) : kind === "contract" ? contractScaffold(targetModule, name) : controllerScaffold(targetModule);
37353
+ const content = kind === "command" ? commandScaffold(targetModule, name) : kind === "query" ? queryScaffold(targetModule, name) : kind === "job" ? jobScaffold(targetModule, name) : kind === "contract" ? contractScaffold(targetModule, name) : kind === "aspect" ? aspectScaffold(targetModule, name) : controllerScaffold(targetModule);
37270
37354
  writes.push({ path, content, overwrite: args.force === true });
37271
37355
  if (kind === "contract")
37272
37356
  contractName = name;
@@ -39041,7 +39125,7 @@ function registerAppTools(server, options = {}) {
39041
39125
  "promote-status",
39042
39126
  "promote-reconcile"
39043
39127
  ]), "App action; promote obtains and verifies its plan before one mutation request"),
39044
- kind: optional(stringEnum2(["module", "command", "query", "controller", "job", "contract", "resource", "feature"]), "[generate] Scaffold kind"),
39128
+ kind: optional(stringEnum2(["module", "command", "query", "controller", "job", "contract", "aspect", "resource", "feature"]), "[generate] Scaffold kind"),
39045
39129
  template: optional(stringEnum2(["minimal", "client", "command", "model-command", "app"]), "[init] minimal (default) is the compiler/Effect stack; client is @supabase/supabase-js only; command is the native-SQL reference; model-command adds ZenStack HTTP/worker commands; app is an alias of minimal"),
39046
39130
  name: optional(String2(), "[init/generate] Project or object name"),
39047
39131
  module: optional(String2(), "[generate] Target feature module; inferred when the project has one top-level module"),
@@ -44686,7 +44770,7 @@ async function runProjectDeployment(http, args) {
44686
44770
  // package.json
44687
44771
  var package_default = {
44688
44772
  name: "@supacloud/cli",
44689
- version: "0.129.6",
44773
+ version: "0.130.0",
44690
44774
  description: "Project-scoped CLI for SupaCloud users",
44691
44775
  type: "module",
44692
44776
  main: "./dist/index.js",
@@ -44738,23 +44822,23 @@ var package_default = {
44738
44822
  directory: "packages/cli"
44739
44823
  },
44740
44824
  dependencies: {
44741
- "@supacloud/compiler": "^0.67.3",
44825
+ "@supacloud/compiler": "^0.68.0",
44742
44826
  "@supacloud/delivery": "0.30.1",
44743
- "@supacloud/db": "0.27.1",
44827
+ "@supacloud/db": "0.28.0",
44744
44828
  typebox: "1.4.3"
44745
44829
  },
44746
44830
  overrides: {
44747
44831
  "@supacloud/contracts": "0.17.0",
44748
44832
  "@supacloud/delivery": "0.30.1",
44749
44833
  "@graphql-tools/utils": "^12.0.4",
44750
- "@supacloud/compiler": "^0.67.3",
44751
- "@supacloud/db": "0.27.1",
44834
+ "@supacloud/compiler": "^0.68.0",
44835
+ "@supacloud/db": "0.28.0",
44752
44836
  "deepmerge-ts": "8.0.2",
44753
44837
  prisma: "6.19.3"
44754
44838
  },
44755
44839
  devDependencies: {
44756
44840
  "@supabase/supabase-js": "2.118.0",
44757
- "@supacloud/elysia": "0.43.2",
44841
+ "@supacloud/elysia": "0.44.0",
44758
44842
  "@types/bun": "^1.4.5",
44759
44843
  effect: "4.0.5",
44760
44844
  elysia: "2.0.0-rc.6",
@@ -1,2 +1,2 @@
1
- export declare const STARTER_ATTACHMENT_SCHEMA = "-- Apply with the migration owner, never from an application process.\nCREATE TABLE public.starter_attachments (\n review_id text PRIMARY KEY REFERENCES public.starter_reviews(id),\n artifact_id uuid NOT NULL UNIQUE, owner_id text NOT NULL, run_id uuid NOT NULL UNIQUE,\n object_path text NOT NULL UNIQUE\n);\nCREATE TABLE public.starter_attachment_results (\n review_id text NOT NULL REFERENCES public.starter_reviews(id),\n version integer NOT NULL CHECK (version >= 2), artifact_id uuid NOT NULL,\n result jsonb NOT NULL, PRIMARY KEY(review_id,version,artifact_id)\n);\nALTER TABLE public.starter_attachments ENABLE ROW LEVEL SECURITY;\nALTER TABLE public.starter_attachment_results ENABLE ROW LEVEL SECURITY;\n";
1
+ export declare const STARTER_ATTACHMENT_SCHEMA = "-- Apply with the migration owner, never from an application process.\nCREATE TABLE public.starter_attachments (\n review_id text PRIMARY KEY REFERENCES public.starter_reviews(id),\n artifact_id uuid NOT NULL UNIQUE, owner_id text NOT NULL, run_id uuid NOT NULL UNIQUE,\n object_path text NOT NULL UNIQUE\n);\nCREATE TABLE public.starter_attachment_results (\n review_id text NOT NULL REFERENCES public.starter_reviews(id),\n version integer NOT NULL CHECK (version >= 2), artifact_id uuid NOT NULL,\n result jsonb NOT NULL, PRIMARY KEY(review_id,version,artifact_id)\n);\nALTER TABLE public.starter_attachments ENABLE ROW LEVEL SECURITY;\nALTER TABLE public.starter_attachment_results ENABLE ROW LEVEL SECURITY;\nDROP POLICY IF EXISTS \"starter_attachments_select\" ON \"public\".\"starter_attachments\";\nCREATE POLICY \"starter_attachments_select\" ON \"public\".\"starter_attachments\" FOR SELECT TO \"authenticated\" USING (((auth.jwt() IS NOT NULL) AND (\"owner_id\" = (auth.jwt() ->> 'id'))));\nDROP POLICY IF EXISTS \"starter_attachment_results_select\" ON \"public\".\"starter_attachment_results\";\nCREATE POLICY \"starter_attachment_results_select\" ON \"public\".\"starter_attachment_results\" FOR SELECT TO \"authenticated\" USING (((auth.jwt() IS NOT NULL) AND EXISTS (SELECT 1 FROM \"public\".\"starter_reviews\" AS \"_rel_0\" WHERE (\"_rel_0\".\"id\" = \"public\".\"starter_attachment_results\".\"review_id\") AND (\"_rel_0\".\"owner_id\" = (auth.jwt() ->> 'id')))));\n";
2
2
  export declare const STARTER_ATTACHMENT_POSTGRES = "import { SupaCloudArtifactsClient } from \"@supacloud/js\";\nimport type { SupabaseClient } from \"@supabase/supabase-js\";\nimport type { CommandDatabase, CommandTransaction } from \"@supacloud/db\";\nimport { createSchemaDecoder } from \"@supacloud/elysia\";\nimport { AttachmentResult, type ReviewAttachmentInput, type ReviewAttachmentResult, type ReviewAttachmentStore } from \"../review/attachment\";\n\nexport interface ReviewAttachmentOptions {\n database: CommandDatabase;\n // Provision this client for the same project as the database; never use a caller's bearer token.\n service: SupabaseClient;\n projectId: string;\n tenantId: string;\n}\n\nfunction rows(value: unknown): Record<string, unknown>[] {\n if (!Array.isArray(value)) throw new TypeError(\"Invalid attachment database result\");\n return value.map(record);\n}\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\nfunction record(value: unknown): Record<string, unknown> {\n if (!isRecord(value)) throw new TypeError(\"Invalid attachment record\");\n return value;\n}\nconst durableResult = createSchemaDecoder(AttachmentResult, { normalize: false });\n\nfunction resultFor(input: ReviewAttachmentInput, value: unknown): ReviewAttachmentResult {\n const result = durableResult(value);\n if (result.reviewId !== input.reviewId || result.version !== input.version\n || result.artifactId !== input.artifactId) throw new Error(\"Conflicting durable attachment result\");\n return result;\n}\n\nexport async function createReviewAttachmentAdapters(options: ReviewAttachmentOptions): Promise<{\n store: ReviewAttachmentStore;\n enqueue(tx: CommandTransaction, reviewId: string, version: number): Promise<void>;\n}> {\n const { database, service, projectId, tenantId } = options;\n if (!projectId.trim() || !tenantId.trim()) throw new TypeError(\"Attachment project/tenant is required\");\n const artifacts = new SupaCloudArtifactsClient(service);\n const binding = rows(await database.transaction(tx => tx.query(\n \"SELECT project_id,tenant_id FROM public.starter_application WHERE singleton\",\n )));\n if (binding.length !== 1 || binding[0]?.[\"project_id\"] !== projectId || binding[0]?.[\"tenant_id\"] !== tenantId) {\n throw new Error(\"Attachment database project/tenant binding mismatch\");\n }\n async function authorize(tx: CommandTransaction, input: ReviewAttachmentInput) {\n const allowed = rows(await tx.query(\n \"SELECT a.object_path,a.run_id FROM public.starter_attachments a \" +\n \"JOIN public.starter_reviews r ON r.id=a.review_id AND r.owner_id=a.owner_id \" +\n \"JOIN public.starter_members m ON m.subject=a.owner_id AND m.enabled AND m.can_approve \" +\n \"CROSS JOIN public.starter_application p \" +\n \"WHERE a.review_id=$1 AND a.artifact_id=$2 AND r.version=$3 AND r.state='approved' \" +\n \"AND p.singleton AND p.project_id=$4 AND p.tenant_id=$5 \" +\n \"FOR UPDATE OF r,a,m FOR SHARE OF p\",\n [input.reviewId, input.artifactId, input.version, projectId, tenantId],\n ));\n if (allowed.length !== 1 || typeof allowed[0]?.[\"object_path\"] !== \"string\") {\n throw new Error(\"Attachment worker authorization or review revision is no longer valid\");\n }\n return allowed[0];\n }\n return {\n async enqueue(tx, reviewId, version) {\n const found = rows(await tx.query(\n \"SELECT artifact_id FROM public.starter_attachments WHERE review_id=$1\", [reviewId],\n ))[0];\n if (!found) return;\n const input = { reviewId, version, artifactId: String(found[\"artifact_id\"]) };\n const allowed = await authorize(tx, input);\n // Bind serialized JSON as text so drivers cannot encode the string as a JSON scalar.\n await tx.query(\"SELECT supacloud_workflows.start_run($1::uuid,$2,'1','verify',$3::text::jsonb,3)\", [\n String(allowed[\"run_id\"]), \"review.verify-attachment\", JSON.stringify(input),\n ]);\n },\n store: {\n async readResult(input) {\n return database.transaction(async tx => {\n await authorize(tx, input);\n const saved = rows(await tx.query(\n \"SELECT result FROM public.starter_attachment_results WHERE review_id=$1 AND version=$2 AND artifact_id=$3\",\n [input.reviewId, input.version, input.artifactId],\n ));\n return saved.length === 0 ? null : resultFor(input, saved[0]?.[\"result\"]);\n });\n },\n async readAttachment(input) {\n const allowed = await database.transaction(tx => authorize(tx, input));\n const artifact = await artifacts.get(input.artifactId);\n if (!artifact || artifact.bucketId !== \"review-attachments\"\n || artifact.objectPath !== allowed[\"object_path\"] || artifact.artifactType !== \"review.attachment\"\n || artifact.mimeType !== \"text/plain\" || !/^[1-9][0-9]*$/.test(artifact.sizeBytes)\n || BigInt(artifact.sizeBytes) > 1048576n) throw new Error(\"Invalid attachment artifact\");\n const downloaded = await service.storage.from(artifact.bucketId).download(artifact.objectPath);\n if (downloaded.error || !downloaded.data) throw new Error(\"Attachment download failed\");\n if (downloaded.data.size !== Number(artifact.sizeBytes)) throw new Error(\"Attachment size mismatch\");\n return { body: new Uint8Array(await downloaded.data.arrayBuffer()), sha256: artifact.sha256 };\n },\n async recordAttachment(input, result) {\n const decoded = resultFor(input, result);\n return database.transaction(async tx => {\n await authorize(tx, input);\n await tx.query(\n \"INSERT INTO public.starter_attachment_results VALUES($1,$2,$3,$4::text::jsonb) ON CONFLICT DO NOTHING\",\n [input.reviewId, input.version, input.artifactId, JSON.stringify(decoded)],\n );\n const saved = rows(await tx.query(\n \"SELECT result FROM public.starter_attachment_results WHERE review_id=$1 AND version=$2 AND artifact_id=$3\",\n [input.reviewId, input.version, input.artifactId],\n ))[0]?.[\"result\"];\n const value = resultFor(input, saved);\n if (value.sha256 !== decoded.sha256 || value.bytes !== decoded.bytes) {\n throw new Error(\"Conflicting durable attachment result\");\n }\n return value;\n });\n },\n },\n };\n}\n";
@@ -9,11 +9,10 @@ export declare const STARTER_DATABASE_CONFIG: {
9
9
  auditConsumers: never[];
10
10
  trustedHosts: string[];
11
11
  role: string;
12
- policyRls: string;
13
12
  };
14
13
  export declare const STARTER_DATABASE_MODEL = "datasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n}\nplugin policy {\n provider = \"@zenstackhq/plugin-policy\"\n}\ntype Principal {\n id String\n canApprove Boolean\n @@auth()\n}\nmodel Application {\n singleton Boolean @id @default(true)\n projectId String @map(\"project_id\")\n tenantId String @map(\"tenant_id\")\n @@map(\"starter_application\")\n @@allow(\"read\", auth() != null)\n}\nmodel Review {\n id String @id\n ownerId String @map(\"owner_id\")\n state String\n version Int\n attachment Attachment?\n results AttachmentResult[]\n @@map(\"starter_reviews\")\n @@allow(\"read\", auth() != null && (ownerId == auth().id || auth().canApprove))\n}\nmodel Member {\n subject String @id\n enabled Boolean @default(true)\n canApprove Boolean @default(false) @map(\"can_approve\")\n storageSubject String? @unique @db.Uuid @map(\"storage_subject\")\n @@map(\"starter_members\")\n @@allow(\"read\", auth() != null && subject == auth().id)\n}\nmodel Attachment {\n reviewId String @id @map(\"review_id\")\n review Review @relation(fields: [reviewId], references: [id])\n artifactId String @unique @db.Uuid @map(\"artifact_id\")\n ownerId String @map(\"owner_id\")\n runId String @unique @db.Uuid @map(\"run_id\")\n objectPath String @unique @map(\"object_path\")\n retries AttachmentRetry[]\n @@map(\"starter_attachments\")\n @@allow(\"read\", auth() != null && ownerId == auth().id)\n}\nmodel AttachmentResult {\n reviewId String @map(\"review_id\")\n review Review @relation(fields: [reviewId], references: [id])\n version Int\n artifactId String @db.Uuid @map(\"artifact_id\")\n result Json\n @@id([reviewId, version, artifactId])\n @@map(\"starter_attachment_results\")\n @@allow(\"read\", auth() != null && review.ownerId == auth().id)\n}\nmodel AttachmentRetry {\n runId String @id @db.Uuid @map(\"run_id\")\n reviewId String @map(\"review_id\")\n attachment Attachment @relation(fields: [reviewId], references: [reviewId])\n previousRunId String @unique @db.Uuid @map(\"previous_run_id\")\n generation Int\n @@unique([reviewId, generation])\n @@map(\"starter_attachment_retries\")\n @@allow(\"read\", auth() != null && attachment.ownerId == auth().id)\n}\n";
15
14
  export declare const STARTER_DATABASE_SCHEMA = "export type { Review as ReviewRow, Attachment as AttachmentRow, AttachmentRetry as AttachmentRetryRow } from \"../zenstack/generated/models\";\nimport type { Review } from \"../zenstack/generated/models\";\nexport type NewReview = Review;\n";
16
- export declare const STARTER_DATABASE_MODULES = "import { defineDatabaseModule } from \"@supacloud/db\";\n\nconst backendPolicies = [\n [\"starter_backend_binding_read\", \"public.starter_application\", \"select\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_binding_lock\", \"public.starter_application\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_binding_immutable\", \"public.starter_application\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_member_read\", \"public.starter_members\", \"select\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_member_lock\", \"public.starter_members\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_member_immutable\", \"public.starter_members\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_review_read\", \"public.starter_reviews\", \"select\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_review_update\", \"public.starter_reviews\", \"update\", [\"starter_review_http\"]],\n [\"starter_worker_review_immutable\", \"public.starter_reviews\", \"update\", [\"starter_review_worker\"]],\n [\"starter_backend_attachment_read\", \"public.starter_attachments\", \"select\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_attachment_lock\", \"public.starter_attachments\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_attachment_immutable\", \"public.starter_attachments\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_http_attachment_insert\", \"public.starter_attachments\", \"insert\", [\"starter_review_http\"]],\n [\"starter_worker_result_read\", \"public.starter_attachment_results\", \"select\", [\"starter_review_worker\"]],\n [\"starter_worker_result_insert\", \"public.starter_attachment_results\", \"insert\", [\"starter_review_worker\"]],\n] as const;\n\n// The module is the single live-Catalog ownership contract for starter tables.\nexport default defineDatabaseModule({\n name: \"starter\",\n tables: [\"public.starter_application\", \"public.starter_reviews\", \"public.starter_members\", \"public.starter_attachments\", \"public.starter_attachment_results\", \"public.starter_attachment_retries\"],\n policies: [\n ...([\n [\"starter_http_retry_read\", \"select\", \"starter_review_http\"],\n [\"starter_http_retry_insert\", \"insert\", \"starter_review_http\"],\n [\"starter_worker_retry_read\", \"select\", \"starter_review_worker\"],\n ] as const).map(([name, operation, role]) => ({\n name, table: \"public.starter_attachment_retries\", operation, roles: [role],\n source: \"migrations/005-review-task-recovery.sql\", tests: [\"tests/database-governance.sql\"],\n })),\n ...backendPolicies.map(([name, table, operation, roles]) => ({\n name, table, operation, roles: [...roles], source: \"migrations/004-review-runtime-roles.sql\",\n tests: [\"tests/database-governance.sql\"],\n })),\n {\n name: \"starter_member_read\", table: \"public.starter_members\", operation: \"select\",\n roles: [\"authenticated\"], source: \"migrations/003-review-uploads.sql\",\n tests: [\"tests/database-governance.sql\"],\n },\n {\n name: \"starter_review_read\", table: \"public.starter_reviews\", operation: \"select\",\n roles: [\"authenticated\"], source: \"migrations/003-review-uploads.sql\",\n tests: [\"tests/database-governance.sql\"],\n },\n ],\n});\n";
17
- export declare const STARTER_DATABASE_TEST = "-- Read-only catalog assertions; behavioral authorization tests remain separate.\nBEGIN READ ONLY;\nDO $test$\nDECLARE\n owned text[] := ARRAY['starter_application','starter_reviews','starter_members',\n 'starter_attachments','starter_attachment_results','starter_attachment_retries'];\nBEGIN\n IF (SELECT count(*) FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace\n WHERE n.nspname='public' AND c.relname=ANY(owned) AND c.relrowsecurity) <> 6 THEN\n RAISE EXCEPTION 'All starter tables must exist with RLS enabled';\n END IF;\n IF (SELECT count(*) FROM pg_policy p JOIN pg_class c ON c.oid=p.polrelid\n JOIN pg_namespace n ON n.oid=c.relnamespace\n WHERE n.nspname='public' AND c.relname=ANY(owned)) <> 20 THEN\n RAISE EXCEPTION 'Starter policy inventory changed; reconcile db/modules.ts';\n END IF;\n IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname IN ('starter_review_http','starter_review_worker')\n AND (rolsuper OR rolbypassrls)) THEN\n RAISE EXCEPTION 'Starter roles must not bypass row security';\n END IF;\n IF (SELECT count(*) FROM pg_roles WHERE rolname IN ('starter_review_http','starter_review_worker')) <> 2 THEN\n RAISE EXCEPTION 'Starter runtime roles are missing';\n END IF;\nEND\n$test$;\nROLLBACK;\n";
18
- export declare const STARTER_DATABASE_GUIDE = "\n## Model and migration workflow\n\nMaintain zenstack/schema.zmodel. Run `bun run db:generate` to compile model and RPC\ncontracts; commit generated types with their sources. Do not introduce any/@ts-ignore\nto bypass model or contract diagnostics. `bun run db:check` compares\nfresh generation without writing files or opening a database. This starter sets\n`policyRls` to `deferred` because relation predicates and storage fences are reviewed\nSQL, not the authenticated row-policy projection. Command writes still use the shared\ntransaction, receipt and audit boundary, not unrestricted CRUD. SQL constraints, RPCs\nand RLS remain explicit reviewed migrations when the model language cannot express them.\n\nUse `bun run db:plan` to send the reviewed migration directory to the\nManagement API for a remote, read-only plan. Review the returned digest, then run\n`bun run db:apply -- --approved_digest <digest>` to apply the exact same bytes\nthrough the project migration ledger. Neither command needs DATABASE_URL or a\npublic PostgreSQL port. Never run zen migrate deploy or db push against a managed\nproduction database.\n`bun run db:pull -- --candidate output/database-audit/schema.zmodel` uses the\nsame Management API binding and writes a review candidate only; it never\noverwrites the maintained model. Add policies before adopting introspection\noutput. Keep one migration history and preserve RLS.\n\nAdopting a database that has no model yet starts with the same command: pull\nintrospects through a temporary datasource-only model inside the Management API,\nso no hand-written ZModel is required. Review the candidate, add the policy\nplugin and @@allow rules, move it to zenstack/schema.zmodel, then run\n`bun run db:generate`. Until that file exists, `db:plan` and\n`db:generate` fail closed instead of building from an unreviewed\nintrospection result. Keep the host wiring unchanged: one\ncreateZenStackDatabase composition root supplies read-only models and the\ntransactional command store.\n";
15
+ export declare const STARTER_DATABASE_MODULES = "import { defineDatabaseModule } from \"@supacloud/db\";\n\nconst backendPolicies = [\n [\"starter_backend_binding_read\", \"public.starter_application\", \"select\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_binding_lock\", \"public.starter_application\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_binding_immutable\", \"public.starter_application\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_member_read\", \"public.starter_members\", \"select\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_member_lock\", \"public.starter_members\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_member_immutable\", \"public.starter_members\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_review_read\", \"public.starter_reviews\", \"select\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_review_update\", \"public.starter_reviews\", \"update\", [\"starter_review_http\"]],\n [\"starter_worker_review_immutable\", \"public.starter_reviews\", \"update\", [\"starter_review_worker\"]],\n [\"starter_backend_attachment_read\", \"public.starter_attachments\", \"select\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_attachment_lock\", \"public.starter_attachments\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_attachment_immutable\", \"public.starter_attachments\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_http_attachment_insert\", \"public.starter_attachments\", \"insert\", [\"starter_review_http\"]],\n [\"starter_worker_result_read\", \"public.starter_attachment_results\", \"select\", [\"starter_review_worker\"]],\n [\"starter_worker_result_insert\", \"public.starter_attachment_results\", \"insert\", [\"starter_review_worker\"]],\n] as const;\n\n// The module is the single live-Catalog ownership contract for starter tables.\nexport default defineDatabaseModule({\n name: \"starter\",\n tables: [\"public.starter_application\", \"public.starter_reviews\", \"public.starter_members\", \"public.starter_attachments\", \"public.starter_attachment_results\", \"public.starter_attachment_retries\"],\n policies: [\n ...([\n [\"starter_http_retry_read\", \"select\", \"starter_review_http\"],\n [\"starter_http_retry_insert\", \"insert\", \"starter_review_http\"],\n [\"starter_worker_retry_read\", \"select\", \"starter_review_worker\"],\n ] as const).map(([name, operation, role]) => ({\n name, table: \"public.starter_attachment_retries\", operation, roles: [role],\n source: \"migrations/005-review-task-recovery.sql\", tests: [\"tests/database-governance.sql\"],\n })),\n ...backendPolicies.map(([name, table, operation, roles]) => ({\n name, table, operation, roles: [...roles], source: \"migrations/004-review-runtime-roles.sql\",\n tests: [\"tests/database-governance.sql\"],\n })),\n {\n name: \"starter_application_select\", table: \"public.starter_application\", operation: \"select\",\n roles: [\"authenticated\"], source: \"migrations/001-review.sql\",\n tests: [\"tests/database-governance.sql\"],\n },\n {\n name: \"starter_reviews_select\", table: \"public.starter_reviews\", operation: \"select\",\n roles: [\"authenticated\"], source: \"migrations/001-review.sql\",\n tests: [\"tests/database-governance.sql\"],\n },\n {\n name: \"starter_members_select\", table: \"public.starter_members\", operation: \"select\",\n roles: [\"authenticated\"], source: \"migrations/001-review.sql\",\n tests: [\"tests/database-governance.sql\"],\n },\n {\n name: \"starter_attachments_select\", table: \"public.starter_attachments\", operation: \"select\",\n roles: [\"authenticated\"], source: \"migrations/002-review-attachments.sql\",\n tests: [\"tests/database-governance.sql\"],\n },\n {\n name: \"starter_attachment_results_select\", table: \"public.starter_attachment_results\", operation: \"select\",\n roles: [\"authenticated\"], source: \"migrations/002-review-attachments.sql\",\n tests: [\"tests/database-governance.sql\"],\n },\n {\n name: \"starter_attachment_retries_select\", table: \"public.starter_attachment_retries\", operation: \"select\",\n roles: [\"authenticated\"], source: \"migrations/005-review-task-recovery.sql\",\n tests: [\"tests/database-governance.sql\"],\n },\n {\n name: \"starter_member_read\", table: \"public.starter_members\", operation: \"select\",\n roles: [\"authenticated\"], source: \"migrations/003-review-uploads.sql\",\n tests: [\"tests/database-governance.sql\"],\n },\n {\n name: \"starter_member_storage_fence\", table: \"public.starter_members\", operation: \"select\",\n roles: [\"authenticated\"], source: \"migrations/003-review-uploads.sql\",\n tests: [\"tests/database-governance.sql\"],\n },\n {\n name: \"starter_review_read\", table: \"public.starter_reviews\", operation: \"select\",\n roles: [\"authenticated\"], source: \"migrations/003-review-uploads.sql\",\n tests: [\"tests/database-governance.sql\"],\n },\n {\n name: \"starter_review_storage_fence\", table: \"public.starter_reviews\", operation: \"select\",\n roles: [\"authenticated\"], source: \"migrations/003-review-uploads.sql\",\n tests: [\"tests/database-governance.sql\"],\n },\n ],\n});\n";
16
+ export declare const STARTER_DATABASE_TEST = "-- Read-only catalog assertions; behavioral authorization tests remain separate.\nBEGIN READ ONLY;\nDO $test$\nDECLARE\n owned text[] := ARRAY['starter_application','starter_reviews','starter_members',\n 'starter_attachments','starter_attachment_results','starter_attachment_retries'];\nBEGIN\n IF (SELECT count(*) FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace\n WHERE n.nspname='public' AND c.relname=ANY(owned) AND c.relrowsecurity) <> 6 THEN\n RAISE EXCEPTION 'All starter tables must exist with RLS enabled';\n END IF;\n IF (SELECT count(*) FROM pg_policy p JOIN pg_class c ON c.oid=p.polrelid\n JOIN pg_namespace n ON n.oid=c.relnamespace\n WHERE n.nspname='public' AND c.relname=ANY(owned)) <> 28 THEN\n RAISE EXCEPTION 'Starter policy inventory changed; reconcile db/modules.ts';\n END IF;\n IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname IN ('starter_review_http','starter_review_worker')\n AND (rolsuper OR rolbypassrls)) THEN\n RAISE EXCEPTION 'Starter roles must not bypass row security';\n END IF;\n IF (SELECT count(*) FROM pg_roles WHERE rolname IN ('starter_review_http','starter_review_worker')) <> 2 THEN\n RAISE EXCEPTION 'Starter runtime roles are missing';\n END IF;\nEND\n$test$;\nROLLBACK;\n";
17
+ export declare const STARTER_DATABASE_GUIDE = "\n## Model and migration workflow\n\nMaintain zenstack/schema.zmodel. Run `bun run db:generate` to compile model and RPC\ncontracts; commit generated types with their sources. Do not introduce any/@ts-ignore\nto bypass model or contract diagnostics. `bun run db:check` compares\nfresh generation without writing files or opening a database. This starter projects\nZModel row policies (including explicit `@relation(fields, references)` EXISTS\npredicates) into `authenticated` RLS statements and checks them against the\nmigration ledger, while storage fences and runtime-role policies remain explicit\nreviewed migrations. Command writes still use the shared\ntransaction, receipt and audit boundary, not unrestricted CRUD. SQL constraints, RPCs\nand additional restrictive fences remain explicit reviewed migrations.\n\nUse `bun run db:plan` to send the reviewed migration directory to the\nManagement API for a remote, read-only plan. Review the returned digest, then run\n`bun run db:apply -- --approved_digest <digest>` to apply the exact same bytes\nthrough the project migration ledger. Neither command needs DATABASE_URL or a\npublic PostgreSQL port. Never run zen migrate deploy or db push against a managed\nproduction database.\n`bun run db:pull -- --candidate output/database-audit/schema.zmodel` uses the\nsame Management API binding and writes a review candidate only; it never\noverwrites the maintained model. Add policies before adopting introspection\noutput. Keep one migration history and preserve RLS.\n\nAdopting a database that has no model yet starts with the same command: pull\nintrospects through a temporary datasource-only model inside the Management API,\nso no hand-written ZModel is required. Review the candidate, add the policy\nplugin and @@allow rules, move it to zenstack/schema.zmodel, then run\n`bun run db:generate`. Until that file exists, `db:plan` and\n`db:generate` fail closed instead of building from an unreviewed\nintrospection result. Keep the host wiring unchanged: one\ncreateZenStackDatabase composition root supplies read-only models and the\ntransactional command store.\n";
19
18
  export declare function starterDatabaseFiles(): Record<string, string>;
@@ -1,4 +1,4 @@
1
- export declare const STARTER_REVIEW_SCHEMA = "-- Apply with the platform migration owner, never from the HTTP process.\n-- One application database belongs to one explicitly provisioned project/tenant.\nCREATE TABLE public.starter_application (\n singleton boolean PRIMARY KEY DEFAULT true CHECK (singleton),\n project_id text NOT NULL CHECK (length(project_id) > 0),\n tenant_id text NOT NULL CHECK (length(tenant_id) > 0)\n);\nCREATE TABLE public.starter_reviews (\n id text PRIMARY KEY, owner_id text NOT NULL,\n state text NOT NULL CHECK (state IN ('draft','approved')),\n version integer NOT NULL CHECK (version > 0)\n);\nCREATE TABLE public.starter_members (\n subject text PRIMARY KEY, enabled boolean NOT NULL DEFAULT true,\n can_approve boolean NOT NULL DEFAULT false\n);\nALTER TABLE public.starter_application ENABLE ROW LEVEL SECURITY;\nALTER TABLE public.starter_reviews ENABLE ROW LEVEL SECURITY;\nALTER TABLE public.starter_members ENABLE ROW LEVEL SECURITY;\n";
1
+ export declare const STARTER_REVIEW_SCHEMA = "-- Apply with the platform migration owner, never from the HTTP process.\n-- One application database belongs to one explicitly provisioned project/tenant.\nCREATE TABLE public.starter_application (\n singleton boolean PRIMARY KEY DEFAULT true CHECK (singleton),\n project_id text NOT NULL CHECK (length(project_id) > 0),\n tenant_id text NOT NULL CHECK (length(tenant_id) > 0)\n);\nCREATE TABLE public.starter_reviews (\n id text PRIMARY KEY, owner_id text NOT NULL,\n state text NOT NULL CHECK (state IN ('draft','approved')),\n version integer NOT NULL CHECK (version > 0)\n);\nCREATE TABLE public.starter_members (\n subject text PRIMARY KEY, enabled boolean NOT NULL DEFAULT true,\n can_approve boolean NOT NULL DEFAULT false\n);\nALTER TABLE public.starter_application ENABLE ROW LEVEL SECURITY;\nALTER TABLE public.starter_reviews ENABLE ROW LEVEL SECURITY;\nALTER TABLE public.starter_members ENABLE ROW LEVEL SECURITY;\nDO $supacloud_policy_rls$ BEGIN IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'authenticated') THEN CREATE ROLE \"authenticated\" NOLOGIN; END IF; END $supacloud_policy_rls$;\nDROP POLICY IF EXISTS \"starter_application_select\" ON \"public\".\"starter_application\";\nCREATE POLICY \"starter_application_select\" ON \"public\".\"starter_application\" FOR SELECT TO \"authenticated\" USING ((auth.jwt() IS NOT NULL));\nDROP POLICY IF EXISTS \"starter_reviews_select\" ON \"public\".\"starter_reviews\";\nCREATE POLICY \"starter_reviews_select\" ON \"public\".\"starter_reviews\" FOR SELECT TO \"authenticated\" USING (((auth.jwt() IS NOT NULL) AND ((\"owner_id\" = (auth.jwt() ->> 'id')) OR ((auth.jwt() ->> 'canApprove') = 'true'))));\nDROP POLICY IF EXISTS \"starter_members_select\" ON \"public\".\"starter_members\";\nCREATE POLICY \"starter_members_select\" ON \"public\".\"starter_members\" FOR SELECT TO \"authenticated\" USING (((auth.jwt() IS NOT NULL) AND (\"subject\" = (auth.jwt() ->> 'id'))));\n";
2
2
  export declare const STARTER_REVIEW_POSTGRES = "import { createTransactionalCommand, plaintextCommandInput } from \"@supacloud/commands\";\nimport { CommandError } from \"@supacloud/contracts\";\nimport { createPostgresCommandStore, type CommandDatabase, type CommandTransaction } from \"@supacloud/db\";\nimport {\n ApplicationError, createSchemaDecoder, createSupAuthRequestContext, requireTrustedIdentity,\n createTransactionalCommandGovernance,\n type SupAuthContextOptions,\n} from \"@supacloud/elysia\";\nimport type { AppAdapters } from \"../application\";\nimport type { ReviewStore } from \"../review/review\";\nimport type { ReviewUploadPort } from \"../review/uploads\";\nimport type { ReviewTaskPort } from \"../review/tasks\";\nimport { ApprovalInput, ReviewResult } from \"../review/contracts\";\nimport type { ReviewRow } from \"../../db/schema\";\n\nconst input = createSchemaDecoder(ApprovalInput, { normalize: false });\nconst result: (value: unknown) => Pick<ReviewRow, \"state\" | \"version\"> =\n createSchemaDecoder(ReviewResult, { normalize: false });\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\nfunction record(value: unknown): Record<string, unknown> {\n if (!isRecord(value)) throw new TypeError(\"Invalid review record\");\n return value;\n}\nfunction rows(value: unknown): Record<string, unknown>[] {\n if (!Array.isArray(value)) throw new TypeError(\"Invalid database result\");\n return value.map(record);\n}\nfunction isPublicConflict(value: unknown): boolean {\n return value instanceof ApplicationError && value.status === 409\n || isRecord(value) && value[\"expose\"] === true && value[\"status\"] === 409 && typeof value[\"code\"] === \"string\";\n}\nexport interface ReviewPostgresOptions {\n database: CommandDatabase;\n tenantId: string;\n identity: Omit<SupAuthContextOptions, \"resolveAccess\">;\n uploads?: ReviewUploadPort;\n tasks?: ReviewTaskPort;\n // Only database effects here: they commit/rollback with the approval and receipt.\n afterApproved?(tx: CommandTransaction, id: string, version: number): Promise<void>;\n}\n\nexport async function createReviewPostgresAdapters(options: ReviewPostgresOptions): Promise<\n AppAdapters & { requestContext: ReturnType<typeof createSupAuthRequestContext> }\n> {\n const { database, tenantId, identity } = options;\n const projectId = identity.projectId;\n const afterApproved = options.afterApproved;\n if (!tenantId.trim()) throw new TypeError(\"Review tenantId is required\");\n const query = (text: string, parameters: readonly string[] = []) =>\n database.transaction(tx => tx.query(text, parameters));\n const binding = rows(await query(\n \"SELECT project_id,tenant_id FROM public.starter_application WHERE singleton\",\n ));\n if (binding.length !== 1 || binding[0]?.[\"project_id\"] !== projectId || binding[0]?.[\"tenant_id\"] !== tenantId) {\n throw new Error(\"Review database project/tenant binding mismatch\");\n }\n const requestContext = createSupAuthRequestContext({\n ...identity,\n async resolveAccess(who) {\n const found = rows(await query(\n \"SELECT m.can_approve FROM public.starter_members m,public.starter_application a \" +\n \"WHERE m.subject=$1 AND m.enabled AND a.singleton AND a.project_id=$2 AND a.tenant_id=$3\",\n [who.subject, projectId, tenantId],\n ));\n return found.length === 1 ? { projectId, tenantId,\n permissions: found[0]?.[\"can_approve\"] === true ? [\"review.approve\"] : [],\n } : null;\n },\n });\n const transaction = () => commandBinding.transaction();\n const store: ReviewStore = {\n ...options.uploads,\n ...options.tasks,\n async lookupOperation(context, operation) {\n const subject = actor(context);\n try {\n let confirmed: boolean = false;\n if (operation.kind === \"upload\") {\n if (!options.uploads?.lookupUpload) {\n throw new ApplicationError(\"Upload receipt lookup unavailable\", { status: 503, code: \"RECEIPTS_UNAVAILABLE\" });\n }\n confirmed = await options.uploads.lookupUpload(context, {\n reviewId: operation.reviewId, artifactId: operation.operationId, expectedVersion: operation.expectedVersion,\n });\n } else {\n const command = createTransactionalCommand({\n name: \"review.approve\", store: commandStore, inputCodec: plaintextCommandInput, input, result,\n authorize: authorizeApproval,\n execute: async () => { throw new Error(\"Receipt lookup cannot execute a command\"); },\n audit: { event: \"review.approved\", details: request => ({ reviewId: request.id }) },\n });\n const receipt = await command.lookup({ actorId: subject, tenantId }, operation.operationId,\n { id: operation.reviewId, expectedVersion: operation.expectedVersion });\n confirmed = receipt?.status === \"confirmed\";\n }\n return { status: confirmed ? \"confirmed\" : \"unknown\", operationId: operation.operationId, reviewId: operation.reviewId };\n } catch (error) {\n if (error instanceof ApplicationError) throw error;\n if (error instanceof CommandError && [\"COMMAND_REJECTED\", \"COMMAND_IDEMPOTENCY_CONFLICT\"].includes(error.code)) {\n throw new ApplicationError(error.code, { code: error.code, status: error.code === \"COMMAND_REJECTED\" ? 403 : 409 });\n }\n throw new ApplicationError(\"Receipt lookup unavailable\", { status: 503, code: \"RECEIPTS_UNAVAILABLE\" });\n }\n },\n async get(table, id) {\n if (table !== \"reviews\") throw new Error(\"Unsupported review table\");\n return rows(await transaction().query(\n \"SELECT state,version FROM public.starter_reviews WHERE id=$1 FOR UPDATE\", [id],\n ))[0];\n },\n async set(table, id, value) {\n if (table !== \"reviews\") throw new Error(\"Unsupported review table\");\n const review = result(value);\n const updated = rows(await transaction().query(\n \"UPDATE public.starter_reviews SET state=$2,version=$3 WHERE id=$1 RETURNING id\",\n [id, review.state, review.version],\n ));\n if (updated.length !== 1) throw new Error(\"Review write did not update one record\");\n await afterApproved?.(transaction(), id, review.version);\n },\n };\n function actor(context: unknown): string {\n const who = requireTrustedIdentity(context);\n const access = record(record(context)[\"access\"]);\n if (access[\"projectId\"] !== projectId || access[\"tenantId\"] !== tenantId\n || !Array.isArray(access[\"permissions\"]) || !access[\"permissions\"].includes(\"review.approve\")) {\n throw new ApplicationError(\"Command permission denied\", { status: 403, code: \"REVIEW_PERMISSION_DENIED\" });\n }\n return who.subject;\n }\n const commandStore = createPostgresCommandStore(database);\n async function authorizeApproval(who: { actorId: string; tenantId: string }, request: ReturnType<typeof input>, tx: CommandTransaction): Promise<\"allow\" | \"deny\"> {\n const found = rows(await tx.query(\n \"SELECT r.id FROM public.starter_reviews r JOIN public.starter_members m ON m.subject=r.owner_id \" +\n \"CROSS JOIN public.starter_application a \" +\n \"WHERE r.id=$1 AND r.owner_id=$2 AND m.enabled AND m.can_approve \" +\n \"AND a.singleton AND a.project_id=$3 AND a.tenant_id=$4 FOR UPDATE OF r,m FOR SHARE OF a\",\n [request.id, who.actorId, projectId, who.tenantId],\n ));\n return found.length === 1 ? \"allow\" : \"deny\";\n }\n const commandBinding = createTransactionalCommandGovernance({\n permission: \"review.approve\",\n identity: invocation => ({ actorId: actor(invocation.requestContext), tenantId }),\n input: invocation => ({\n ...record(invocation.input.body), id: invocation.input.params[\"id\"],\n }),\n rejection: error => isPublicConflict(error) ? new CommandError(\"COMMAND_IDEMPOTENCY_CONFLICT\") : undefined,\n definition: {\n name: \"review.approve\", store: commandStore,\n inputCodec: plaintextCommandInput, input, result,\n authorize: authorizeApproval,\n audit: { event: \"review.approved\", details: request => ({ reviewId: request.id }) },\n },\n });\n return { deps: { dbClient: store }, requestContext, commandGovernance: commandBinding.governance };\n}\n";
3
3
  export declare const STARTER_REVIEW_POSTGRES_TEST = "import { expect, test } from \"bun:test\";\nimport { createReviewPostgresAdapters } from \"../src/host/review-postgres\";\nimport type { ReviewStore } from \"../src/review/review\";\n\nconst identity = {\n issuer: \"https://identity.example.test\", audience: \"review-test\", clientId: \"review-client\",\n projectId: \"review-test\", jwksUrl: \"https://identity.example.test/jwks\",\n};\nfunction database(binding: unknown) {\n const queries: string[] = [];\n return {\n queries,\n async transaction<T>(run: (tx: { query(text: string): Promise<unknown> }) => Promise<T>): Promise<T> {\n return run({ async query(text) { queries.push(text); return binding; } });\n },\n };\n}\n\ntest(\"PostgreSQL host rejects missing or mismatched application ownership without creating data\", async () => {\n for (const binding of [[], [{ project_id: \"other\", tenant_id: \"review-test\" }],\n [{ project_id: \"review-test\", tenant_id: \"other\" }]]) {\n const db = database(binding);\n await expect(createReviewPostgresAdapters({ database: db, identity, tenantId: \"review-test\" }))\n .rejects.toThrow(\"binding mismatch\");\n expect(db.queries).toEqual([\"SELECT project_id,tenant_id FROM public.starter_application WHERE singleton\"]);\n }\n});\n\ntest(\"PostgreSQL host never falls back to demo identity or unbound business storage\", async () => {\n const db = database([{ project_id: \"review-test\", tenant_id: \"review-test\" }]);\n const adapters = await createReviewPostgresAdapters({ database: db, identity, tenantId: \"review-test\" });\n await expect(adapters.requestContext(new Request(\"http://localhost/reviews/health\")))\n .rejects.toMatchObject({ code: \"AUTHENTICATION_REQUIRED\" });\n const store = adapters.deps[\"dbClient\"] as ReviewStore;\n await expect(store.get(\"reviews\", \"example\")).rejects.toThrow(\"not active\");\n await expect(store.set(\"reviews\", \"example\", { state: \"approved\", version: 2 }))\n .rejects.toThrow(\"not active\");\n expect(db.queries).toHaveLength(1);\n});\n";
4
4
  export declare const STARTER_REVIEW_DELIVERY_HOST = "\nimport { createClient } from \"@supabase/supabase-js\";\nimport { createBunCommandDatabase, createBunSqlHost } from \"@supacloud/db/bun\";\nimport { createApplication, type CompiledModule } from \"@supacloud/elysia\";\nimport { createReviewPostgresAdapters } from \"./host/review-postgres\";\nimport { createReviewAttachmentAdapters } from \"./host/review-attachments\";\nimport { createReviewUploadAdapters } from \"./host/review-uploads\";\nimport { createReviewTaskAdapters } from \"./host/review-tasks\";\nimport { createReviewHttpObserver } from \"./host/review-execution-observability\";\n\nfunction required(name: string): string {\n const value = process.env[name];\n if (!value?.trim()) throw new Error(\"Missing required host setting: \" + name);\n return value;\n}\n\nexport async function createDeliveryApplication(modules: CompiledModule[], lifecycle: { signal: AbortSignal }) {\n lifecycle.signal.throwIfAborted();\n const attachments = process.env[\"REVIEW_ATTACHMENTS\"];\n if (attachments !== undefined && attachments !== \"enabled\") throw new Error(\"Invalid attachment configuration\");\n const settings = {\n tenantId: required(\"APP_TENANT_ID\"),\n identity: {\n issuer: required(\"SUPAUTH_ISSUER\"), audience: required(\"SUPAUTH_AUDIENCE\"),\n clientId: required(\"SUPAUTH_CLIENT_ID\"), projectId: required(\"SUPACLOUD_PROJECT_ID\"),\n jwksUrl: required(\"SUPAUTH_JWKS_URL\"),\n },\n };\n const host = createBunSqlHost({ max: 12, connectionTimeout: 5 });\n const pool = host.pool;\n let closing: Promise<void> | undefined;\n const close = () => closing ??= host.close();\n let stage: \"attachments\" | \"uploads\" | \"postgres\" | \"application\" = \"attachments\";\n try {\n const database = createBunCommandDatabase(pool);\n const attachmentOptions = attachments === \"enabled\" ? {\n database, tenantId: settings.tenantId, projectId: settings.identity.projectId,\n service: createClient(required(\"SUPACLOUD_URL\"), required(\"SUPACLOUD_SERVICE_ROLE_KEY\"), {\n auth: { persistSession: false, autoRefreshToken: false, detectSessionInUrl: false },\n }),\n } : undefined;\n const durable = attachmentOptions ? await createReviewAttachmentAdapters(attachmentOptions) : undefined;\n stage = \"uploads\";\n const uploads = attachmentOptions ? await createReviewUploadAdapters(attachmentOptions) : undefined;\n const tasks = attachmentOptions ? await createReviewTaskAdapters(attachmentOptions) : undefined;\n stage = \"postgres\";\n const adapters = await createReviewPostgresAdapters({\n database, tenantId: settings.tenantId, identity: settings.identity,\n ...(uploads ? { uploads } : {}),\n ...(tasks ? { tasks } : {}),\n ...(durable ? { afterApproved: durable.enqueue } : {}),\n });\n lifecycle.signal.throwIfAborted();\n stage = \"application\";\n const app = createApplication({ name: \"review\", modules, ...adapters, onExecution: createReviewHttpObserver() });\n return { fetch: (request: Request) => app.handle(request), close };\n } catch (error) {\n await close();\n const code = error !== null && typeof error === \"object\" && \"code\" in error\n && typeof error.code === \"string\" && /^[A-Z0-9_]{1,64}$/.test(error.code) ? error.code : \"UNKNOWN\";\n console.error(JSON.stringify({ event: \"review-host-initialization-failed\", stage, code }));\n // Database/identity errors can contain connection details; never echo the underlying cause.\n throw new Error(\"Review host initialization failed\");\n }\n}\n";
@@ -1,4 +1,4 @@
1
1
  export declare const STARTER_TASK_CONTRACTS = "import { t, type UnwrapSchema } from \"elysia\";\nimport { AttachmentResult } from \"./attachment\";\nimport { REVIEW_VERSION_MAX } from \"./limits\";\nimport { ReviewVersion } from \"./contracts\";\n\nexport const TaskParams = t.Object({ id: t.String({ minLength: 1, maxLength: 100 }) }, { additionalProperties: false });\nexport const RetryBody = t.Object({\n expectedVersion: t.Integer({ minimum: 2, maximum: REVIEW_VERSION_MAX }),\n expectedRunId: t.String({ format: \"uuid\" }),\n recoveryId: t.String({ format: \"uuid\" }),\n}, { additionalProperties: false });\nexport const RetryInput = t.Object({\n reviewId: TaskParams.properties.id, ...RetryBody.properties,\n}, { additionalProperties: false });\nexport const TaskStatus = t.Object({\n reviewId: TaskParams.properties.id,\n version: ReviewVersion,\n artifactId: t.Nullable(t.String({ format: \"uuid\" })),\n runId: t.Nullable(t.String({ format: \"uuid\" })),\n state: t.Union([t.Literal(\"not_submitted\"), t.Literal(\"queued\"), t.Literal(\"running\"),\n t.Literal(\"completed\"), t.Literal(\"failed\"), t.Literal(\"cancelled\")]),\n attempts: t.Integer({ minimum: 0 }),\n maxAttempts: t.Literal(3),\n canRetry: t.Boolean(),\n result: t.Nullable(AttachmentResult),\n}, { additionalProperties: false });\nexport const RetryResult = t.Object({\n reviewId: TaskParams.properties.id,\n previousRunId: t.String({ format: \"uuid\" }),\n runId: t.String({ format: \"uuid\" }),\n state: t.Literal(\"queued\"),\n}, { additionalProperties: false });\nexport type ReviewTaskStatus = UnwrapSchema<typeof TaskStatus>;\nexport type ReviewRetryBody = UnwrapSchema<typeof RetryBody>;\nexport type ReviewRetryInput = UnwrapSchema<typeof RetryInput>;\nexport type ReviewRetryResult = UnwrapSchema<typeof RetryResult>;\n";
2
2
  export declare const STARTER_TASK_FEATURE = "import { Effect } from \"effect\";\nimport { Body, Controller, DB_CLIENT, Get, Inject, Injectable, Param, Post, REQUEST_CONTEXT } from \"@supacloud/app\";\nimport { ApplicationError } from \"@supacloud/elysia\";\nimport { RetryBody, RetryResult, TaskParams, TaskStatus,\n type ReviewRetryBody, type ReviewRetryInput, type ReviewRetryResult, type ReviewTaskStatus } from \"./task-contracts\";\n\nexport interface ReviewTaskPort {\n attachmentTask(context: unknown, reviewId: string): Promise<ReviewTaskStatus>;\n retryAttachmentTask(context: unknown, input: ReviewRetryInput): Promise<ReviewRetryResult>;\n}\ntype TaskError =\n | { readonly _tag: \"AUTHENTICATION_REQUIRED\" }\n | { readonly _tag: \"TASK_INPUT_INVALID\" }\n | { readonly _tag: \"TASK_DENIED\" }\n | { readonly _tag: \"TASK_CONFLICT\" }\n | { readonly _tag: \"TASK_UNAVAILABLE\" }\n | { readonly _tag: \"TASK_OUTCOME_UNKNOWN\" };\n\n@Injectable({ scope: \"request\" })\nexport class ReviewTasks {\n constructor(@Inject(DB_CLIENT) private readonly store: Partial<ReviewTaskPort>,\n @Inject(REQUEST_CONTEXT) private readonly context: unknown) {}\n\n status(id: string): Promise<ReviewTaskStatus> {\n if (!this.store.attachmentTask) throw new ApplicationError(\"Attachment tasks are not configured\", { status: 501, code: \"TASK_UNAVAILABLE\" });\n return this.store.attachmentTask(this.context, id);\n }\n retry(input: ReviewRetryInput): Promise<ReviewRetryResult> {\n if (!this.store.retryAttachmentTask) throw new ApplicationError(\"Attachment tasks are not configured\", { status: 501, code: \"TASK_UNAVAILABLE\" });\n return this.store.retryAttachmentTask(this.context, input);\n }\n}\n\n@Controller(\"/reviews\")\nexport class ReviewTasksController {\n constructor(@Inject(ReviewTasks) private readonly tasks: ReviewTasks) {}\n\n @Get(\"/:id/attachment-task\", {\n params: TaskParams, responses: { 200: TaskStatus },\n effect: { required: true, dependencies: [], retry: \"none\", errors: [\n { tag: \"AUTHENTICATION_REQUIRED\", status: 401, code: \"AUTHENTICATION_REQUIRED\" },\n { tag: \"TASK_INPUT_INVALID\", status: 400, code: \"TASK_INPUT_INVALID\" },\n { tag: \"TASK_DENIED\", status: 403, code: \"TASK_DENIED\" },\n { tag: \"TASK_CONFLICT\", status: 409, code: \"TASK_CONFLICT\" },\n { tag: \"TASK_UNAVAILABLE\", status: 501, code: \"TASK_UNAVAILABLE\" },\n { tag: \"TASK_OUTCOME_UNKNOWN\", status: 503, code: \"TASK_OUTCOME_UNKNOWN\" },\n ] },\n })\n status(@Param(\"id\") id: string): Effect.Effect<ReviewTaskStatus, TaskError, never> {\n return Effect.promise(() => this.tasks.status(id));\n }\n\n @Post(\"/:id/attachment-task/retry\", {\n params: TaskParams, body: RetryBody, responses: { 200: RetryResult },\n effect: { required: true, dependencies: [], retry: \"none\", errors: [\n { tag: \"AUTHENTICATION_REQUIRED\", status: 401, code: \"AUTHENTICATION_REQUIRED\" },\n { tag: \"TASK_INPUT_INVALID\", status: 400, code: \"TASK_INPUT_INVALID\" },\n { tag: \"TASK_DENIED\", status: 403, code: \"TASK_DENIED\" },\n { tag: \"TASK_CONFLICT\", status: 409, code: \"TASK_CONFLICT\" },\n { tag: \"TASK_UNAVAILABLE\", status: 501, code: \"TASK_UNAVAILABLE\" },\n { tag: \"TASK_OUTCOME_UNKNOWN\", status: 503, code: \"TASK_OUTCOME_UNKNOWN\" },\n ] },\n })\n retry(@Param(\"id\") id: string, @Body() body: ReviewRetryBody): Effect.Effect<ReviewRetryResult, TaskError, never> {\n return Effect.promise(() => this.tasks.retry({ ...body, reviewId: id }));\n }\n}\n";
3
- export declare const STARTER_TASK_SCHEMA = "-- Forward-only operator provisioning after 004 and the platform Workflow runtime.\nCREATE TABLE public.starter_attachment_retries (\n run_id uuid PRIMARY KEY,\n review_id text NOT NULL REFERENCES public.starter_attachments(review_id),\n previous_run_id uuid NOT NULL UNIQUE,\n generation integer NOT NULL CHECK (generation > 0),\n UNIQUE(review_id,generation),\n CHECK (run_id <> previous_run_id)\n);\nALTER TABLE public.starter_attachment_retries ENABLE ROW LEVEL SECURITY;\nREVOKE ALL ON public.starter_attachment_retries FROM PUBLIC, anon, authenticated;\nGRANT SELECT,INSERT ON public.starter_attachment_retries TO starter_review_http;\nGRANT SELECT ON public.starter_attachment_retries TO starter_review_worker;\nDROP POLICY IF EXISTS starter_http_retry_read ON public.starter_attachment_retries;\nCREATE POLICY starter_http_retry_read ON public.starter_attachment_retries\n FOR SELECT TO starter_review_http USING (true);\nDROP POLICY IF EXISTS starter_http_retry_insert ON public.starter_attachment_retries;\nCREATE POLICY starter_http_retry_insert ON public.starter_attachment_retries\n FOR INSERT TO starter_review_http WITH CHECK (true);\nDROP POLICY IF EXISTS starter_worker_retry_read ON public.starter_attachment_retries;\nCREATE POLICY starter_worker_retry_read ON public.starter_attachment_retries\n FOR SELECT TO starter_review_worker USING (true);\n-- Trusted HTTP adapters authorize the review before inspecting its bound run.\nGRANT EXECUTE ON FUNCTION supacloud_workflows.snapshot(uuid,boolean) TO starter_review_http;\n";
3
+ export declare const STARTER_TASK_SCHEMA = "-- Forward-only operator provisioning after 004 and the platform Workflow runtime.\nCREATE TABLE public.starter_attachment_retries (\n run_id uuid PRIMARY KEY,\n review_id text NOT NULL REFERENCES public.starter_attachments(review_id),\n previous_run_id uuid NOT NULL UNIQUE,\n generation integer NOT NULL CHECK (generation > 0),\n UNIQUE(review_id,generation),\n CHECK (run_id <> previous_run_id)\n);\nALTER TABLE public.starter_attachment_retries ENABLE ROW LEVEL SECURITY;\nREVOKE ALL ON public.starter_attachment_retries FROM PUBLIC, anon, authenticated;\nGRANT SELECT,INSERT ON public.starter_attachment_retries TO starter_review_http;\nGRANT SELECT ON public.starter_attachment_retries TO starter_review_worker;\nDROP POLICY IF EXISTS starter_http_retry_read ON public.starter_attachment_retries;\nCREATE POLICY starter_http_retry_read ON public.starter_attachment_retries\n FOR SELECT TO starter_review_http USING (true);\nDROP POLICY IF EXISTS starter_http_retry_insert ON public.starter_attachment_retries;\nCREATE POLICY starter_http_retry_insert ON public.starter_attachment_retries\n FOR INSERT TO starter_review_http WITH CHECK (true);\nDROP POLICY IF EXISTS starter_worker_retry_read ON public.starter_attachment_retries;\nCREATE POLICY starter_worker_retry_read ON public.starter_attachment_retries\n FOR SELECT TO starter_review_worker USING (true);\nDROP POLICY IF EXISTS \"starter_attachment_retries_select\" ON \"public\".\"starter_attachment_retries\";\nCREATE POLICY \"starter_attachment_retries_select\" ON \"public\".\"starter_attachment_retries\" FOR SELECT TO \"authenticated\" USING (((auth.jwt() IS NOT NULL) AND EXISTS (SELECT 1 FROM \"public\".\"starter_attachments\" AS \"_rel_0\" WHERE (\"_rel_0\".\"review_id\" = \"public\".\"starter_attachment_retries\".\"review_id\") AND (\"_rel_0\".\"owner_id\" = (auth.jwt() ->> 'id')))));\n-- Trusted HTTP adapters authorize the review before inspecting its bound run.\nGRANT EXECUTE ON FUNCTION supacloud_workflows.snapshot(uuid,boolean) TO starter_review_http;\n";
4
4
  export declare const STARTER_TASK_HOST = "import { t } from \"elysia\";\nimport { createTransactionalCommand, plaintextCommandInput } from \"@supacloud/commands\";\nimport { CommandError } from \"@supacloud/contracts\";\nimport { createPostgresCommandStore, type CommandDatabase, type CommandTransaction } from \"@supacloud/db\";\nimport { ApplicationError, createSchemaDecoder, requireTrustedIdentity } from \"@supacloud/elysia\";\nimport { AttachmentInput, AttachmentResult } from \"../review/attachment\";\nimport { ReviewResult } from \"../review/contracts\";\nimport { RetryInput, RetryResult, TaskParams, TaskStatus, type ReviewRetryInput } from \"../review/task-contracts\";\nimport type { ReviewTaskPort } from \"../review/tasks\";\nimport type { ReviewRow } from \"../../db/schema\";\n\nexport interface ReviewTaskOptions { database: CommandDatabase; projectId: string; tenantId: string }\ntype Binding = { artifactId: string; runId: string; generation: number };\nconst decodeInput = createSchemaDecoder(RetryInput, { normalize: false });\nconst decodeRetry = createSchemaDecoder(RetryResult, { normalize: false });\nconst decodeStatus = createSchemaDecoder(TaskStatus, { normalize: false });\nconst decodeParams = createSchemaDecoder(TaskParams, { normalize: false });\nconst decodeReview: (value: unknown) => Pick<ReviewRow, \"state\" | \"version\"> =\n createSchemaDecoder(ReviewResult, { normalize: false });\nconst decodeResult = createSchemaDecoder(AttachmentResult, { normalize: false });\nconst decodeBinding: (value: unknown) => Binding = createSchemaDecoder(t.Object({\n artifactId: t.String({ format: \"uuid\" }), runId: t.String({ format: \"uuid\" }),\n generation: t.Integer({ minimum: 0 }),\n}), { normalize: false });\nconst decodeRun = createSchemaDecoder(t.Object({\n runId: t.String({ format: \"uuid\" }), workflowName: t.Literal(\"review.verify-attachment\"),\n workflowVersion: t.Literal(\"1\"),\n status: t.Union([t.Literal(\"queued\"), t.Literal(\"running\"), t.Literal(\"completed\"), t.Literal(\"failed\"), t.Literal(\"cancelled\")]),\n input: AttachmentInput, output: t.Unknown(), idempotent: t.Boolean(),\n steps: t.Array(t.Object({\n stepKey: t.Literal(\"verify\"), attempts: t.Integer({ minimum: 0 }),\n maxAttempts: t.Literal(3),\n status: t.Union([t.Literal(\"queued\"), t.Literal(\"running\"), t.Literal(\"completed\"), t.Literal(\"failed\"), t.Literal(\"dead_lettered\"), t.Literal(\"cancelled\")]),\n }, { additionalProperties: true }), { minItems: 1, maxItems: 1 }),\n}, { additionalProperties: true }), { normalize: false });\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\nfunction record(value: unknown): Record<string, unknown> {\n if (!isRecord(value)) throw new Error(\"Invalid task record\");\n return value;\n}\nfunction rows(value: unknown): Record<string, unknown>[] {\n if (!Array.isArray(value)) throw new Error(\"Invalid task rows\");\n return value.map(record);\n}\nfunction capture(value: unknown): ReviewRetryInput {\n try {\n const input = decodeInput(value);\n return { ...input, recoveryId: input.recoveryId.toLowerCase(), expectedRunId: input.expectedRunId.toLowerCase() };\n } catch { throw new ApplicationError(\"Invalid task request\", { status: 400, code: \"TASK_INPUT_INVALID\" }); }\n}\nfunction failure(error: unknown): never {\n if (error instanceof ApplicationError) throw error;\n if (error instanceof CommandError && error.code === \"COMMAND_REJECTED\") {\n throw new ApplicationError(\"Task access denied\", { status: 403, code: \"TASK_DENIED\" });\n }\n if (error instanceof CommandError && error.code === \"COMMAND_IDEMPOTENCY_CONFLICT\") {\n throw new ApplicationError(\"Task changed or is not retryable\", { status: 409, code: \"TASK_CONFLICT\" });\n }\n throw new ApplicationError(\"Task outcome could not be confirmed\", { status: 503, code: \"TASK_OUTCOME_UNKNOWN\" });\n}\nconst conflict = () => { throw new CommandError(\"COMMAND_IDEMPOTENCY_CONFLICT\"); };\n\nexport async function createReviewTaskAdapters(options: ReviewTaskOptions): Promise<ReviewTaskPort> {\n const { database, projectId, tenantId } = options;\n const configured = rows(await database.transaction(tx => tx.query(\n \"SELECT project_id,tenant_id FROM public.starter_application WHERE singleton\",\n )));\n if (!projectId.trim() || !tenantId.trim() || configured.length !== 1\n || configured[0]?.[\"project_id\"] !== projectId || configured[0]?.[\"tenant_id\"] !== tenantId) {\n throw new Error(\"Task database project/tenant binding mismatch\");\n }\n function actor(context: unknown): string {\n const who = requireTrustedIdentity(context);\n const access = record(record(context)[\"access\"]);\n if (access[\"projectId\"] !== projectId || access[\"tenantId\"] !== tenantId\n || !Array.isArray(access[\"permissions\"]) || !access[\"permissions\"].includes(\"review.approve\")) {\n throw new ApplicationError(\"Task access denied\", { status: 403, code: \"TASK_DENIED\" });\n }\n return who.subject;\n }\n async function authorize(tx: CommandTransaction, subject: string, reviewId: string) {\n const found = rows(await tx.query(\n \"SELECT r.state,r.version FROM public.starter_reviews r \" +\n \"JOIN public.starter_members m ON m.subject=r.owner_id CROSS JOIN public.starter_application p \" +\n \"WHERE r.id=$1 AND r.owner_id=$2 AND m.enabled AND m.can_approve \" +\n \"AND p.singleton AND p.project_id=$3 AND p.tenant_id=$4 FOR UPDATE OF r,m FOR SHARE OF p\",\n [reviewId, subject, projectId, tenantId],\n ));\n if (found.length !== 1) throw new ApplicationError(\"Task access denied\", { status: 403, code: \"TASK_DENIED\" });\n return decodeReview(found[0]);\n }\n async function binding(tx: CommandTransaction, reviewId: string) {\n const found = rows(await tx.query(\n 'SELECT a.artifact_id AS \"artifactId\",COALESCE(retry.run_id,a.run_id) AS \"runId\",COALESCE(retry.generation,0) AS generation ' +\n \"FROM public.starter_attachments a LEFT JOIN LATERAL (\" +\n \"SELECT run_id,generation FROM public.starter_attachment_retries WHERE review_id=a.review_id ORDER BY generation DESC LIMIT 1\" +\n \") retry ON true WHERE a.review_id=$1\", [reviewId],\n ));\n return found.length === 0 ? null : decodeBinding(found[0]);\n }\n async function snapshot(tx: CommandTransaction, runId: string) {\n return rows(await tx.query(\"SELECT supacloud_workflows.snapshot($1::uuid,false) AS run\", [runId]))[0]?.[\"run\"];\n }\n function boundRun(value: unknown, reviewId: string, version: number, bound: NonNullable<Awaited<ReturnType<typeof binding>>>) {\n const run = decodeRun(value);\n if (run.runId !== bound.runId || run.input.reviewId !== reviewId\n || run.input.version !== version || run.input.artifactId !== bound.artifactId) {\n throw new Error(\"Task Workflow binding mismatch\");\n }\n const step = run.steps[0];\n if (!step || (run.status === \"queued\" && step.status !== \"queued\")\n || (run.status === \"running\" && step.status !== \"queued\" && step.status !== \"running\")\n || (run.status === \"completed\" && step.status !== \"completed\")\n || (run.status === \"failed\" && step.status !== \"failed\" && step.status !== \"dead_lettered\")\n || (run.status === \"cancelled\" && step.status !== \"cancelled\")) {\n throw new Error(\"Task Workflow state mismatch\");\n }\n return run;\n }\n const retry = createTransactionalCommand({\n name: \"review.retry-attachment\", store: createPostgresCommandStore(database),\n inputCodec: plaintextCommandInput, input: capture, result: decodeRetry,\n async authorize(who, input, tx) {\n try {\n const review = await authorize(tx, who.actorId, input.reviewId);\n return review.state === \"approved\" && review.version === input.expectedVersion ? \"allow\" : \"deny\";\n } catch (error) {\n if (error instanceof ApplicationError && error.code === \"TASK_DENIED\") return \"deny\";\n throw error;\n }\n },\n async execute(tx, input) {\n const bound = await binding(tx, input.reviewId);\n if (!bound || bound.runId !== input.expectedRunId || input.recoveryId === bound.runId) return conflict();\n const previous = boundRun(await snapshot(tx, bound.runId), input.reviewId, input.expectedVersion, bound);\n if (previous.status !== \"failed\") return conflict();\n if (await snapshot(tx, input.recoveryId) !== null) return conflict();\n const started = rows(await tx.query(\n \"SELECT supacloud_workflows.start_run($1::uuid,'review.verify-attachment','1','verify',$2::text::jsonb,3) AS run\",\n [input.recoveryId, JSON.stringify(previous.input)],\n ))[0]?.[\"run\"];\n const next = boundRun(started, input.reviewId, input.expectedVersion, { ...bound, runId: input.recoveryId });\n if (next.idempotent || next.status !== \"queued\") return conflict();\n await tx.query(\"INSERT INTO public.starter_attachment_retries(run_id,review_id,previous_run_id,generation) VALUES($1,$2,$3,$4)\",\n [input.recoveryId, input.reviewId, bound.runId, bound.generation + 1]);\n return { reviewId: input.reviewId, previousRunId: bound.runId, runId: input.recoveryId, state: \"queued\" as const };\n },\n audit: { event: \"review.attachment-retried\", details: input => ({\n reviewId: input.reviewId, previousRunId: input.expectedRunId, runId: input.recoveryId,\n }) },\n });\n return {\n async attachmentTask(context, reviewId) {\n try {\n const subject = actor(context);\n try { decodeParams({ id: reviewId }); }\n catch { throw new ApplicationError(\"Invalid task request\", { status: 400, code: \"TASK_INPUT_INVALID\" }); }\n return await database.transaction(async tx => {\n const review = await authorize(tx, subject, reviewId);\n const bound = await binding(tx, reviewId);\n const empty = { reviewId, version: review.version, artifactId: bound?.artifactId ?? null,\n runId: null, state: \"not_submitted\", attempts: 0, maxAttempts: 3, canRetry: false, result: null } as const;\n if (!bound) return decodeStatus(empty);\n const value = await snapshot(tx, bound.runId);\n if (value === null && review.state === \"draft\" && bound.generation === 0) return decodeStatus(empty);\n const run = boundRun(value, reviewId, review.version, bound);\n const step = run.steps[0];\n if (!step) throw new Error(\"Missing task step\");\n const result = run.status === \"completed\" ? decodeResult(run.output) : null;\n if (result && (result.reviewId !== reviewId || result.version !== review.version || result.artifactId !== bound.artifactId)) {\n throw new Error(\"Task result binding mismatch\");\n }\n return decodeStatus({ ...empty, runId: run.runId,\n state: run.status === \"running\" && step.status === \"queued\" ? \"queued\" : run.status,\n attempts: step.attempts, canRetry: run.status === \"failed\", result });\n });\n } catch (error) { return failure(error); }\n },\n async retryAttachmentTask(context, value) {\n try {\n const subject = actor(context), input = capture(value);\n const receipt = await retry.execute({ actorId: subject, tenantId }, input.recoveryId, input);\n if (receipt.status !== \"confirmed\") throw new CommandError(\"COMMAND_OUTCOME_UNKNOWN\");\n return receipt.result;\n } catch (error) { return failure(error); }\n },\n };\n}\n";
@@ -1,3 +1,3 @@
1
1
  export declare const STARTER_UPLOAD_FEATURE = "import { Effect } from \"effect\";\nimport { Body, Controller, Inject, Injectable, Param, Post, DB_CLIENT, REQUEST_CONTEXT } from \"@supacloud/app\";\nimport { ApplicationError } from \"@supacloud/elysia\";\nimport { UploadBody, UploadLocation, UploadParams, UploadResult,\n type ReviewUploadBody, type ReviewUploadInput, type ReviewUploadLocation, type ReviewUploadResult } from \"./contracts\";\nexport type { ReviewUploadInput, ReviewUploadLocation, ReviewUploadResult } from \"./contracts\";\ntype PreviewUploadError =\n | { readonly _tag: \"AUTHENTICATION_REQUIRED\" }\n | { readonly _tag: \"UPLOAD_INPUT_INVALID\" }\n | { readonly _tag: \"UPLOAD_DENIED\" }\n | { readonly _tag: \"UPLOADS_UNAVAILABLE\" };\ntype RegisterUploadError =\n | PreviewUploadError\n | { readonly _tag: \"UPLOAD_CONTENT_INVALID\" }\n | { readonly _tag: \"COMMAND_IDEMPOTENCY_CONFLICT\" }\n | { readonly _tag: \"COMMAND_REJECTED\" }\n | { readonly _tag: \"UPLOAD_OUTCOME_UNKNOWN\" };\nexport interface ReviewUploadPort {\n previewUpload(context: unknown, input: ReviewUploadInput): Promise<ReviewUploadLocation>;\n registerUpload(context: unknown, input: ReviewUploadInput): Promise<ReviewUploadResult>;\n lookupUpload?(context: unknown, input: ReviewUploadInput): Promise<boolean>;\n}\n@Injectable({ scope: \"request\" })\nexport class ReviewUploads {\n constructor(@Inject(DB_CLIENT) private readonly store: Partial<ReviewUploadPort>,\n @Inject(REQUEST_CONTEXT) private readonly context: unknown) {}\n\n preview(input: ReviewUploadInput): Promise<ReviewUploadLocation> {\n if (!this.store.previewUpload) throw new ApplicationError(\"Attachment uploads are not configured\", { status: 501, code: \"UPLOADS_UNAVAILABLE\" });\n return this.store.previewUpload(this.context, input);\n }\n register(input: ReviewUploadInput): Promise<ReviewUploadResult> {\n if (!this.store.registerUpload) throw new ApplicationError(\"Attachment uploads are not configured\", { status: 501, code: \"UPLOADS_UNAVAILABLE\" });\n return this.store.registerUpload(this.context, input);\n }\n}\n\n@Controller(\"/reviews\")\nexport class ReviewUploadsController {\n constructor(@Inject(ReviewUploads) private readonly uploads: ReviewUploads) {}\n\n @Post(\"/:id/attachment-upload\", {\n params: UploadParams,\n body: UploadBody,\n responses: { 200: UploadLocation },\n effect: {\n required: true,\n dependencies: [],\n errors: [\n { tag: \"AUTHENTICATION_REQUIRED\", status: 401, code: \"AUTHENTICATION_REQUIRED\" },\n { tag: \"UPLOAD_INPUT_INVALID\", status: 400, code: \"UPLOAD_INPUT_INVALID\" },\n { tag: \"UPLOAD_DENIED\", status: 403, code: \"UPLOAD_DENIED\" },\n { tag: \"UPLOADS_UNAVAILABLE\", status: 501, code: \"UPLOADS_UNAVAILABLE\" },\n ],\n retry: \"none\",\n },\n })\n preview(@Param(\"id\") id: string, @Body() body: ReviewUploadBody): Effect.Effect<ReviewUploadLocation, PreviewUploadError, never> {\n return Effect.promise(() => this.uploads.preview({ reviewId: id, artifactId: body.artifactId, expectedVersion: body.expectedVersion }));\n }\n @Post(\"/:id/attachment-registration\", {\n params: UploadParams,\n body: UploadBody,\n responses: { 200: UploadResult },\n effect: {\n required: true,\n dependencies: [],\n errors: [\n { tag: \"AUTHENTICATION_REQUIRED\", status: 401, code: \"AUTHENTICATION_REQUIRED\" },\n { tag: \"UPLOAD_INPUT_INVALID\", status: 400, code: \"UPLOAD_INPUT_INVALID\" },\n { tag: \"UPLOAD_DENIED\", status: 403, code: \"UPLOAD_DENIED\" },\n { tag: \"UPLOAD_CONTENT_INVALID\", status: 400, code: \"UPLOAD_CONTENT_INVALID\" },\n { tag: \"COMMAND_IDEMPOTENCY_CONFLICT\", status: 409, code: \"COMMAND_IDEMPOTENCY_CONFLICT\" },\n { tag: \"COMMAND_REJECTED\", status: 403, code: \"COMMAND_REJECTED\" },\n { tag: \"UPLOADS_UNAVAILABLE\", status: 501, code: \"UPLOADS_UNAVAILABLE\" },\n { tag: \"UPLOAD_OUTCOME_UNKNOWN\", status: 503, code: \"UPLOAD_OUTCOME_UNKNOWN\" },\n ],\n retry: \"none\",\n },\n })\n register(@Param(\"id\") id: string, @Body() body: ReviewUploadBody): Effect.Effect<ReviewUploadResult, RegisterUploadError, never> {\n return Effect.promise(() => this.uploads.register({ reviewId: id, artifactId: body.artifactId, expectedVersion: body.expectedVersion }));\n }\n}\n";
2
- export declare const STARTER_UPLOAD_SCHEMA = "-- Apply explicitly with the migration owner.\nALTER TABLE public.starter_members ADD COLUMN storage_subject uuid UNIQUE;\nGRANT SELECT (subject,enabled,can_approve,storage_subject) ON public.starter_members TO authenticated;\nDROP POLICY IF EXISTS starter_member_read ON public.starter_members;\nCREATE POLICY starter_member_read ON public.starter_members FOR SELECT TO authenticated\n USING (subject=COALESCE(NULLIF(auth.jwt()->>'external_sub',''),auth.jwt()->>'sub') AND storage_subject=auth.uid());\nGRANT SELECT ON public.starter_reviews TO authenticated;\nDROP POLICY IF EXISTS starter_review_read ON public.starter_reviews;\nCREATE POLICY starter_review_read ON public.starter_reviews FOR SELECT TO authenticated\n USING (owner_id=COALESCE(NULLIF(auth.jwt()->>'external_sub',''),auth.jwt()->>'sub') AND EXISTS (\n SELECT 1 FROM public.starter_members m WHERE m.subject=owner_id\n AND m.enabled AND m.can_approve AND m.storage_subject=auth.uid()\n ));\nINSERT INTO storage.buckets(id,name,public,file_size_limit,allowed_mime_types)\n VALUES ('review-attachments','review-attachments',false,1048576,ARRAY['text/plain']);\nDROP POLICY IF EXISTS starter_attachment_read ON storage.objects;\nCREATE POLICY starter_attachment_read ON storage.objects FOR SELECT TO authenticated\n USING (bucket_id='review-attachments');\nDROP POLICY IF EXISTS starter_attachment_insert ON storage.objects;\nCREATE POLICY starter_attachment_insert ON storage.objects FOR INSERT TO authenticated\n WITH CHECK (bucket_id='review-attachments');\n-- Restrictive fences also apply when the host already has permissive Storage policies.\nDROP POLICY IF EXISTS starter_attachment_owner_fence ON storage.objects;\nCREATE POLICY starter_attachment_owner_fence ON storage.objects AS RESTRICTIVE FOR ALL TO authenticated\n USING (bucket_id<>'review-attachments' OR (split_part(name,'/',1)=auth.uid()::text AND EXISTS (\n SELECT 1 FROM public.starter_reviews r JOIN public.starter_members m ON m.subject=r.owner_id\n WHERE r.id=split_part(name,'/',2) AND m.subject=COALESCE(NULLIF(auth.jwt()->>'external_sub',''),auth.jwt()->>'sub')\n AND m.storage_subject=auth.uid() AND m.enabled AND m.can_approve\n )))\n WITH CHECK (bucket_id<>'review-attachments' OR (split_part(name,'/',1)=auth.uid()::text\n AND name ~ '^[a-f0-9-]{36}/[a-f0-9-]{36}/[a-f0-9-]{36}[.]txt$' AND EXISTS (\n SELECT 1 FROM public.starter_reviews r JOIN public.starter_members m ON m.subject=r.owner_id\n WHERE r.id=split_part(name,'/',2) AND r.state='draft' AND m.subject=COALESCE(NULLIF(auth.jwt()->>'external_sub',''),auth.jwt()->>'sub')\n AND m.storage_subject=auth.uid() AND m.enabled AND m.can_approve\n )));\nDROP POLICY IF EXISTS starter_attachment_update_fence ON storage.objects;\nCREATE POLICY starter_attachment_update_fence ON storage.objects AS RESTRICTIVE FOR UPDATE TO authenticated\n USING (bucket_id<>'review-attachments') WITH CHECK (bucket_id<>'review-attachments');\nDROP POLICY IF EXISTS starter_attachment_delete_fence ON storage.objects;\nCREATE POLICY starter_attachment_delete_fence ON storage.objects AS RESTRICTIVE FOR DELETE TO authenticated\n USING (bucket_id<>'review-attachments');\n";
2
+ export declare const STARTER_UPLOAD_SCHEMA = "-- Apply explicitly with the migration owner.\nALTER TABLE public.starter_members ADD COLUMN storage_subject uuid UNIQUE;\nGRANT SELECT (subject,enabled,can_approve,storage_subject) ON public.starter_members TO authenticated;\nDROP POLICY IF EXISTS starter_member_read ON public.starter_members;\nCREATE POLICY starter_member_read ON public.starter_members FOR SELECT TO authenticated\n USING (subject=COALESCE(NULLIF(auth.jwt()->>'external_sub',''),auth.jwt()->>'sub') AND storage_subject=auth.uid());\nDROP POLICY IF EXISTS starter_member_storage_fence ON public.starter_members;\nCREATE POLICY starter_member_storage_fence ON public.starter_members AS RESTRICTIVE FOR SELECT TO authenticated\n USING (subject=COALESCE(NULLIF(auth.jwt()->>'external_sub',''),auth.jwt()->>'sub') AND storage_subject=auth.uid());\nGRANT SELECT ON public.starter_reviews TO authenticated;\nDROP POLICY IF EXISTS starter_review_read ON public.starter_reviews;\nCREATE POLICY starter_review_read ON public.starter_reviews FOR SELECT TO authenticated\n USING (owner_id=COALESCE(NULLIF(auth.jwt()->>'external_sub',''),auth.jwt()->>'sub') AND EXISTS (\n SELECT 1 FROM public.starter_members m WHERE m.subject=owner_id\n AND m.enabled AND m.can_approve AND m.storage_subject=auth.uid()\n ));\nDROP POLICY IF EXISTS starter_review_storage_fence ON public.starter_reviews;\nCREATE POLICY starter_review_storage_fence ON public.starter_reviews AS RESTRICTIVE FOR SELECT TO authenticated\n USING (owner_id=COALESCE(NULLIF(auth.jwt()->>'external_sub',''),auth.jwt()->>'sub') AND EXISTS (\n SELECT 1 FROM public.starter_members m WHERE m.subject=owner_id\n AND m.enabled AND m.can_approve AND m.storage_subject=auth.uid()\n ));\nINSERT INTO storage.buckets(id,name,public,file_size_limit,allowed_mime_types)\n VALUES ('review-attachments','review-attachments',false,1048576,ARRAY['text/plain']);\nDROP POLICY IF EXISTS starter_attachment_read ON storage.objects;\nCREATE POLICY starter_attachment_read ON storage.objects FOR SELECT TO authenticated\n USING (bucket_id='review-attachments');\nDROP POLICY IF EXISTS starter_attachment_insert ON storage.objects;\nCREATE POLICY starter_attachment_insert ON storage.objects FOR INSERT TO authenticated\n WITH CHECK (bucket_id='review-attachments');\n-- Restrictive fences also apply when the host already has permissive Storage policies.\nDROP POLICY IF EXISTS starter_attachment_owner_fence ON storage.objects;\nCREATE POLICY starter_attachment_owner_fence ON storage.objects AS RESTRICTIVE FOR ALL TO authenticated\n USING (bucket_id<>'review-attachments' OR (split_part(name,'/',1)=auth.uid()::text AND EXISTS (\n SELECT 1 FROM public.starter_reviews r JOIN public.starter_members m ON m.subject=r.owner_id\n WHERE r.id=split_part(name,'/',2) AND m.subject=COALESCE(NULLIF(auth.jwt()->>'external_sub',''),auth.jwt()->>'sub')\n AND m.storage_subject=auth.uid() AND m.enabled AND m.can_approve\n )))\n WITH CHECK (bucket_id<>'review-attachments' OR (split_part(name,'/',1)=auth.uid()::text\n AND name ~ '^[a-f0-9-]{36}/[a-f0-9-]{36}/[a-f0-9-]{36}[.]txt$' AND EXISTS (\n SELECT 1 FROM public.starter_reviews r JOIN public.starter_members m ON m.subject=r.owner_id\n WHERE r.id=split_part(name,'/',2) AND r.state='draft' AND m.subject=COALESCE(NULLIF(auth.jwt()->>'external_sub',''),auth.jwt()->>'sub')\n AND m.storage_subject=auth.uid() AND m.enabled AND m.can_approve\n )));\nDROP POLICY IF EXISTS starter_attachment_update_fence ON storage.objects;\nCREATE POLICY starter_attachment_update_fence ON storage.objects AS RESTRICTIVE FOR UPDATE TO authenticated\n USING (bucket_id<>'review-attachments') WITH CHECK (bucket_id<>'review-attachments');\nDROP POLICY IF EXISTS starter_attachment_delete_fence ON storage.objects;\nCREATE POLICY starter_attachment_delete_fence ON storage.objects AS RESTRICTIVE FOR DELETE TO authenticated\n USING (bucket_id<>'review-attachments');\n";
3
3
  export declare const STARTER_UPLOAD_ADAPTER = "import { MIMEType } from \"node:util\";\nimport { SupaCloudArtifactsClient } from \"@supacloud/js\";\nimport { createTransactionalCommand, plaintextCommandInput } from \"@supacloud/commands\";\nimport { CommandError } from \"@supacloud/contracts\";\nimport { createPostgresCommandStore, type CommandTransaction } from \"@supacloud/db\";\nimport { ApplicationError, createSchemaDecoder, requireTrustedIdentity } from \"@supacloud/elysia\";\nimport { UploadInput, UploadResult } from \"../review/contracts\";\nimport type { ReviewAttachmentOptions } from \"./review-attachments\";\nimport type { ReviewUploadInput, ReviewUploadPort, ReviewUploadResult } from \"../review/uploads\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\nfunction record(value: unknown): Record<string, unknown> {\n if (!isRecord(value)) throw new TypeError(\"Invalid upload record\");\n return value;\n}\nfunction rows(value: unknown): Record<string, unknown>[] {\n if (!Array.isArray(value)) throw new TypeError(\"Invalid upload database result\");\n return value.map(record);\n}\nconst decodeInput = createSchemaDecoder(UploadInput, { normalize: false });\nconst result = createSchemaDecoder(UploadResult, { normalize: false });\nfunction capture(value: unknown): ReviewUploadInput {\n try {\n const input = decodeInput(value);\n return { ...input, reviewId: input.reviewId.toLowerCase(), artifactId: input.artifactId.toLowerCase() };\n } catch {\n throw new ApplicationError(\"Invalid upload input\", { status: 400, code: \"UPLOAD_INPUT_INVALID\" });\n }\n}\n\nexport async function createReviewUploadAdapters(options: ReviewAttachmentOptions): Promise<ReviewUploadPort> {\n const { database, service, projectId, tenantId } = options;\n const binding = rows(await database.transaction(tx => tx.query(\n \"SELECT project_id,tenant_id FROM public.starter_application WHERE singleton\",\n )));\n if (!projectId.trim() || !tenantId.trim() || binding.length !== 1\n || binding[0]?.[\"project_id\"] !== projectId || binding[0]?.[\"tenant_id\"] !== tenantId) {\n throw new Error(\"Upload database project/tenant binding mismatch\");\n }\n const artifacts = new SupaCloudArtifactsClient(service);\n function actor(context: unknown): string {\n const who = requireTrustedIdentity(context);\n const access = record(record(context)[\"access\"]);\n if (access[\"projectId\"] !== projectId || access[\"tenantId\"] !== tenantId\n || !Array.isArray(access[\"permissions\"]) || !access[\"permissions\"].includes(\"review.approve\")) {\n throw new ApplicationError(\"Upload permission denied\", { status: 403, code: \"UPLOAD_DENIED\" });\n }\n return who.subject;\n }\n async function authorize(tx: CommandTransaction, subject: string, input: ReviewUploadInput, replay = false) {\n const allowed = rows(await tx.query(\n \"SELECT m.storage_subject::text AS storage_subject FROM public.starter_reviews r \" +\n \"JOIN public.starter_members m ON m.subject=r.owner_id CROSS JOIN public.starter_application p \" +\n \"WHERE r.id=$1 AND r.owner_id=$2 AND ((r.state='draft' AND r.version=$3) OR \" +\n \"($6::boolean AND r.state='approved' AND r.version=$3::bigint+1 AND EXISTS (\" +\n \"SELECT 1 FROM public.starter_attachments b WHERE b.review_id=r.id AND b.artifact_id=$7::uuid AND b.owner_id=$2 \" +\n \"AND b.object_path=m.storage_subject::text || '/' || r.id || '/' || $7::text || '.txt'))) \" +\n \"AND m.enabled AND m.can_approve AND m.storage_subject IS NOT NULL \" +\n \"AND p.singleton AND p.project_id=$4 AND p.tenant_id=$5 FOR UPDATE OF r,m FOR SHARE OF p\",\n [input.reviewId, subject, input.expectedVersion, projectId, tenantId, replay, input.artifactId],\n ));\n if (allowed.length !== 1 || typeof allowed[0]?.[\"storage_subject\"] !== \"string\") {\n throw new ApplicationError(\"Upload ownership, permission or revision changed\", { status: 403, code: \"UPLOAD_DENIED\" });\n }\n return allowed[0][\"storage_subject\"] + \"/\" + input.reviewId + \"/\" + input.artifactId + \".txt\";\n }\n const receiptLookup = createTransactionalCommand({\n name: \"review.attach\", store: createPostgresCommandStore(database), inputCodec: plaintextCommandInput,\n input: capture, result,\n async authorize(who, request, tx) {\n try { await authorize(tx, who.actorId, request, true); return \"allow\"; }\n catch (error) {\n if (error instanceof ApplicationError && error.code === \"UPLOAD_DENIED\") return \"deny\";\n throw error;\n }\n },\n execute: async () => { throw new Error(\"Receipt lookup cannot register an upload\"); },\n audit: { event: \"review.attachment-bound\", details: request => ({ reviewId: request.reviewId, artifactId: request.artifactId }) },\n });\n return {\n async lookupUpload(context, value) {\n const input = capture(value), subject = actor(context);\n return (await receiptLookup.lookup({ actorId: subject, tenantId }, input.artifactId, input))?.status === \"confirmed\";\n },\n async previewUpload(context, value) {\n const input = capture(value), subject = actor(context);\n const objectPath = await database.transaction(tx => authorize(tx, subject, input));\n return { artifactId: input.artifactId, bucketId: \"review-attachments\", objectPath };\n },\n async registerUpload(context, value) {\n const input = capture(value), subject = actor(context);\n try {\n // Only an authorized, validated receipt can bypass external registration.\n const saved = await receiptLookup.lookup({ actorId: subject, tenantId }, input.artifactId, input);\n if (saved !== null) {\n if (saved.status !== \"confirmed\") throw new CommandError(\"COMMAND_RECEIPT_INVALID\");\n return saved.result;\n }\n const objectPath = await database.transaction(tx => authorize(tx, subject, input, true));\n const downloaded = await service.storage.from(\"review-attachments\").download(objectPath);\n if (downloaded.error || !downloaded.data) throw new Error(\"Upload unavailable\");\n const blob = downloaded.data;\n if (blob.size < 1 || blob.size > 1048576 || new MIMEType(blob.type).essence !== \"text/plain\") {\n throw new ApplicationError(\"Unsupported upload\", { status: 400, code: \"UPLOAD_CONTENT_INVALID\" });\n }\n const sha256 = Array.from(new Uint8Array(await crypto.subtle.digest(\"SHA-256\", await blob.arrayBuffer())),\n byte => byte.toString(16).padStart(2, \"0\")).join(\"\");\n await artifacts.register({ artifactId: input.artifactId, bucketId: \"review-attachments\", objectPath,\n artifactType: \"review.attachment\", sha256, sizeBytes: blob.size, mimeType: \"text/plain\" });\n const command = createTransactionalCommand({\n name: \"review.attach\", store: createPostgresCommandStore(database), inputCodec: plaintextCommandInput,\n input: capture, result,\n async authorize(who, request, tx) {\n try {\n const currentPath = await authorize(tx, who.actorId, request, true);\n return currentPath === objectPath ? \"allow\" : \"deny\";\n } catch (error) {\n if (error instanceof ApplicationError && error.code === \"UPLOAD_DENIED\") return \"deny\";\n throw error;\n }\n },\n async execute(tx, request) {\n const existing = rows(await tx.query(\"SELECT artifact_id FROM public.starter_attachments WHERE review_id=$1\", [request.reviewId]));\n if (existing.length) throw new CommandError(\"COMMAND_IDEMPOTENCY_CONFLICT\");\n const bound: ReviewUploadResult = { artifactId: request.artifactId, runId: request.artifactId, objectPath, sha256, bytes: blob.size };\n await tx.query(\"INSERT INTO public.starter_attachments VALUES($1,$2,$3,$4,$5)\",\n [request.reviewId, bound.artifactId, subject, bound.runId, bound.objectPath]);\n return bound;\n },\n audit: { event: \"review.attachment-bound\", details: request => ({ reviewId: request.reviewId, artifactId: request.artifactId }) },\n });\n const receipt = await command.execute({ actorId: subject, tenantId }, input.artifactId, input);\n if (receipt.status !== \"confirmed\") throw new CommandError(\"COMMAND_OUTCOME_UNKNOWN\");\n return receipt.result;\n } catch (error) {\n if (error instanceof ApplicationError) throw error;\n if (error instanceof CommandError && error.code === \"COMMAND_IDEMPOTENCY_CONFLICT\") {\n throw new ApplicationError(\"Conflicting attachment binding\", { status: 409, code: error.code });\n }\n if (error instanceof CommandError && error.code === \"COMMAND_REJECTED\") {\n throw new ApplicationError(\"Upload permission denied\", { status: 403, code: error.code });\n }\n // Registration may have committed even when binding failed; never delete immutable evidence here.\n throw new ApplicationError(\"Upload registration could not be confirmed\", { status: 503, code: \"UPLOAD_OUTCOME_UNKNOWN\" });\n }\n },\n };\n}\n";
@@ -67,7 +67,7 @@ export interface AppToolArguments {
67
67
  ttl_seconds?: number;
68
68
  wait?: boolean;
69
69
  timeout_seconds?: number;
70
- kind?: "module" | "command" | "query" | "controller" | "job" | "contract" | "resource" | "feature";
70
+ kind?: "module" | "command" | "query" | "controller" | "job" | "contract" | "aspect" | "resource" | "feature";
71
71
  template?: "minimal" | "client" | "command" | "model-command" | "app";
72
72
  name?: string;
73
73
  module?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@supacloud/cli",
3
- "version": "0.129.6",
3
+ "version": "0.130.0",
4
4
  "description": "Project-scoped CLI for SupaCloud users",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -52,23 +52,23 @@
52
52
  "directory": "packages/cli"
53
53
  },
54
54
  "dependencies": {
55
- "@supacloud/compiler": "^0.67.3",
55
+ "@supacloud/compiler": "^0.68.0",
56
56
  "@supacloud/delivery": "0.30.1",
57
- "@supacloud/db": "0.27.1",
57
+ "@supacloud/db": "0.28.0",
58
58
  "typebox": "1.4.3"
59
59
  },
60
60
  "overrides": {
61
61
  "@supacloud/contracts": "0.17.0",
62
62
  "@supacloud/delivery": "0.30.1",
63
63
  "@graphql-tools/utils": "^12.0.4",
64
- "@supacloud/compiler": "^0.67.3",
65
- "@supacloud/db": "0.27.1",
64
+ "@supacloud/compiler": "^0.68.0",
65
+ "@supacloud/db": "0.28.0",
66
66
  "deepmerge-ts": "8.0.2",
67
67
  "prisma": "6.19.3"
68
68
  },
69
69
  "devDependencies": {
70
70
  "@supabase/supabase-js": "2.118.0",
71
- "@supacloud/elysia": "0.43.2",
71
+ "@supacloud/elysia": "0.44.0",
72
72
  "@types/bun": "^1.4.5",
73
73
  "effect": "4.0.5",
74
74
  "elysia": "2.0.0-rc.6",