@marktiderman/genesis-supabase 0.10.1 → 0.12.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.
@@ -0,0 +1,260 @@
1
+ -- Genesis events: the app's own product events (ADR 0010).
2
+ --
3
+ -- public.genesis_events
4
+ -- One row per product event: when it happened, who (the login and, in a tenant, their person
5
+ -- record), where (the tenant), what (a short name and the feature id it belongs to), small
6
+ -- flat properties, the flags that were on, the platform and the app version. Properties are
7
+ -- labels and counts: no content someone typed, and identifiers only (the login and person
8
+ -- ids). Row security is on with no policies: only the service role reads it, and only the
9
+ -- functions below write it. Deleting a login (0001) clears its user_id.
10
+ --
11
+ -- public.genesis_track_events(events jsonb) returns integer
12
+ -- For a signed-in person. Takes a JSON array of at most 100 events and returns how many it
13
+ -- kept. An event naming a tenant the person has no record in (private.genesis_viewer_person_ids,
14
+ -- 0016) is dropped, as is one with a bad name or oversized properties; the person record is
15
+ -- filled in from the tenant. A client clock more than five minutes ahead or seven days behind
16
+ -- is replaced by now(). A person keeps at most 2,000 events an hour (SQLSTATE GS429 past it)
17
+ -- and a call is at most 512 KB; a client can't claim the `server` platform.
18
+ --
19
+ -- public.genesis_track_server_events(events jsonb) returns integer
20
+ -- For server code (service role only): the same shape, plus user_id and person_id, trusted as
21
+ -- given.
22
+ --
23
+ -- public.genesis_feature_usage(tenant uuid, since timestamptz) returns table
24
+ -- Per feature in a tenant since a time: events, distinct people, the last one. Service role
25
+ -- only; the product hub reads usage through it.
26
+ --
27
+ -- public.genesis_prune_events(older_than interval default '400 days', max_rows integer default 50000) returns bigint
28
+ -- Deletes up to max_rows older events and returns how many (call again until 0). Service role
29
+ -- only; run it from a schedule.
30
+ --
31
+ -- Needs 0016 (its private.genesis_viewer_person_ids, which reads the app's people hook).
32
+ --
33
+ -- Use: copy this file into your app's `supabase/migrations/` under a new timestamped name
34
+ -- (`genesis add events` does it). Never edit it once applied; change it with a new migration.
35
+ --
36
+ -- Verify: tests/0018_genesis_events.test.sql.
37
+
38
+ create table public.genesis_events (
39
+ id bigint generated always as identity primary key,
40
+ occurred_at timestamptz not null,
41
+ received_at timestamptz not null default now(),
42
+ -- The login, when there was one; null for an event server code raised for nobody in particular.
43
+ user_id uuid references auth.users (id) on delete set null,
44
+ tenant_id uuid,
45
+ person_id uuid,
46
+ name text not null
47
+ constraint genesis_events_name_format check (name ~ '^[a-z][a-z0-9]*([._:-][a-z0-9]+)*$' and char_length(name) <= 100),
48
+ -- The FeatureId it belongs to. No foreign key: an app's registry mirror may lag a deploy.
49
+ feature_id text
50
+ constraint genesis_events_feature_format check (feature_id is null or (feature_id ~ '^[a-z][a-z0-9]*([-_.][a-z0-9]+)*$' and char_length(feature_id) <= 100)),
51
+ -- Flat: { "count": 3, "view": "grid" }, no nested objects or lists.
52
+ properties jsonb not null default '{}'
53
+ constraint genesis_events_properties_object check (jsonb_typeof(properties) = 'object' and octet_length(properties::text) <= 4096
54
+ and not jsonb_path_exists(properties, '$.* ? (@.type() == "object" || @.type() == "array")')),
55
+ -- The flags that were on, { "flag-id": value }, so a reader can split by them.
56
+ flags jsonb not null default '{}'
57
+ constraint genesis_events_flags_object check (jsonb_typeof(flags) = 'object' and octet_length(flags::text) <= 2048),
58
+ platform text not null default 'web'
59
+ constraint genesis_events_platform check (platform in ('web', 'native', 'server')),
60
+ app_version text constraint genesis_events_app_version_length check (char_length(app_version) <= 40),
61
+ session_id text constraint genesis_events_session_length check (char_length(session_id) <= 64)
62
+ );
63
+
64
+ comment on table public.genesis_events is
65
+ 'Product events: who, where, which feature, when, small flat properties and the flags that were on. No content; identifiers only. Written through genesis_track_events and genesis_track_server_events; read by the service role. Genesis events.';
66
+
67
+ create index genesis_events_tenant_time on public.genesis_events (tenant_id, occurred_at desc);
68
+ create index genesis_events_feature_time on public.genesis_events (feature_id, occurred_at desc) where feature_id is not null;
69
+ create index genesis_events_name_time on public.genesis_events (name, occurred_at desc);
70
+ -- Append-only by time: a BRIN index keeps pruning old events cheap at any size.
71
+ create index genesis_events_occurred_brin on public.genesis_events using brin (occurred_at);
72
+ create index genesis_events_user_received on public.genesis_events (user_id, received_at desc) where user_id is not null;
73
+
74
+ alter table public.genesis_events enable row level security;
75
+ revoke all on table public.genesis_events from public, anon, authenticated;
76
+
77
+ -- One event from a JSON object, checked, or null when it can't be kept. Shared by both writers.
78
+ create or replace function private.genesis_event_row(e jsonb, trusted boolean)
79
+ returns public.genesis_events
80
+ language plpgsql
81
+ stable
82
+ set search_path = ''
83
+ as $$
84
+ declare
85
+ r public.genesis_events;
86
+ at timestamptz;
87
+ begin
88
+ if jsonb_typeof(e) is distinct from 'object' then
89
+ return null;
90
+ end if;
91
+ r.name := e ->> 'name';
92
+ r.feature_id := nullif(e ->> 'feature', '');
93
+ r.properties := coalesce(e -> 'properties', '{}');
94
+ r.flags := coalesce(e -> 'flags', '{}');
95
+ r.platform := coalesce(nullif(e ->> 'platform', ''), case when trusted then 'server' else 'web' end);
96
+ r.app_version := nullif(e ->> 'appVersion', '');
97
+ r.session_id := nullif(e ->> 'sessionId', '');
98
+ if r.name is null or r.name !~ '^[a-z][a-z0-9]*([._:-][a-z0-9]+)*$' or char_length(r.name) > 100
99
+ or (r.feature_id is not null and (r.feature_id !~ '^[a-z][a-z0-9]*([-_.][a-z0-9]+)*$' or char_length(r.feature_id) > 100))
100
+ or jsonb_typeof(r.properties) <> 'object' or octet_length(r.properties::text) > 4096
101
+ or jsonb_path_exists(r.properties, '$.* ? (@.type() == "object" || @.type() == "array")')
102
+ or jsonb_typeof(r.flags) <> 'object' or octet_length(r.flags::text) > 2048
103
+ or r.platform not in ('web', 'native', 'server') or (r.platform = 'server' and not trusted)
104
+ or char_length(r.app_version) > 40 or char_length(r.session_id) > 64 then
105
+ return null;
106
+ end if;
107
+ begin
108
+ at := (e ->> 'occurredAt')::timestamptz;
109
+ exception when others then
110
+ at := null;
111
+ end;
112
+ r.occurred_at := case when at is null or at > now() + interval '5 minutes' or at < now() - interval '7 days' then now() else at end;
113
+ r.received_at := now();
114
+ begin
115
+ r.tenant_id := nullif(e ->> 'tenantId', '')::uuid;
116
+ if trusted then
117
+ r.user_id := nullif(e ->> 'userId', '')::uuid;
118
+ r.person_id := nullif(e ->> 'personId', '')::uuid;
119
+ end if;
120
+ exception when others then
121
+ return null;
122
+ end;
123
+ return r;
124
+ end;
125
+ $$;
126
+
127
+ revoke execute on function private.genesis_event_row(jsonb, boolean) from public, anon, authenticated;
128
+
129
+ create or replace function public.genesis_track_events(events jsonb)
130
+ returns integer
131
+ language plpgsql
132
+ volatile
133
+ security definer
134
+ set search_path = ''
135
+ as $$
136
+ declare
137
+ e jsonb;
138
+ r public.genesis_events;
139
+ kept integer := 0;
140
+ viewer uuid := auth.uid();
141
+ begin
142
+ if viewer is null then
143
+ raise exception 'genesis_track_events: sign in first' using errcode = '42501';
144
+ end if;
145
+ -- One login's calls take turns, so two at once can't both pass the hourly limit.
146
+ perform pg_advisory_xact_lock(hashtextextended('genesis_events:' || viewer::text, 0));
147
+ if jsonb_typeof(events) is distinct from 'array' or jsonb_array_length(events) > 100 or octet_length(events::text) > 524288 then
148
+ raise exception 'genesis_track_events: send a JSON array of at most 100 events and 512 KB' using errcode = '22023';
149
+ end if;
150
+ -- At most 2,000 kept events per login per hour, so one login can't fill the table.
151
+ if (select count(*) from public.genesis_events g where g.user_id = viewer and g.received_at > now() - interval '1 hour') + jsonb_array_length(events) > 2000 then
152
+ raise exception 'genesis_track_events: too many events this hour' using errcode = 'GS429';
153
+ end if;
154
+ for e in select value from jsonb_array_elements(events) loop
155
+ r := private.genesis_event_row(e, false);
156
+ continue when r is null;
157
+ r.user_id := viewer;
158
+ if r.tenant_id is not null then
159
+ -- Only a tenant the person has a record in, and that record is who they were there.
160
+ select v.person_id into r.person_id from private.genesis_viewer_person_ids() v where v.tenant_id = r.tenant_id order by v.person_id limit 1;
161
+ continue when r.person_id is null;
162
+ end if;
163
+ insert into public.genesis_events (occurred_at, received_at, user_id, tenant_id, person_id, name, feature_id, properties, flags, platform, app_version, session_id)
164
+ values (r.occurred_at, r.received_at, r.user_id, r.tenant_id, r.person_id, r.name, r.feature_id, r.properties, r.flags, r.platform, r.app_version, r.session_id);
165
+ kept := kept + 1;
166
+ end loop;
167
+ return kept;
168
+ end;
169
+ $$;
170
+
171
+ comment on function public.genesis_track_events(jsonb) is
172
+ 'Records a signed-in person''s product events (a JSON array of at most 100); returns how many were kept. Events in a tenant the person has no record in, or that fail the checks, are dropped. Genesis events.';
173
+
174
+ revoke execute on function public.genesis_track_events(jsonb) from public, anon;
175
+ grant execute on function public.genesis_track_events(jsonb) to authenticated;
176
+
177
+ create or replace function public.genesis_track_server_events(events jsonb)
178
+ returns integer
179
+ language plpgsql
180
+ volatile
181
+ security definer
182
+ set search_path = ''
183
+ as $$
184
+ declare
185
+ e jsonb;
186
+ r public.genesis_events;
187
+ kept integer := 0;
188
+ begin
189
+ if jsonb_typeof(events) is distinct from 'array' or jsonb_array_length(events) > 1000 or octet_length(events::text) > 4194304 then
190
+ raise exception 'genesis_track_server_events: send a JSON array of at most 1000 events' using errcode = '22023';
191
+ end if;
192
+ for e in select value from jsonb_array_elements(events) loop
193
+ r := private.genesis_event_row(e, true);
194
+ continue when r is null;
195
+ -- A login that no longer exists (or never did) is kept as no login, not an error for the batch.
196
+ if r.user_id is not null and not exists (select 1 from auth.users u where u.id = r.user_id) then
197
+ r.user_id := null;
198
+ end if;
199
+ insert into public.genesis_events (occurred_at, received_at, user_id, tenant_id, person_id, name, feature_id, properties, flags, platform, app_version, session_id)
200
+ values (r.occurred_at, r.received_at, r.user_id, r.tenant_id, r.person_id, r.name, r.feature_id, r.properties, r.flags, r.platform, r.app_version, r.session_id);
201
+ kept := kept + 1;
202
+ end loop;
203
+ return kept;
204
+ end;
205
+ $$;
206
+
207
+ comment on function public.genesis_track_server_events(jsonb) is
208
+ 'Records product events from server code (service role): userId, tenantId and personId are trusted as given. Returns how many were kept. Genesis events.';
209
+
210
+ revoke execute on function public.genesis_track_server_events(jsonb) from public, anon, authenticated;
211
+ grant execute on function public.genesis_track_server_events(jsonb) to service_role;
212
+
213
+ create or replace function public.genesis_feature_usage(tenant uuid, since timestamptz)
214
+ returns table (feature_id text, events bigint, people bigint, last_at timestamptz)
215
+ language sql
216
+ stable
217
+ security definer
218
+ set search_path = ''
219
+ as $$
220
+ -- Two branches so each uses genesis_events_tenant_time: one tenant, or the events with none.
221
+ select e.feature_id, count(*), count(distinct coalesce(e.person_id, e.user_id)), max(e.occurred_at)
222
+ from public.genesis_events e
223
+ where tenant is not null and e.tenant_id = tenant and e.occurred_at >= since and e.feature_id is not null
224
+ group by e.feature_id
225
+ union all
226
+ select e.feature_id, count(*), count(distinct coalesce(e.person_id, e.user_id)), max(e.occurred_at)
227
+ from public.genesis_events e
228
+ where tenant is null and e.tenant_id is null and e.occurred_at >= since and e.feature_id is not null
229
+ group by e.feature_id
230
+ order by 2 desc
231
+ $$;
232
+
233
+ comment on function public.genesis_feature_usage(uuid, timestamptz) is
234
+ 'Per feature in a tenant since a time: events, distinct people and the last event. Service role only. Genesis events.';
235
+
236
+ revoke execute on function public.genesis_feature_usage(uuid, timestamptz) from public, anon, authenticated;
237
+ grant execute on function public.genesis_feature_usage(uuid, timestamptz) to service_role;
238
+
239
+ create or replace function public.genesis_prune_events(older_than interval default '400 days', max_rows integer default 50000)
240
+ returns bigint
241
+ language sql
242
+ volatile
243
+ security definer
244
+ set search_path = ''
245
+ as $$
246
+ -- At most max_rows per call, so one run never holds a long lock; call again until it returns 0.
247
+ with gone as (
248
+ delete from public.genesis_events
249
+ where id in (select e.id from public.genesis_events e
250
+ where older_than > interval '0' and e.occurred_at < now() - older_than
251
+ limit greatest(1, least(max_rows, 500000)))
252
+ returning 1)
253
+ select count(*) from gone
254
+ $$;
255
+
256
+ comment on function public.genesis_prune_events(interval, integer) is
257
+ 'Deletes up to max_rows (default 50,000) events older than older_than (default 400 days) and returns how many; call again until 0. Service role only; run it from a schedule. Genesis events.';
258
+
259
+ revoke execute on function public.genesis_prune_events(interval, integer) from public, anon, authenticated;
260
+ grant execute on function public.genesis_prune_events(interval, integer) to service_role;
@@ -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.
@@ -0,0 +1,147 @@
1
+ -- @feat:events
2
+ -- pgTAP test for 0018_genesis_events.sql (needs 0016).
3
+ -- Copy into your app's `supabase/tests/database/` and run `supabase test db`.
4
+ -- It writes only its own users, hook and events and rolls everything back. If your app already has
5
+ -- the people hook, it is dropped and replaced inside this transaction only.
6
+ begin;
7
+ create extension if not exists pgtap with schema extensions;
8
+ select plan(32);
9
+
10
+ insert into auth.users (id, aud, role, email, instance_id)
11
+ select ('00000000-0000-4000-8000-0000000018' || n)::uuid, 'authenticated', 'authenticated', 'genesis-events-' || n || '@example.test', '00000000-0000-0000-0000-000000000000'
12
+ from unnest(array['a1', 'b2']) n;
13
+
14
+ create function pg_temp.login(n text) returns uuid language sql immutable as $$ select ('00000000-0000-4000-8000-0000000018' || n)::uuid $$;
15
+ create function pg_temp.as_person(n text) returns void language plpgsql as $$
16
+ begin
17
+ perform set_config('request.jwt.claims', json_build_object('sub', pg_temp.login(n), 'role', 'authenticated')::text, true);
18
+ perform set_config('request.jwt.claim.sub', pg_temp.login(n)::text, true);
19
+ execute 'set local role authenticated';
20
+ end $$;
21
+ create function pg_temp.as_owner() returns void language plpgsql as $$
22
+ begin
23
+ execute 'reset role';
24
+ perform set_config('request.jwt.claims', '', true);
25
+ perform set_config('request.jwt.claim.sub', '', true);
26
+ end $$;
27
+ grant execute on function pg_temp.login(text), pg_temp.as_person(text), pg_temp.as_owner() to authenticated, anon, service_role;
28
+
29
+ -- a1 is a person in tenant 1 only.
30
+ drop function if exists private.genesis_viewer_people(uuid);
31
+ create function private.genesis_viewer_people(viewer uuid)
32
+ returns table (tenant_id uuid, person_id uuid) language sql stable set search_path = '' as $$
33
+ select '00000000-0000-4000-8000-000000000001'::text::uuid, '00000000-0000-4000-8000-000000000101'::text::uuid
34
+ where viewer = '00000000-0000-4000-8000-0000000018a1'
35
+ $$;
36
+
37
+ -- Privileges --------------------------------------------------------------------------------------
38
+ select ok(not has_table_privilege('authenticated', 'public.genesis_events', 'select'), 'a person can''t read events');
39
+ select ok(not has_table_privilege('authenticated', 'public.genesis_events', 'insert'), '... or insert them directly');
40
+ select ok(not has_function_privilege('anon', 'public.genesis_track_events(jsonb)', 'execute'), 'anon can''t track');
41
+ select ok(has_function_privilege('authenticated', 'public.genesis_track_events(jsonb)', 'execute'), 'a signed-in person can');
42
+ select ok(not has_function_privilege('authenticated', 'public.genesis_track_server_events(jsonb)', 'execute'), 'server tracking is the service role''s');
43
+ select ok(not has_function_privilege('authenticated', 'public.genesis_feature_usage(uuid, timestamptz)', 'execute'), 'usage summaries are the service role''s');
44
+ select ok(not has_function_privilege('authenticated', 'public.genesis_prune_events(interval, integer)', 'execute'), 'pruning is the service role''s');
45
+ select ok(not has_function_privilege('anon', 'public.genesis_track_server_events(jsonb)', 'execute')
46
+ and not has_function_privilege('anon', 'public.genesis_feature_usage(uuid, timestamptz)', 'execute')
47
+ and not has_function_privilege('anon', 'public.genesis_prune_events(interval, integer)', 'execute'), 'anon reaches none of the service functions');
48
+ select ok(not has_function_privilege('authenticated', 'private.genesis_event_row(jsonb, boolean)', 'execute')
49
+ and not has_function_privilege('anon', 'private.genesis_event_row(jsonb, boolean)', 'execute'), 'nobody but the owner calls the row check');
50
+
51
+ -- Tracking as a person ----------------------------------------------------------------------------
52
+ select pg_temp.as_person('a1');
53
+ select is(
54
+ public.genesis_track_events(jsonb_build_array(
55
+ jsonb_build_object('name', 'task.completed', 'feature', 'tasks', 'tenantId', '00000000-0000-4000-8000-000000000001', 'properties', jsonb_build_object('count', 3), 'flags', jsonb_build_object('new-list', true), 'platform', 'native', 'appVersion', '1.2.0'),
56
+ jsonb_build_object('name', 'app.opened'),
57
+ -- a tenant a1 has no record in: dropped
58
+ jsonb_build_object('name', 'task.completed', 'feature', 'tasks', 'tenantId', '00000000-0000-4000-8000-000000000002'),
59
+ -- a bad name, oversized properties, a bad platform: dropped
60
+ jsonb_build_object('name', 'Has Spaces'),
61
+ jsonb_build_object('name', 'big', 'properties', jsonb_build_object('text', repeat('x', 5000))),
62
+ jsonb_build_object('name', 'odd', 'platform', 'fridge'),
63
+ '"not an object"'::jsonb
64
+ )),
65
+ 2, 'keeps the valid events in the person''s own tenants, drops the rest');
66
+ select throws_ok($$select public.genesis_track_events('{}'::jsonb)$$, '22023', null, 'refuses a body that isn''t an array');
67
+ select throws_ok(
68
+ $$select public.genesis_track_events((select jsonb_agg(jsonb_build_object('name', 'x')) from generate_series(1, 101)))$$,
69
+ '22023', null, '... and more than 100 events');
70
+ -- What a client can't claim: another login or person, the server platform, nested properties.
71
+ select is(
72
+ public.genesis_track_events(jsonb_build_array(
73
+ jsonb_build_object('name', 'forged.ids', 'tenantId', '00000000-0000-4000-8000-000000000001', 'userId', pg_temp.login('b2'), 'personId', '00000000-0000-4000-8000-000000000999'),
74
+ jsonb_build_object('name', 'forged.platform', 'platform', 'server'),
75
+ jsonb_build_object('name', 'nested', 'properties', jsonb_build_object('a', jsonb_build_object('b', 1)))
76
+ )),
77
+ 1, 'drops the server platform and nested properties from a client');
78
+ select pg_temp.as_owner();
79
+ select is(
80
+ (select user_id::text || ' ' || person_id::text from public.genesis_events where name = 'forged.ids'),
81
+ pg_temp.login('a1')::text || ' 00000000-0000-4000-8000-000000000101',
82
+ 'the login and person come from the session and the hook, never from the event');
83
+
84
+ select is((select person_id from public.genesis_events where name = 'task.completed'), '00000000-0000-4000-8000-000000000101'::uuid, 'the person record comes from the tenant');
85
+ select is((select user_id from public.genesis_events where name = 'app.opened'), pg_temp.login('a1'), 'the login is the caller, whatever the client says');
86
+ select is((select tenant_id from public.genesis_events where name = 'app.opened'), null, 'an event with no tenant keeps none');
87
+ select is((select platform || ' ' || app_version || ' ' || (flags ->> 'new-list') from public.genesis_events where name = 'task.completed'), 'native 1.2.0 true', 'platform, version and flags are kept');
88
+
89
+ -- A clock far off is replaced by now().
90
+ select pg_temp.as_person('a1');
91
+ select public.genesis_track_events(jsonb_build_array(jsonb_build_object('name', 'clock.check', 'occurredAt', '2001-01-01T00:00:00Z')));
92
+ select pg_temp.as_owner();
93
+ select ok((select occurred_at > now() - interval '1 minute' from public.genesis_events where name = 'clock.check'), 'an implausible client time becomes now()');
94
+
95
+ -- Signed out, anon and no role ----------------------------------------------------------------------
96
+ select set_config('request.jwt.claims', '', true);
97
+ select set_config('request.jwt.claim.sub', '', true);
98
+ set local role authenticated;
99
+ select throws_ok($$select public.genesis_track_events('[]'::jsonb)$$, '42501', null, 'tracking needs a signed-in person');
100
+ reset role;
101
+ set local role anon;
102
+ select throws_ok($$select public.genesis_track_events('[]'::jsonb)$$, '42501', null, 'anon can''t track');
103
+ reset role;
104
+ select throws_ok($$select public.genesis_track_events('[]'::jsonb)$$, '42501', null, 'no login and no role: refused');
105
+
106
+ -- Without the people hook, an event naming a tenant is dropped.
107
+ drop function private.genesis_viewer_people(uuid);
108
+ select pg_temp.as_person('a1');
109
+ select is(public.genesis_track_events(jsonb_build_array(jsonb_build_object('name', 'no.hook', 'tenantId', '00000000-0000-4000-8000-000000000001'))), 0, 'no hook: a tenant event is dropped');
110
+ select throws_ok(
111
+ $$select public.genesis_track_events((select jsonb_agg(jsonb_build_object('name', 'x', 'properties', jsonb_build_object('t', repeat('y', 6000)))) from generate_series(1, 100)))$$,
112
+ '22023', null, 'a call over 512 KB is refused before it is read');
113
+ select pg_temp.as_owner();
114
+ insert into public.genesis_events (occurred_at, user_id, name) select now(), pg_temp.login('a1'), 'flood' from generate_series(1, 2000);
115
+ select pg_temp.as_person('a1');
116
+ select throws_ok($$select public.genesis_track_events('[{"name":"one.more"}]'::jsonb)$$, 'GS429', null, 'past 2,000 events an hour a login is refused');
117
+ select pg_temp.as_owner();
118
+ delete from public.genesis_events where name = 'flood';
119
+
120
+ -- Server code -------------------------------------------------------------------------------------
121
+ set local role service_role;
122
+ select is(
123
+ public.genesis_track_server_events(jsonb_build_array(
124
+ jsonb_build_object('name', 'invoice.sent', 'feature', 'invoicing', 'tenantId', '00000000-0000-4000-8000-000000000002', 'personId', '00000000-0000-4000-8000-000000000109', 'userId', pg_temp.login('b2')),
125
+ jsonb_build_object('name', 'invoice.sent', 'feature', 'invoicing', 'tenantId', 'not-a-uuid'),
126
+ jsonb_build_object('name', 'ghost.user', 'userId', '00000000-0000-4000-8000-00000000dead')
127
+ )),
128
+ 2, 'server events trust tenant, person and user, and still drop a malformed one');
129
+ select is(
130
+ (select events::int || ' ' || people::int from public.genesis_feature_usage('00000000-0000-4000-8000-000000000001', now() - interval '1 day') where feature_id = 'tasks'),
131
+ '1 1', 'feature usage counts events and people per feature in a tenant');
132
+ reset role;
133
+
134
+ update public.genesis_events set occurred_at = now() - interval '500 days' where name = 'app.opened';
135
+ set local role service_role;
136
+ select is(public.genesis_prune_events(), 1::bigint, 'pruning deletes events past the retention window');
137
+ reset role;
138
+ select is((select count(*)::int from public.genesis_events where name = 'app.opened'), 0, '... and only those');
139
+ set local role service_role;
140
+ select is(public.genesis_prune_events(interval '0'), 0::bigint, 'a zero window deletes nothing');
141
+ reset role;
142
+ select is((select user_id from public.genesis_events where name = 'ghost.user'), null, 'an unknown login is kept as none');
143
+ delete from auth.users where id = pg_temp.login('a1');
144
+ select is((select count(*)::int from public.genesis_events where user_id is null and name = 'task.completed'), 1, 'deleting a login clears its user_id');
145
+
146
+ select * from finish();
147
+ rollback;
package/package.json CHANGED
@@ -1,10 +1,31 @@
1
1
  {
2
2
  "name": "@marktiderman/genesis-supabase",
3
- "version": "0.10.1",
3
+ "version": "0.12.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
7
  "description": "Supabase for Genesis apps on web and React Native: a client with PKCE and safe defaults, Keychain session storage that survives interrupted writes, refresh only while the app is in front, native Sign in with Apple and Google, OAuth redirects, in-app account deletion, per-tenant feature switches (tenant_features), a background-job queue with schedules (genesis_jobs) on one outbox engine (/runner, shared with notifications and forms), the feature registry in the database for the feature gate (features, entitlements, flag values, feature_on), a native-to-web sign-in handoff (continue on the web, already signed in: web-handoff), and a result helper. Part of the Genesis framework.",
8
+ "keywords": [
9
+ "genesis",
10
+ "genesis-framework",
11
+ "supabase",
12
+ "auth",
13
+ "postgres",
14
+ "rls",
15
+ "sign-in",
16
+ "account-deletion",
17
+ "apple",
18
+ "feature-toggle",
19
+ "per-tenant",
20
+ "organization-settings",
21
+ "background-jobs",
22
+ "cron",
23
+ "queue"
24
+ ],
25
+ "homepage": "https://github.com/marktiderman/genesis/tree/main/packages/supabase#readme",
26
+ "bugs": {
27
+ "url": "https://github.com/marktiderman/genesis/issues"
28
+ },
8
29
  "repository": {
9
30
  "type": "git",
10
31
  "url": "git+https://github.com/marktiderman/genesis.git",
@@ -36,6 +57,10 @@
36
57
  "types": "./dist/jobs.d.ts",
37
58
  "import": "./dist/jobs.js"
38
59
  },
60
+ "./events": {
61
+ "types": "./dist/events.d.ts",
62
+ "import": "./dist/events.js"
63
+ },
39
64
  "./runner": {
40
65
  "types": "./dist/runner.d.ts",
41
66
  "import": "./dist/runner.js"
@@ -57,7 +82,7 @@
57
82
  "README.md"
58
83
  ],
59
84
  "dependencies": {
60
- "@marktiderman/genesis-features": "^0.7.0"
85
+ "@marktiderman/genesis-features": "^0.8.1"
61
86
  },
62
87
  "peerDependencies": {
63
88
  "@supabase/supabase-js": "^2.118.0",
@@ -67,9 +92,12 @@
67
92
  "@supabase/supabase-js": "^2.118.0",
68
93
  "tsup": "^8.3.0",
69
94
  "typescript": "~6.0.3",
70
- "vitest": "^4.1.12"
95
+ "vitest": "^5.0.5"
71
96
  },
72
97
  "genesis": {
98
+ "layer": "primitive",
99
+ "group": "data",
100
+ "owner": "@marktiderman",
73
101
  "blocks": {
74
102
  "account": {
75
103
  "feature": {
@@ -243,6 +271,37 @@
243
271
  "Add the /auth/handoff page: call takeWebHandoffFragment before analytics or error reporting load, then completeWebHandoff; send Referrer-Policy: no-referrer and frame-ancestors 'none' for it.",
244
272
  "In the native app, call openOnWeb from @marktiderman/genesis-native/web-handoff with the mint route, the session's access token and expo-web-browser."
245
273
  ]
274
+ },
275
+ "events": {
276
+ "feature": {
277
+ "name": "Product events",
278
+ "summary": "The app's own product events in Postgres: who used which feature, in which tenant, when, with the flags that were on; tracked from web, native and server.",
279
+ "keywords": [
280
+ "analytics",
281
+ "events",
282
+ "usage",
283
+ "telemetry",
284
+ "activation"
285
+ ],
286
+ "audience": [
287
+ "developer",
288
+ "admin"
289
+ ]
290
+ },
291
+ "migrations": [
292
+ {
293
+ "file": "migrations/0018_genesis_events.sql",
294
+ "test": "migrations/tests/0018_genesis_events.test.sql"
295
+ }
296
+ ],
297
+ "steps": [
298
+ "Track from the client with createEventTracker from @marktiderman/genesis-supabase/events (and createEventsSink on native). Events in a tenant count only when the app defines the private.genesis_viewer_people hook (0016).",
299
+ "Schedule genesis_prune_events() (default 400 days) from your jobs, e.g. a monthly genesis_schedule_job."
300
+ ],
301
+ "platforms": [
302
+ "web",
303
+ "native"
304
+ ]
246
305
  }
247
306
  },
248
307
  "doctor": {
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/blocks.ts"],"names":[],"mappings":"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","file":"chunk-FWQGZT4S.js","sourcesContent":["/**\n * The blocks this package carries the server half of, as `defineBlock`\n * declarations: what each needs in the database, and what it means for the\n * stores' privacy forms. The functions themselves (`deleteMyAccount`,\n * `tenantFeatures`, …) don't change.\n */\nimport { defineBlock } from \"@marktiderman/genesis-features/blocks\";\n\nconst PACKAGE = \"@marktiderman/genesis-supabase\";\n\n/**\n * The account block: sign-in, profile and in-app account deletion. Its\n * screens are the app's (or genesis-ui-native's `AuthScreen`); this names its\n * migrations and its data.\n *\n * @stability Beta\n */\nexport const accountBlock = defineBlock({\n id: \"account\",\n platforms: [\"web\", \"native\"],\n contributes: {\n migrations: [\n {\n package: PACKAGE,\n file: \"migrations/0001_genesis_account_deletion.sql\",\n test: \"migrations/tests/0001_genesis_account_deletion.test.sql\",\n },\n // With Sign in with Apple, with the genesis-apple-revoke function beside it.\n {\n package: PACKAGE,\n file: \"migrations/0003_genesis_apple_token_revocation.sql\",\n test: \"migrations/tests/0003_genesis_apple_token_revocation.test.sql\",\n },\n ],\n privacy: {\n collects: [\n {\n type: \"email address\",\n purposes: [\"app functionality\"],\n linked: true,\n tracking: false,\n },\n {\n type: \"user id\",\n purposes: [\"app functionality\"],\n linked: true,\n tracking: false,\n },\n {\n type: \"name\",\n purposes: [\"app functionality\"],\n linked: true,\n tracking: false,\n },\n ],\n notes: [\n \"People delete their account from inside the app; their login and the rows that cascade from it go with it.\",\n \"With Sign in with Apple, the person's Apple tokens are revoked when the account is deleted.\",\n ],\n },\n },\n});\n\n/**\n * The tenant features block: per-tenant on/off switches for shipped\n * features, set by the tenant's admins with a reason.\n *\n * @stability Beta\n */\nexport const tenantFeaturesBlock = defineBlock({\n id: \"tenant-features\",\n contributes: {\n migrations: [\n {\n package: PACKAGE,\n file: \"migrations/0004_genesis_tenant_features.sql\",\n test: \"migrations/tests/0004_genesis_tenant_features.test.sql\",\n },\n ],\n privacy: {\n notes: [\n \"Keeps who changed a tenant's switches; a deleted person's changes stay, without the person.\",\n ],\n },\n },\n});\n\n/**\n * The feature registry block: the registry mirrored into the app's database\n * on deploy, entitlements, per-tenant and platform flag values and SQL `feature_on()`,\n * for the feature gate. Needs the tenant features block.\n *\n * @stability Beta\n */\nexport const featureMirrorBlock = defineBlock({\n id: \"feature-mirror\",\n requires: [\"tenant-features\"],\n contributes: {\n migrations: [\n {\n package: PACKAGE,\n file: \"migrations/0008_genesis_feature_registry.sql\",\n test: \"migrations/tests/0008_genesis_feature_registry.test.sql\",\n },\n {\n package: PACKAGE,\n file: \"migrations/0014_genesis_feature_registry_hardening.sql\",\n test: \"migrations/tests/0014_genesis_feature_registry_hardening.test.sql\",\n },\n { package: PACKAGE, file: \"migrations/0016_genesis_viewer_people.sql\", test: \"migrations/tests/0016_genesis_viewer_people.test.sql\" },\n {\n package: PACKAGE,\n file: \"migrations/0017_genesis_person_entitlements.sql\",\n test: \"migrations/tests/0017_genesis_person_entitlements.test.sql\",\n },\n ],\n privacy: {\n notes: [\n \"Stores which tenants and which people (the app's person ids) hold which paid features, and flag values.\",\n ],\n },\n },\n});\n\n/**\n * The jobs block: a background-job queue and named schedules that call the\n * app's job route. Server only; the route is `createJobsHandler` from `/jobs`.\n *\n * @stability Beta\n */\nexport const jobsBlock = defineBlock({\n id: \"jobs\",\n platforms: [\"web\"],\n contributes: {\n migrations: [{ package: PACKAGE, file: \"migrations/0007_genesis_jobs.sql\", test: \"migrations/tests/0007_genesis_jobs.test.sql\" }],\n privacy: { notes: [\"Job payloads hold ids, never content or secrets; finished jobs are deleted after 14 days.\"] },\n },\n});\n\n/**\n * The web handoff block: continue on the web, already signed in. The routes are\n * `createWebHandoff` from `/web-handoff/server`, the page uses `/web-handoff`, and the native\n * app calls `openOnWeb` from genesis-native.\n *\n * @stability Beta\n */\nexport const webHandoffBlock = defineBlock({\n id: \"web-handoff\",\n platforms: [\"web\", \"native\"],\n contributes: {\n migrations: [\n { package: PACKAGE, file: \"migrations/0015_genesis_web_handoff.sql\", test: \"migrations/tests/0015_genesis_web_handoff.test.sql\" },\n ],\n privacy: {\n notes: [\n \"Logs each handoff (who, which page, when) for 30 days; keeps a SHA-256 digest of each link's token, never the token or a sign-in token.\",\n ],\n },\n },\n});\n\n"]}