@marktiderman/genesis-cli 1.18.0 → 1.19.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.
@@ -209,6 +209,15 @@ native modules use jest-expo's mocks or their library's own. A test fails when t
209
209
  error (`[push]`, `[updates]`, `[observability]`) or React warns about act(); see `reports.ts`.
210
210
  Add a screen's test there; tests that only read files stay in vitest, outside that folder.
211
211
 
212
+ Gestures and animations run in these tests as they are written, on Gesture Handler's mocks
213
+ (`react-native-gesture-handler/jestSetup.js`, in `jest.config.js`) and Reanimated's test mode
214
+ (`setUpTests()` in `setup.ts`, its resolver in `resolver.js`): worklets run on the JS thread with
215
+ Reanimated's web build, so what only the native UI runtime does (frame timing, native-driven
216
+ gestures, cross-thread races) still needs a device or Maestro run. Fire a gesture by its
217
+ `testID` with `fireGestureHandler` and `getByGestureTestId` from
218
+ `react-native-gesture-handler/jest-utils`, and read an animated style with `getAnimatedStyle`;
219
+ `gestures.test.tsx` drags a Pan gesture and checks the shared value it moves.
220
+
212
221
  ## Releasing
213
222
 
214
223
  `eas.json` and `.eas/workflows/` are the release path on EAS Workflows, and `.maestro/` the smoke
@@ -0,0 +1,64 @@
1
+ // @feat:native-starter
2
+ /**
3
+ * Gestures in Jest: Gesture Handler's mocks (`jestSetup.js`, from jest.config.js) and Reanimated's
4
+ * test mode (`setUpTests()` in setup.ts, its resolver in resolver.js). A Pan gesture fires from
5
+ * the test with `fireGestureHandler`, its worklets write a shared value, and the animated style
6
+ * follows: no device, no UI thread, and no rewriting the component onto the JS thread to test it.
7
+ */
8
+ import { describe, expect, it } from "@jest/globals";
9
+ import { act, render, screen } from "@testing-library/react-native";
10
+ import { useState } from "react";
11
+ import { Text } from "react-native";
12
+ import { GestureDetector, GestureHandlerRootView, State, usePanGesture } from "react-native-gesture-handler";
13
+ import { fireGestureHandler, getByGestureTestId } from "react-native-gesture-handler/jest-utils";
14
+ import Animated, { getAnimatedStyle, useAnimatedStyle, useSharedValue } from "react-native-reanimated";
15
+ import { scheduleOnRN } from "react-native-worklets";
16
+
17
+ // Reanimated types its Jest helpers in index.native.d.ts; TypeScript reads the web stub, which takes nothing.
18
+ const animatedStyle = getAnimatedStyle as unknown as (element: unknown) => unknown;
19
+
20
+ /** A card dragged sideways: the offset lives in a shared value, the drop is reported to React. */
21
+ function DraggableCard() {
22
+ const offset = useSharedValue(0);
23
+ const [dropped, setDropped] = useState<number | null>(null);
24
+ const pan = usePanGesture({
25
+ testID: "card-pan",
26
+ onUpdate: (event) => {
27
+ "worklet";
28
+ offset.value = event.translationX;
29
+ },
30
+ onDeactivate: () => {
31
+ "worklet";
32
+ scheduleOnRN(setDropped, offset.value);
33
+ },
34
+ });
35
+ const style = useAnimatedStyle(() => ({ transform: [{ translateX: offset.value }] }));
36
+ return (
37
+ <GestureHandlerRootView>
38
+ <GestureDetector gesture={pan}>
39
+ <Animated.View testID="card" style={style}>
40
+ <Text>{dropped === null ? "Drag me" : `Dropped at ${dropped}`}</Text>
41
+ </Animated.View>
42
+ </GestureDetector>
43
+ </GestureHandlerRootView>
44
+ );
45
+ }
46
+
47
+ describe("gestures in Jest", () => {
48
+ it("drives a Pan gesture's shared value and animated style from the test", async () => {
49
+ await render(<DraggableCard />);
50
+ expect(animatedStyle(screen.getByTestId("card"))).toEqual({ transform: [{ translateX: 0 }] });
51
+
52
+ await act(async () => {
53
+ fireGestureHandler(getByGestureTestId("card-pan"), [
54
+ { state: State.BEGAN, translationX: 0 },
55
+ { state: State.ACTIVE, translationX: 40 },
56
+ { translationX: 120 },
57
+ { state: State.END, translationX: 120 },
58
+ ]);
59
+ });
60
+
61
+ expect(animatedStyle(screen.getByTestId("card"))).toEqual({ transform: [{ translateX: 120 }] });
62
+ expect(await screen.findByText("Dropped at 120")).toBeOnTheScreen();
63
+ });
64
+ });
@@ -3,10 +3,22 @@
3
3
  * one. jest-expo resolves with the `require` and `react-native` conditions only, so it would
