-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathschema.sql
More file actions
408 lines (346 loc) · 14.8 KB
/
Copy pathschema.sql
File metadata and controls
408 lines (346 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
-- ownSheets: complete database schema
-- Run this once against a fresh Supabase project (SQL Editor -> Run).
-- Tested on Postgres 15 / Supabase projects created after 2026-05-30.
-- Extensions
create extension if not exists pgcrypto;
-- Tables
-- sheets: one row per PDF, owned by a single auth user.
create table public.sheets (
id uuid primary key default gen_random_uuid(),
owner_id uuid not null references auth.users(id) on delete cascade,
title text not null,
composer text,
arranger text,
key text,
difficulty smallint check (difficulty between 1 and 10),
page_count int,
file_path text not null,
notes text,
tags text[] not null default '{}',
search tsvector, -- maintained by trigger below
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
create index sheets_tags_gin on public.sheets using gin(tags);
create index sheets_search_gin on public.sheets using gin(search);
-- setlists: named, ordered collections of sheets.
create table public.setlists (
id uuid primary key default gen_random_uuid(),
owner_id uuid not null references auth.users(id) on delete cascade,
name text not null,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
-- setlist_items: junction table preserving sheet order within a setlist.
create table public.setlist_items (
setlist_id uuid not null references public.setlists(id) on delete cascade,
sheet_id uuid not null references public.sheets(id) on delete cascade,
position int not null,
primary key (setlist_id, sheet_id)
);
-- annotations: per-page overlay data (phase 2: table present now, used later).
create table public.annotations (
id uuid primary key default gen_random_uuid(),
owner_id uuid not null references auth.users(id) on delete cascade,
sheet_id uuid not null references public.sheets(id) on delete cascade,
page int not null,
data jsonb not null default '{}',
updated_at timestamptz not null default now()
);
-- access_codes: guest access codes created by the owner, stored as SHA-256 hashes.
create table public.access_codes (
id uuid primary key default gen_random_uuid(),
label text not null,
code_hash text not null unique,
created_at timestamptz not null default now()
);
-- validated_guests: one row per browser/device that has validated a code.
-- device_id is a UUID stored in localStorage, stable across sign-out/sign-in cycles.
-- user_id holds the current anonymous Supabase user (updated on re-authentication).
-- Deleting a code cascade-deletes all device rows for instant access revocation.
create table public.validated_guests (
device_id text primary key,
user_id uuid not null,
code_id uuid not null references public.access_codes(id) on delete cascade,
created_at timestamptz not null default now(),
last_seen_at timestamptz not null default now(),
download_count int not null default 0,
download_bytes bigint not null default 0
);
create index validated_guests_user_id_idx on public.validated_guests(user_id);
-- app_config: single-row table holding the owner's email.
-- Read only by the is_owner() security-definer function (no API access at all),
-- so it is how the database knows which signed-in account is the real owner.
-- You MUST insert your owner email once after running this schema, see the
-- setup note just below the is_owner() function.
create table public.app_config (
id smallint primary key default 1 check (id = 1),
owner_email text not null
);
-- Full-text search trigger
create function public.sheets_search_update()
returns trigger
language plpgsql
set search_path = public
as $$
begin
new.search := to_tsvector(
'english'::regconfig,
coalesce(new.title, '') || ' ' ||
coalesce(new.composer, '') || ' ' ||
array_to_string(new.tags, ' ')
);
return new;
end;
$$;
create trigger sheets_search_update
before insert or update on public.sheets
for each row execute function public.sheets_search_update();
-- Auth helper functions
-- validate_guest_code: called by the frontend after anonymous sign-in.
-- Checks the SHA-256 hash against access_codes; on success writes a validated_guests row so RLS policies can recognise this anonymous user.
create function public.validate_guest_code(p_code_hash text, p_device_id text)
returns boolean
language plpgsql
security definer
set search_path = public
as $$
declare
v_code_id uuid;
begin
select id into v_code_id
from public.access_codes
where code_hash = p_code_hash;
if v_code_id is null then
return false;
end if;
-- Upsert by device_id so the same browser always maps to the same row, even after sign-out. user_id is updated to the current anonymous session.
insert into public.validated_guests (device_id, user_id, code_id, last_seen_at)
values (p_device_id, auth.uid(), v_code_id, now())
on conflict (device_id) do update
set user_id = auth.uid(),
code_id = v_code_id,
last_seen_at = now();
return true;
end;
$$;
-- touch_guest_session: called when a guest opens the app to update last_seen_at.
create function public.touch_guest_session()
returns void
language sql
security definer
set search_path = public
as $$
update public.validated_guests set last_seen_at = now() where user_id = auth.uid();
$$;
-- record_guest_download: increments download_count and adds file bytes for the calling guest device.
create function public.record_guest_download(p_bytes bigint default 0)
returns void
language sql
security definer
set search_path = public
as $$
update public.validated_guests
set download_count = download_count + 1,
download_bytes = download_bytes + p_bytes
where user_id = auth.uid();
$$;
-- record_guest_egress: adds bytes to egress tracking without incrementing download_count.
-- Called when Supabase Storage serves a PDF to a guest (thumbnail generation or PDF viewing).
create function public.record_guest_egress(p_bytes bigint default 0)
returns void
language sql
security definer
set search_path = public
as $$
update public.validated_guests
set download_bytes = download_bytes + p_bytes
where user_id = auth.uid();
$$;
-- get_storage_usage: returns total bytes used in the sheets bucket.
-- Called by the owner's Settings page to show the storage progress bar.
create function public.get_storage_usage()
returns bigint
language sql
security definer
stable
set search_path = storage, public
as $$
select coalesce(sum((metadata->>'size')::bigint), 0)
from storage.objects
where bucket_id = 'sheets' and public.is_owner();
$$;
-- is_validated_guest: stable helper called inside RLS policies.
-- Stable + security definer means the sub-select runs once per query, not per row.
create function public.is_validated_guest()
returns boolean
language sql
stable
security definer
set search_path = public
as $$
select exists(
select 1 from public.validated_guests where user_id = auth.uid()
);
$$;
-- is_owner: true only for the one account whose email matches app_config.
-- A session is the owner when it is NOT anonymous AND its email equals the
-- configured owner email. Pinning to the email (rather than just "non-anonymous")
-- means email signups can stay enabled, which Supabase requires for anonymous
-- guest sign-ins to work, without any new account being mistaken for the owner.
-- Security definer so it can read app_config, which has no API access of its own.
create function public.is_owner()
returns boolean
language sql
stable
security definer
set search_path = public
as $$
select coalesce((auth.jwt() ->> 'is_anonymous')::boolean, true) = false
and lower(auth.jwt() ->> 'email') = (select lower(owner_email) from public.app_config where id = 1);
$$;
-- SETUP, REQUIRED: tell the database who the owner is. Run once, using the same
-- email you created the owner user with (and that is in VITE_OWNER_EMAIL):
-- insert into public.app_config (owner_email) values ('you@example.com');
-- Until you do, is_owner() is false for everyone and the owner cannot write
-- (the app fails closed, which is safe, just non-functional for the owner).
-- Row Level Security
alter table public.sheets enable row level security;
alter table public.setlists enable row level security;
alter table public.setlist_items enable row level security;
alter table public.annotations enable row level security;
alter table public.access_codes enable row level security;
alter table public.validated_guests enable row level security;
alter table public.app_config enable row level security;
-- app_config gets NO policies on purpose: with RLS on and no policy, the API
-- (anon and authenticated alike) can never read or write it. Only the
-- is_owner() security-definer function reads it.
-- Writes are gated on is_owner() so anonymous/guest sessions can never insert,
-- update, or delete. Reads are allowed for the owner and for validated guests.
-- sheets
create policy "owner all" on public.sheets for all
to authenticated
using (public.is_owner() and owner_id = auth.uid())
with check (public.is_owner() and owner_id = auth.uid());
create policy "guest read" on public.sheets for select
to authenticated
using (public.is_validated_guest());
-- setlists
create policy "owner all" on public.setlists for all
to authenticated
using (public.is_owner() and owner_id = auth.uid())
with check (public.is_owner() and owner_id = auth.uid());
create policy "guest read" on public.setlists for select
to authenticated
using (public.is_validated_guest());
-- setlist_items
create policy "owner all" on public.setlist_items for all
to authenticated
using (
public.is_owner() and exists (
select 1 from public.setlists s
where s.id = setlist_id and s.owner_id = auth.uid()
)
)
with check (
public.is_owner() and exists (
select 1 from public.setlists s
where s.id = setlist_id and s.owner_id = auth.uid()
)
);
create policy "guest read" on public.setlist_items for select
to authenticated
using (public.is_validated_guest());
-- annotations
create policy "owner all" on public.annotations for all
to authenticated
using (public.is_owner() and owner_id = auth.uid())
with check (public.is_owner() and owner_id = auth.uid());
create policy "guest read" on public.annotations for select
to authenticated
using (public.is_validated_guest());
-- access_codes: owner only. Guests never touch this table directly; code
-- validation runs through the validate_guest_code() security-definer function.
create policy "owner read" on public.access_codes for select
to authenticated
using (public.is_owner());
create policy "owner insert" on public.access_codes for insert
to authenticated
with check (public.is_owner());
create policy "owner delete" on public.access_codes for delete
to authenticated
using (public.is_owner());
-- validated_guests: a guest may read only their own row (revocation check on
-- load); the owner may read all rows for the usage dashboard. There are no
-- write policies: rows are only ever created/updated by the security-definer
-- functions validate_guest_code(), touch_guest_session(), and the record_* fns.
create policy "own record only" on public.validated_guests for select
to authenticated
using (user_id = auth.uid());
create policy "owner read all" on public.validated_guests for select
to authenticated
using (public.is_owner());
-- Storage
insert into storage.buckets (id, name, public)
values ('sheets', 'sheets', false)
on conflict do nothing;
-- Owner: full control over their own folder (path prefix = their user id).
-- is_owner() blocks anonymous sessions from writing to a folder named after
-- their own uid.
create policy "owner upload" on storage.objects for insert
to authenticated
with check (
bucket_id = 'sheets'
and public.is_owner()
and auth.uid()::text = (storage.foldername(name))[1]
);
create policy "owner read" on storage.objects for select
to authenticated
using (
bucket_id = 'sheets'
and public.is_owner()
and auth.uid()::text = (storage.foldername(name))[1]
);
create policy "owner delete" on storage.objects for delete
to authenticated
using (
bucket_id = 'sheets'
and public.is_owner()
and auth.uid()::text = (storage.foldername(name))[1]
);
-- Guests: read any file in the bucket (all files belong to the single owner).
create policy "guest read" on storage.objects for select
to authenticated
using (
bucket_id = 'sheets'
and public.is_validated_guest()
);
-- Grants
grant usage on schema public to anon, authenticated;
grant select, insert, update, delete on public.sheets to authenticated;
grant select, insert, update, delete on public.setlists to authenticated;
grant select, insert, update, delete on public.setlist_items to authenticated;
grant select, insert, update, delete on public.annotations to authenticated;
grant select, insert, delete on public.access_codes to authenticated;
grant select on public.validated_guests to authenticated;
grant usage, select on all sequences in schema public to authenticated;
-- Revoke from both PUBLIC and explicit anon to ensure clean grants.
revoke execute on function public.get_storage_usage() from public, anon;
revoke execute on function public.record_guest_download(bigint) from public, anon;
revoke execute on function public.record_guest_egress(bigint) from public, anon;
revoke execute on function public.touch_guest_session() from public, anon;
revoke execute on function public.validate_guest_code(text, text) from public, anon;
revoke execute on function public.is_validated_guest() from public;
revoke execute on function public.is_owner() from public;
-- get_storage_usage: owner only
grant execute on function public.get_storage_usage() to authenticated;
-- record_guest_download, touch_guest_session: guests are authenticated users
grant execute on function public.record_guest_download(bigint) to authenticated;
grant execute on function public.record_guest_egress(bigint) to authenticated;
grant execute on function public.touch_guest_session() to authenticated;
-- validate_guest_code: called after signInAnonymously() so user is already authenticated (not anon)
grant execute on function public.validate_guest_code(text, text) to authenticated;
-- is_validated_guest: used in RLS policies, anon requests also trigger RLS so anon needs EXECUTE
grant execute on function public.is_validated_guest() to anon, authenticated;
-- is_owner: used in RLS policies to gate every write to the owner
grant execute on function public.is_owner() to anon, authenticated;