4
4
  * find nothing; for `@marktiderman/*` (and only those) this adds `import`. Babel turns the
5
5
  * module into CommonJS on the way in (`alsoTransform` in jest.config.js).
6
+ *
7
+ * Everything then goes through Reanimated's resolver (its Jest guide), which picks the web
8
+ * builds of Reanimated and Worklets: shared values, animated styles and gesture callbacks run
9
+ * in Jest without a UI thread.
6
10
  */
11
+ const reanimatedResolver = require("react-native-reanimated/jest/resolver");
12
+
7
13
  module.exports = (request, options) => {
14
+ // Gesture Handler's native build hands Worklets' UI runtime to its native module once loaded.
15
+ // Jest runs the web Worklets, which has no UI runtime and throws, so that one step takes Gesture
16
+ // Handler's web build (a no-op), as it does on the web. Its gestures still run on its Jest mocks.
17
+ if (request.endsWith("/installUIRuntimeBindings") && options.basedir.includes("react-native-gesture-handler")) {
18
+ return reanimatedResolver(`${request}.web`, options);
19
+ }
8
20
  if (request.startsWith("@marktiderman/")) {
9
- return options.defaultResolver(request, { ...options, conditions: [...(options.conditions ?? []), "import"] });
21
+ return reanimatedResolver(request, { ...options, conditions: [...(options.conditions ?? []), "import"] });
10
22
  }
11
- return options.defaultResolver(request, options);
23
+ return reanimatedResolver(request, options);
12
24
  };
@@ -8,6 +8,11 @@ import { expectedReports } from "./reports";
8
8
  process.env.EXPO_PUBLIC_SUPABASE_URL = "https://test.supabase.invalid";
9
9
  process.env.EXPO_PUBLIC_SUPABASE_PUBLISHABLE_KEY = "test-publishable-key";
10
10
 
11
+ // Reanimated's test mode (its Jest guide, with the resolver in resolver.js): animations run on
12
+ // Jest's timers, and `toHaveAnimatedStyle` checks an animated style. Gesture Handler's mocks load
13
+ // from jest.config.js (`setupFiles`); `__tests__/components/gestures.test.tsx` shows both.
14
+ require("react-native-reanimated").setUpTests();
15
+
11
16
  // Native modules jest-expo has no mock for: each library's own Jest mock.
12
17
  jest.mock("@react-native-async-storage/async-storage", () => require("@react-native-async-storage/async-storage/jest/async-storage-mock"));
13
18
  jest.mock("@react-native-community/netinfo", () => require("@react-native-community/netinfo/jest/netinfo-mock.js"));
@@ -1,5 +1,5 @@
1
1
  // @feat:native-starter @feat:app-updates @feat:push @feat:observability @feat:devtools-overlay @feat:support-feedback @feat:chat @feat:product-roadmap
2
- import { readFileSync, readdirSync, statSync } from "node:fs";
2
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
3
3
  import { createRequire } from "node:module";
4
4
  import { dirname, join } from "node:path";
5
5
  import { describe, expect, it } from "vitest";
@@ -21,6 +21,9 @@ const chatSql = (path: string) => readFileSync(join(chatPackage, "migrations", p
21
21
  // `genesis init --without <switch>` has none of that block's migrations, tests or functions, so
22
22
  // the checks of those files run only while it's on.
23
23
  const { updates, push, notifications, support, chat } = starter.features;
24
+ // An app made with `genesis init --beside <web-app>` has no supabase/ folder: its database files
25
+ // are the web app's, so the checks of them run only where the folder is.
26
+ const database = existsSync(join(root, "supabase"));
24
27
 
25
28
  function filesUnder(dir: string): string[] {
26
29
  return readdirSync(join(root, dir)).flatMap((name) => {
@@ -37,7 +40,7 @@ describe("root layout", () => {
37
40
  });
38
41
  });
39
42
 
40
- describe("migrations", () => {
43
+ describe.runIf(database)("migrations", () => {
41
44
  it("each has its own version, so a new app's database applies every one", () => {
42
45
  const versions = filesUnder("supabase/migrations").map((f) => f.split("/").pop()!.split("_")[0]!);
43
46
  expect(new Set(versions).size).toBe(versions.length);
@@ -99,6 +102,12 @@ describe("deep links", () => {
99
102
  expect(linkHosts({ links: null })).toEqual([]);
100
103
  expect(linkHosts({ links: {} })).toEqual([]);
101
104
  });
105
+
106
+ it("accepts a genesis.config.json with other keys and no links block (it typechecks)", () => {
107
+ // What a JSON import infers once `links` is removed: no key in common with `links`.
108
+ const noLinks = { doctor: { packs: ["native"] }, starter: { blocks: { push: ["push"] } } };
109
+ expect(linkHosts(noLinks)).toEqual([]);
110
+ });
102
111
  });
103
112
 
104
113
  describe("EAS config", () => {
@@ -223,7 +232,7 @@ describe("copy catalog", () => {
223
232
  });
224
233
  });
225
234
 
226
- describe("supabase/migrations", () => {
235
+ describe.runIf(database)("supabase/migrations", () => {
227
236
  it("carries @marktiderman/genesis-supabase's account-deletion migration unchanged", () => {
228
237
  const shipped = shippedSql("0001_genesis_account_deletion.sql");
229
238
  const copies = filesUnder("supabase/migrations").filter((f) => f.endsWith("_genesis_account_deletion.sql"));
@@ -290,9 +299,20 @@ describe("supabase/migrations", () => {
290
299
  const order = filesUnder("supabase/migrations").sort();
291
300
  expect(order.indexOf(copies[0]!)).toBeGreaterThan(order.findIndex((f) => f.endsWith("_genesis_push.sql")));
292
301
  });
302
+
303
+ it.runIf(support)("carries genesis-support's findings migration and its pgTAP test unchanged, after the support one", () => {
304
+ const supportPackage = dirname(createRequire(join(root, "package.json")).resolve("@marktiderman/genesis-support/package.json"));
305
+ const shipped = (rel: string) => readFileSync(join(supportPackage, "migrations", rel), "utf8");
306
+ const copies = filesUnder("supabase/migrations").filter((f) => f.endsWith("_genesis_support_findings.sql"));
307
+ expect(copies).toHaveLength(1);
308
+ expect(read(copies[0]!)).toBe(shipped("0003_genesis_support_findings.sql"));
309
+ expect(read("supabase/tests/database/genesis_support_findings.test.sql")).toBe(shipped("tests/0003_genesis_support_findings.test.sql"));
310
+ const order = filesUnder("supabase/migrations").sort();
311
+ expect(order.indexOf(copies[0]!)).toBeGreaterThan(order.findIndex((f) => f.endsWith("_genesis_support.sql")));
312
+ });
293
313
  });
294
314
 
295
- describe("supabase/functions", () => {
315
+ describe.runIf(database)("supabase/functions", () => {
296
316
  it("carries @marktiderman/genesis-supabase's genesis-apple-revoke function unchanged", () => {
297
317
  const shipped = join(supabasePackage, "functions", "genesis-apple-revoke");
298
318
  const names = readdirSync(shipped).sort();
@@ -357,7 +377,7 @@ describe("support", () => {
357
377
  });
358
378
 
359
379
  describe("chat", () => {
360
- it.runIf(chat)("carries chat's migration and pgTAP test unchanged after the support one, and serves genesis_chat through the API", () => {
380
+ it.runIf(chat && database)("carries chat's migration and pgTAP test unchanged after the support one, and serves genesis_chat through the API", () => {
361
381
  const copies = filesUnder("supabase/migrations").filter((f) => f.endsWith("_genesis_chat.sql"));
362
382
  expect(copies).toHaveLength(1);
363
383
  expect(read(copies[0]!)).toBe(chatSql("0001_genesis_chat.sql"));
@@ -378,7 +398,7 @@ describe("chat", () => {
378
398
  expect(JSON.parse(read("genesis.config.json")).doctor.supabase.exposedSchemas).toContain("genesis_chat");
379
399
  });
380
400
 
381
- it.runIf(chat)("carries chat's 0002 migration (topics, scheduled send, availability, broadcast, search) and its pgTAP test unchanged, after 0001", () => {
401
+ it.runIf(chat && database)("carries chat's 0002 migration (topics, scheduled send, availability, broadcast, search) and its pgTAP test unchanged, after 0001", () => {
382
402
  const copies = filesUnder("supabase/migrations").filter((f) => f.endsWith("_genesis_chat_coaching.sql"));
383
403
  expect(copies).toHaveLength(1);
384
404
  expect(read(copies[0]!)).toBe(chatSql("0002_genesis_chat_coaching.sql"));
@@ -423,7 +443,7 @@ describe("chat", () => {
423
443
  expect(read("src/lib/chat.tsx")).toContain("starter.features.chat && starter.features.push");
424
444
  });
425
445
 
426
- it.runIf(chat)("names people from their auth metadata through chat_people, after the chat migration, with its pgTAP test", () => {
446
+ it.runIf(chat && database)("names people from their auth metadata through chat_people, after the chat migration, with its pgTAP test", () => {
427
447
  const copies = filesUnder("supabase/migrations").filter((f) => f.endsWith("_chat_people.sql"));
428
448
  expect(copies).toHaveLength(1);
429
449
  const order = filesUnder("supabase/migrations").sort();
@@ -22,6 +22,9 @@ module.exports = {
22
22
  preset: "jest-expo",
23
23
  // Every test file here is jest's, `.ts` or `.tsx`; vitest.config.mts leaves this folder out.
24
24
  testMatch: ["<rootDir>/__tests__/components/**/*.test.{ts,tsx}"],
25
+ // Gesture Handler's own mocks (its Jest guide), after jest-expo's: gestures fire from tests
26
+ // with `fireGestureHandler` (react-native-gesture-handler/jest-utils), no native module.
27
+ setupFiles: [...expoPreset.setupFiles, "react-native-gesture-handler/jestSetup.js"],
25
28
  setupFilesAfterEnv: ["<rootDir>/__tests__/components/setup.ts"],
26
29
  resolver: "<rootDir>/__tests__/components/resolver.js",
27
30
  moduleNameMapper: {
@@ -72,6 +72,7 @@
72
72
  "react-hook-form": "^7.56.4",
73
73
  "react-native": "0.88.0",
74
74
  "react-native-css-interop": "^0.2.7",
75
+ "react-native-gesture-handler": "~3.3.0",
75
76
  "react-native-keyboard-controller": "1.22.7",
76
77
  "react-native-reanimated": "4.7.1",
77
78
  "react-native-safe-area-context": "~5.10.1",
@@ -84,6 +85,7 @@
84
85
  "zod": "^4.6.6"
85
86
  },
86
87
  "devDependencies": {
88
+ "@jest/globals": "~30.5.2",
87
89
  "@marktiderman/genesis-cli": "workspace:^",
88
90
  "@react-native/jest-preset": "0.88.0",
89
91
  "@testing-library/react-native": "^14.1.0",
@@ -1,8 +1,12 @@
1
1
  /**
2
2
  * The web hosts whose links open in the app: genesis.config.json's `links.hosts`. An app with no
3
- * domain yet has no `links` block (or no hosts in it), so it has no app links and only its
4
- * schemes open it. Kept free of React Native imports so the tests can read it.
3
+ * domain yet has no `links` block: remove the whole block, since the Expo config plugin rejects
4
+ * one with an empty `hosts` list. It then has no app links and only its schemes open it. Kept
5
+ * free of React Native imports so the tests can read it.
5
6
  */
6
- export function linkHosts(config: { links?: { hosts?: readonly string[] } | null }): string[] {
7
+ export type LinkHostsConfig = { readonly links?: { readonly hosts?: readonly string[] } | null; readonly [key: string]: unknown };
8
+
9
+ /** Takes the whole genesis.config.json, so a config with other keys and no `links` still typechecks. */
10
+ export function linkHosts(config: LinkHostsConfig): string[] {
7
11
  return [...(config.links?.hosts ?? [])];
8
12
  }
@@ -39,6 +39,11 @@ export interface AppleConfig {
39
39
 
40
40
  const TEN_CHARS = /^[A-Z0-9]{10}$/;
41
41
  const CLIENT_ID = /^[A-Za-z0-9][A-Za-z0-9.-]{0,254}$/;
42
+ // The PKCS#8 PEM armour, with the dashes counted (`-{5}`) rather than written out: the literal
43
+ // header is what secret scanners (gitleaks' private-key rule) look for, and every app that installs
44
+ // this function scans it.
45
+ const PEM_KEY = /-{5}BEGIN PRIVATE KEY-{5}[\s\S]+-{5}END PRIVATE KEY-{5}/;
46
+ const PEM_MARKER = /-{5}(?:BEGIN|END) PRIVATE KEY-{5}/g;
42
47
 
43
48
  /**
44
49
  * Reads the Apple settings from the environment. Returns the names that are
@@ -55,7 +60,7 @@ export function readAppleConfig(env: (name: string) => string | undefined): { co
55
60
  .filter(Boolean);
56
61
  if (!TEN_CHARS.test(teamId)) problems.push("APPLE_TEAM_ID (10 capital letters or digits)");
57
62
  if (!TEN_CHARS.test(keyId)) problems.push("APPLE_KEY_ID (10 capital letters or digits)");
58
- if (!/-----BEGIN PRIVATE KEY-----[\s\S]+-----END PRIVATE KEY-----/.test(privateKey)) problems.push("APPLE_PRIVATE_KEY (the .p8 file's PEM text)");
63
+ if (!PEM_KEY.test(privateKey)) problems.push("APPLE_PRIVATE_KEY (the .p8 file's PEM text)");
59
64
  if (clientIds.length === 0 || !clientIds.every((id) => CLIENT_ID.test(id))) problems.push("APPLE_CLIENT_IDS (comma-separated bundle ids or Services IDs)");
60
65
  return problems.length ? { problems } : { config: { teamId, keyId, privateKey, clientIds } };
61
66
  }
@@ -85,7 +90,7 @@ const keyCache = new Map<string, Promise<CryptoKey>>();
85
90
  function signingKey(pem: string): Promise<CryptoKey> {
86
91
  let key = keyCache.get(pem);
87
92
  if (!key) {
88
- const body = pem.replace(/-----(BEGIN|END) PRIVATE KEY-----/g, "").replace(/\s+/g, "");
93
+ const body = pem.replace(PEM_MARKER, "").replace(/\s+/g, "");
89
94
  const der = Uint8Array.from(atob(body), (c) => c.charCodeAt(0));
90
95
  key = crypto.subtle.importKey("pkcs8", der, { name: "ECDSA", namedCurve: "P-256" }, false, ["sign"]);
91
96
  // A bad key must not stay cached as a rejected promise.
@@ -0,0 +1,339 @@
1
+ -- Genesis support findings: severity, the verify loop and report handlers
2
+ --
3
+ -- Part of the `support-feedback` block of `@marktiderman/genesis-support`. Apply it after
4
+ -- `0006_genesis_support.sql` from `@marktiderman/genesis-supabase` (`genesis add
5
+ -- support-feedback` orders them).
6
+ --
7
+ -- severity low, medium, high or critical, as the person (or an agent) sent it, in its
8
+ -- own column (the intake function also keeps it in `context`).
9
+ -- handlers Besides support staff, the app may name who else handles a report: they read
10
+ -- it and its screenshots, reply as support and set its status. The app's hook
11
+ -- `private.genesis_support_report_handler(report uuid, person uuid)` returns
12
+ -- boolean; it is optional, and without it only staff handle reports. Handlers
13
+ -- don't observe a report's support-chat thread (staff-only internal notes
14
+ -- stay staff-only); their replies reach it as support.
15
+ -- verify loop The person confirms a fix (verified_at) or reopens the report (back to
16
+ -- in_progress, reopened_at) with support_verify_report. Marking a report
17
+ -- addressed or wont_fix stamps resolved_at.
18
+ -- verify prompt Off unless the app turns it on with its hook
19
+ -- `private.genesis_support_verify_prompt_enabled()` returning true: then a
20
+ -- report someone else marks addressed asks its person, in its thread, to check
21
+ -- the fix (at most once an hour per report). That reply is the system's
22
+ -- (support_replies.prompt = 'verify'): it doesn't count against anyone's reply
23
+ -- limit. It is a staff reply, so it marks the report unread for its person,
24
+ -- ends their editing, and with support-chat is pushed as the marker's message.
25
+ -- If it can't be posted (a reply rule that refuses it, a limit), the status
26
+ -- change still goes through without it.
27
+ --
28
+ -- The support-email block (`0002_genesis_support_email.sql`) also replaces
29
+ -- private.genesis_support_new_reply. This file's version keeps the email channel's rules when
30
+ -- that block is already installed; if support-email is added after this file, handlers can no
31
+ -- longer reply (status changes still work, without the prompt) until this file's
32
+ -- genesis_support_new_reply is applied again.
33
+ --
34
+ -- Never edit it once applied; change it with a new migration.
35
+ --
36
+ -- Verify: the pgTAP test beside this file (`tests/0003_genesis_support_findings.test.sql`).
37
+
38
+ create schema if not exists private;
39
+
40
+ alter table public.support_reports
41
+ add column if not exists severity text constraint support_reports_severity check (severity in ('low', 'medium', 'high', 'critical')),
42
+ add column if not exists resolved_at timestamptz,
43
+ add column if not exists verified_at timestamptz,
44
+ add column if not exists reopened_at timestamptz;
45
+
46
+ comment on column public.support_reports.severity is
47
+ 'How bad it is, as the person sent it: low, medium, high or critical. Genesis support.';
48
+ comment on column public.support_reports.resolved_at is
49
+ 'When it was last marked addressed or wont_fix (cleared when it is reopened). Genesis support.';
50
+ comment on column public.support_reports.verified_at is
51
+ 'When its person confirmed the fix. Genesis support.';
52
+ comment on column public.support_reports.reopened_at is
53
+ 'When its person last said the fix did not work. Genesis support.';
54
+
55
+ -- The person sends it with the report.
56
+ grant insert (severity) on table public.support_reports to authenticated;
57
+
58
+ -- A reply the system posted, and which: only the database writes it (no column grant).
59
+ alter table public.support_replies
60
+ add column if not exists prompt text constraint support_replies_prompt check (prompt in ('verify'));
61
+
62
+ comment on column public.support_replies.prompt is
63
+ 'Set on a reply the system posted: verify (asks the person to check a fix). Genesis support.';
64
+
65
+ -- Handlers ----------------------------------------------------------------------------
66
+
67
+ -- Staff, or whom the app's hook names for this report.
68
+ create or replace function private.genesis_support_handler(report uuid, person uuid)
69
+ returns boolean
70
+ language plpgsql
71
+ stable
72
+ security definer
73
+ set search_path = ''
74
+ as $$
75
+ begin
76
+ if person is null or report is null then
77
+ return false;
78
+ end if;
79
+ -- The staff hook is the app's (0006); without it, nobody is staff.
80
+ if to_regprocedure('private.genesis_support_staff(uuid)') is not null then
81
+ if coalesce(private.genesis_support_staff(person), false) then
82
+ return true;
83
+ end if;
84
+ end if;
85
+ if to_regprocedure('private.genesis_support_report_handler(uuid, uuid)') is null then
86
+ return false;
87
+ end if;
88
+ return coalesce(private.genesis_support_report_handler(report, person), false);
89
+ end;
90
+ $$;
91
+
92
+ revoke execute on function private.genesis_support_handler(uuid, uuid) from public, anon, authenticated;
93
+
94
+ -- Does the signed-in person handle this report? Policies and the client ask; it answers only
95
+ -- about the caller.
96
+ create or replace function public.support_handles(report uuid)
97
+ returns boolean
98
+ language sql
99
+ stable
100
+ security definer
101
+ set search_path = ''
102
+ as $$
103
+ select private.genesis_support_handler(report, auth.uid())
104
+ $$;
105
+
106
+ comment on function public.support_handles(uuid) is
107
+ 'Whether the signed-in person handles this report (staff, or whom the app''s hook names). Genesis support.';
108
+ revoke execute on function public.support_handles(uuid) from public, anon;
109
+ grant execute on function public.support_handles(uuid) to authenticated;
110
+
111
+ drop policy if exists support_reports_read on public.support_reports;
112
+ create policy support_reports_read on public.support_reports
113
+ for select to authenticated
114
+ using (user_id = (select auth.uid()) or (select public.support_is_staff()) or public.support_handles(id));
115
+
116
+ drop policy if exists support_attachments_read on public.support_attachments;
117
+ create policy support_attachments_read on public.support_attachments
118
+ for select to authenticated
119
+ using (user_id = (select auth.uid()) or (select public.support_is_staff()) or public.support_handles(report_id));
120
+
121
+ drop policy if exists support_replies_read on public.support_replies;
122
+ create policy support_replies_read on public.support_replies
123
+ for select to authenticated
124
+ using (
125
+ (select public.support_is_staff()) or public.support_handles(report_id)
126
+ or exists (select 1 from public.support_reports r where r.id = report_id and r.user_id = (select auth.uid()))
127
+ );
128
+ drop policy if exists support_replies_send on public.support_replies;
129
+ create policy support_replies_send on public.support_replies
130
+ for insert to authenticated
131
+ with check (
132
+ (select public.support_is_staff()) or public.support_handles(report_id)
133
+ or exists (select 1 from public.support_reports r where r.id = report_id and r.user_id = (select auth.uid()))
134
+ );
135
+
136
+ -- Who wrote a reply, and whether as support, come from the session. A handler writes as support
137
+ -- on someone else's report. A reply the system posts (genesis_support_ask_to_verify, with
138
+ -- `prompt` set, which no person can write) isn't counted against the limit. With the support-email block installed, server code may write on
139
+ -- an email ticket and a ticket without a person takes support's replies only, as that block has it.
140
+ create or replace function private.genesis_support_new_reply()
141
+ returns trigger
142
+ language plpgsql
143
+ security definer
144
+ set search_path = ''
145
+ as $$
146
+ declare
147
+ me uuid := auth.uid();
148
+ report public.support_reports;
149
+ handles boolean;
150
+ begin
151
+ select * into report from public.support_reports r where r.id = new.report_id;
152
+ if report.id is null then
153
+ raise exception 'support: not your report' using errcode = '42501';
154
+ end if;
155
+ if me is null then
156
+ -- Server code (anon has no right on this table): only on an email ticket (support-email).
157
+ if coalesce(to_jsonb(report) ->> 'channel', '') <> 'email' then
158
+ raise exception 'support: not your report' using errcode = '42501';
159
+ end if;
160
+ new.author_id := null;
161
+ new.created_at := clock_timestamp();
162
+ return new;
163
+ end if;
164
+ handles := private.genesis_support_handler(new.report_id, me);
165
+ if report.user_id is null then
166
+ if not handles then
167
+ raise exception 'support: not your report' using errcode = '42501';
168
+ end if;
169
+ new.author_id := me;
170
+ new.from_staff := true;
171
+ else
172
+ if report.user_id <> me and not handles then
173
+ raise exception 'support: not your report' using errcode = '42501';
174
+ end if;
175
+ new.author_id := me;
176
+ -- On their own report a staff member writes as the person.
177
+ new.from_staff := handles and report.user_id <> me;
178
+ end if;
179
+ new.created_at := clock_timestamp();
180
+ if new.prompt is null then
181
+ perform private.genesis_support_rate_limit(me, 'reply', 60, interval '1 hour');
182
+ end if;
183
+ return new;
184
+ end;
185
+ $$;
186
+
187
+ revoke execute on function private.genesis_support_new_reply() from public, anon, authenticated;
188
+
189
+ -- Screenshots: a handler of the report the attachment row belongs to reads it too.
190
+ create or replace function public.support_can_read(object_name text, uploaded_at timestamptz)
191
+ returns boolean
192
+ language sql
193
+ stable
194
+ security definer
195
+ set search_path = ''
196
+ as $$
197
+ select auth.uid() is not null and (
198
+ exists (select 1 from public.support_attachments a
199
+ where a.path = object_name
200
+ and (split_part(object_name, '/', 1) = auth.uid()::text or public.support_is_staff()
201
+ or private.genesis_support_handler(a.report_id, auth.uid())))
202
+ or (split_part(object_name, '/', 1) = auth.uid()::text and uploaded_at > now() - interval '1 hour')
203
+ )
204
+ $$;
205
+
206
+ comment on function public.support_can_read(text, timestamptz) is
207
+ 'Whether the signed-in person may read this support screenshot (their own, or as staff or a handler). Genesis support.';
208
+
209
+ -- Status: staff, or a handler of the report.
210
+ create or replace function public.support_set_report_status(report uuid, status text, feature text default null)
211
+ returns void
212
+ language plpgsql
213
+ security definer
214
+ set search_path = ''
215
+ as $$
216
+ begin
217
+ if not private.genesis_support_handler(report, auth.uid()) then
218
+ raise exception 'support_set_report_status: only staff' using errcode = '42501';
219
+ end if;
220
+ update public.support_reports r
221
+ set status = support_set_report_status.status,
222
+ feature_id = case when feature = '' then null else coalesce(feature, r.feature_id) end
223
+ where r.id = report;
224
+ if not found then
225
+ raise exception 'support_set_report_status: no such report' using errcode = 'P0002';
226
+ end if;
227
+ end;
228
+ $$;
229
+
230
+ comment on function public.support_set_report_status(uuid, text, text) is
231
+ 'Staff or a handler set a report''s status and the FeatureId it is about. Genesis support.';
232
+
233
+ -- The verify loop ---------------------------------------------------------------------
234
+
235
+ -- Addressed or wont_fix: stamped, and not yet verified. Back to open or in progress: cleared.
236
+ create or replace function private.genesis_support_resolution()
237
+ returns trigger
238
+ language plpgsql
239
+ security definer
240
+ set search_path = ''
241
+ as $$
242
+ begin
243
+ if new.status in ('addressed', 'wont_fix') and old.status is distinct from new.status then
244
+ new.resolved_at := now();
245
+ new.verified_at := null;
246
+ elsif old.status in ('addressed', 'wont_fix') and new.status in ('open', 'submitted', 'in_progress') then
247
+ new.resolved_at := null;
248
+ new.verified_at := null;
249
+ end if;
250
+ return new;
251
+ end;
252
+ $$;
253
+
254
+ revoke execute on function private.genesis_support_resolution() from public, anon, authenticated;
255
+ drop trigger if exists genesis_support_resolution on public.support_reports;
256
+ create trigger genesis_support_resolution
257
+ before update of status on public.support_reports
258
+ for each row execute function private.genesis_support_resolution();
259
+
260
+ -- The verify prompt, only when the app's hook turns it on: someone other than the person marked
261
+ -- it addressed (a reply needs a session), so ask them to check it, at most once an hour per
262
+ -- report, so a status flipped back and forth can't flood the thread. The reply is the system's
263
+ -- (prompt = 'verify'): it doesn't count against the marker's reply limit. If a reply rule
264
+ -- refuses it (support-email's trigger applied after this file refuses a handler) or a limit
265
+ -- stops it, the status change still goes through, without the prompt.
266
+ create or replace function private.genesis_support_ask_to_verify()
267
+ returns trigger
268
+ language plpgsql
269
+ security definer
270
+ set search_path = ''
271
+ as $$
272
+ begin
273
+ -- A status set directly is depth 1; through support-chat's conversation sync, 2. Deeper is a
274
+ -- loop of triggers, never a person marking a fix.
275
+ if pg_trigger_depth() > 2 then
276
+ return null;
277
+ end if;
278
+ -- Two statements: one SQL expression may evaluate the call even when the hook is missing.
279
+ if to_regprocedure('private.genesis_support_verify_prompt_enabled()') is null then
280
+ return null;
281
+ end if;
282
+ if not coalesce(private.genesis_support_verify_prompt_enabled(), false) then
283
+ return null;
284
+ end if;
285
+ if auth.uid() is null or auth.uid() = new.user_id
286
+ or exists (select 1 from public.support_replies r
287
+ where r.report_id = new.id and r.prompt = 'verify' and r.created_at > now() - interval '1 hour') then
288
+ return null;
289
+ end if;
290
+ begin
291
+ insert into public.support_replies (report_id, body, prompt)
292
+ values (new.id, 'This is marked fixed. Please check it: confirm the fix, or reopen it if it isn''t fixed.', 'verify');
293
+ exception
294
+ when insufficient_privilege or sqlstate 'GS429' then
295
+ raise log 'genesis-support: the verify prompt for report % was not posted (%)', new.id, sqlerrm;
296
+ end;
297
+ return null;
298
+ end;
299
+ $$;
300
+
301
+ revoke execute on function private.genesis_support_ask_to_verify() from public, anon, authenticated;
302
+ drop trigger if exists genesis_support_ask_to_verify on public.support_reports;
303
+ create trigger genesis_support_ask_to_verify
304
+ after update of status on public.support_reports
305
+ for each row when (new.status = 'addressed' and old.status is distinct from 'addressed')
306
+ execute function private.genesis_support_ask_to_verify();
307
+
308
+ -- The person confirms the fix, or reopens the report (with what's still wrong, in the thread).
309
+ create or replace function public.support_verify_report(report uuid, fixed boolean, note text default null)
310
+ returns void
311
+ language plpgsql
312
+ security definer
313
+ set search_path = ''
314
+ as $$
315
+ declare
316
+ _r public.support_reports;
317
+ begin
318
+ select * into _r from public.support_reports where id = report;
319
+ if _r.id is null or _r.user_id is distinct from auth.uid() then
320
+ raise exception 'support_verify_report: not your report' using errcode = '42501';
321
+ end if;
322
+ if _r.status <> 'addressed' then
323
+ raise exception 'support_verify_report: it isn''t marked fixed' using errcode = '22023';
324
+ end if;
325
+ if nullif(btrim(note), '') is not null then
326
+ insert into public.support_replies (report_id, body) values (report, btrim(note));
327
+ end if;
328
+ if fixed then
329
+ update public.support_reports set verified_at = now() where id = report;
330
+ else
331
+ update public.support_reports set status = 'in_progress', reopened_at = now() where id = report;
332
+ end if;
333
+ end;
334
+ $$;
335
+
336
+ comment on function public.support_verify_report(uuid, boolean, text) is
337
+ 'The person confirms a fix, or reopens their report with an optional note. Genesis support.';
338
+ revoke execute on function public.support_verify_report(uuid, boolean, text) from public, anon;
339
+ grant execute on function public.support_verify_report(uuid, boolean, text) to authenticated;
@@ -1,4 +1,4 @@
1
- -- @feat:support-feedback @feat:feature-voting
1
+ -- @feat:support-feedback
2
2
  -- pgTAP test for 0006_genesis_support.sql.
3
3
  -- Copy into your app's `supabase/tests/database/` and run `supabase test db`.
4
4
  -- It writes only its own users, reports, ideas and storage rows and rolls everything back.