@company-six/qbosync 0.2.0 → 0.3.1

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.
@@ -1,368 +1,368 @@
1
- -- An app's connection to QBO Sync: run this once in the app's own Postgres database (the Supabase SQL
2
- -- editor, for instance). One transaction; re-running it is a no-op.
3
- --
4
- -- qbosync_connection ONE row: the client id, the renewal token and the current access token.
5
- -- Every server of the app reads the same row, so they share one access token.
6
- -- qbosync_connect_request ONE row: the Connect in progress and its PKCE verifier.
7
- --
8
- -- QBO Sync replaces a renewal token on every use and ENDS the connection when an old one is used again, and it
9
- -- hands a connect request's connection out only once. So a server first CLAIMS a renewal or a collect here (one
10
- -- claim at a time, on the database clock, expiring by itself so a crashed server cannot hold it forever), and
11
- -- the answer is saved only while the row still holds what was spent.
12
- --
13
- -- The tables have row level security on and no policy, and every function is granted to service_role only:
14
- -- the tokens are read by the app's server alone. Outside Supabase, grant the functions and tables to the role
15
- -- your server connects with.
16
-
17
- begin;
18
-
19
- -- ── 1. The connection ───────────────────────────────────────────────────────────────
20
-
21
- create table if not exists public.qbosync_connection (
22
- id smallint primary key default 1,
23
- -- The qbosync this connection is with (the app's QBO Sync address when it was made, no trailing slash). A row for another
24
- -- address is not used: a connection made against a local qbosync must never be sent to the real one, or the reverse.
25
- base_url text not null,
26
- client_id text not null,
27
- -- The return address registered with qbosync on the first Connect. qbosync accepts only this one afterwards.
28
- redirect_uri text not null,
29
- refresh_token text not null,
30
- access_token text,
31
- access_expires_at timestamptz,
32
- connected_by text not null,
33
- connected_at timestamptz not null default now(),
34
- renewed_at timestamptz,
35
- renewal_claimed_until timestamptz,
36
- ended_at timestamptz,
37
- ended_reason text,
38
- constraint qbosync_connection_one_row check (id = 1),
39
- constraint qbosync_connection_base_url_check check (base_url ~ '^https?://[^/?#\s]+$'),
40
- constraint qbosync_connection_client_id_check check (client_id ~ '^qbc_[0-9a-f]{32}$'),
41
- constraint qbosync_connection_redirect_uri_check check (redirect_uri ~ '^https?://[^?#\s]+$'),
42
- constraint qbosync_connection_refresh_token_check check (refresh_token ~ '^qbr_[0-9a-f]{64}$'),
43
- constraint qbosync_connection_access_token_check check (access_token is null or access_token ~ '^qba_[0-9a-f]{64}$'),
44
- constraint qbosync_connection_access_pair_check check ((access_token is null) = (access_expires_at is null)),
45
- constraint qbosync_connection_connected_by_check check (length(btrim(connected_by)) > 0),
46
- constraint qbosync_connection_ended_check check (
47
- (ended_at is null) = (ended_reason is null)
48
- and (ended_reason is null or length(btrim(ended_reason)) > 0)
49
- -- An ended connection holds no usable access token and no renewal in progress.
50
- and (ended_at is null or (access_token is null and renewal_claimed_until is null)))
51
- );
52
-
53
- alter table public.qbosync_connection enable row level security;
54
-
55
- revoke all on table public.qbosync_connection from public;
56
- do $$
57
- begin
58
- if exists (select 1 from pg_roles where rolname = 'anon') then
59
- execute 'revoke all on table public.qbosync_connection from anon';
60
- end if;
61
- if exists (select 1 from pg_roles where rolname = 'authenticated') then
62
- execute 'revoke all on table public.qbosync_connection from authenticated';
63
- end if;
64
- end $$;
65
-
66
- -- ── 2. Renewing, one server at a time ───────────────────────────────────────────────
67
-
68
- -- Claims the renewal of this renewal token for p_seconds (1 to 300). True for exactly one caller while the claim lasts; false when
69
- -- another server holds it, when the token is no longer the row's (someone renewed or reconnected meanwhile), or when the
70
- -- connection has ended.
71
- create or replace function public.qbosync_claim_renewal(p_refresh_token text, p_seconds integer default 60)
72
- returns boolean
73
- language plpgsql
74
- set search_path = public
75
- as $$
76
- begin
77
- if p_seconds is null or p_seconds < 1 or p_seconds > 300 then
78
- raise exception 'qbosync_claim_renewal: p_seconds must be between 1 and 300, got %', p_seconds;
79
- end if;
80
- update public.qbosync_connection
81
- set renewal_claimed_until = now() + make_interval(secs => p_seconds)
82
- where id = 1
83
- and refresh_token = p_refresh_token
84
- and ended_at is null
85
- and (renewal_claimed_until is null or renewal_claimed_until <= now());
86
- return found;
87
- end;
88
- $$;
89
-
90
- -- Saves QBO Sync's answer to a renewal: the new renewal token, the access token and when it expires (p_expires_in seconds from
91
- -- now, on the database clock). Writes only while the row still holds p_old_refresh_token, so an answer never overwrites a newer connection. Ends the
92
- -- claim. True when saved.
93
- create or replace function public.qbosync_save_renewal(
94
- p_old_refresh_token text,
95
- p_refresh_token text,
96
- p_access_token text,
97
- p_expires_in integer
98
- )
99
- returns boolean
100
- language plpgsql
101
- set search_path = public
102
- as $$
103
- begin
104
- if p_expires_in is null or p_expires_in < 1 then
105
- raise exception 'qbosync_save_renewal: p_expires_in must be a positive number of seconds, got %', p_expires_in;
106
- end if;
107
- update public.qbosync_connection
108
- set refresh_token = p_refresh_token,
109
- access_token = p_access_token,
110
- access_expires_at = now() + make_interval(secs => p_expires_in),
111
- renewed_at = now(),
112
- renewal_claimed_until = null
113
- where id = 1
114
- and refresh_token = p_old_refresh_token
115
- and ended_at is null;
116
- return found;
117
- end;
118
- $$;
119
-
120
- -- Gives a claim back after an attempt that did not renew (qbosync unreachable, or a server error), so the next call may try again
121
- -- without waiting for the claim to expire.
122
- create or replace function public.qbosync_release_renewal(p_refresh_token text)
123
- returns void
124
- language sql
125
- set search_path = public
126
- as $$
127
- update public.qbosync_connection
128
- set renewal_claimed_until = null
129
- where id = 1
130
- and refresh_token = p_refresh_token;
131
- $$;
132
-
133
- -- Records that qbosync ended the connection this renewal token belonged to (it refused the token: staff revoked the connection,
134
- -- or a token was used twice). Only while the row still holds that token and has not ended. True when recorded.
135
- create or replace function public.qbosync_end_connection(p_refresh_token text, p_reason text)
136
- returns boolean
137
- language plpgsql
138
- set search_path = public
139
- as $$
140
- begin
141
- update public.qbosync_connection
142
- set ended_at = now(),
143
- ended_reason = coalesce(nullif(btrim(p_reason), ''), 'qbosync refused the renewal token'),
144
- access_token = null,
145
- access_expires_at = null,
146
- renewal_claimed_until = null
147
- where id = 1
148
- and refresh_token = p_refresh_token
149
- and ended_at is null;
150
- return found;
151
- end;
152
- $$;
153
-
154
- do $$
155
- declare
156
- fn text;
157
- begin
158
- foreach fn in array array[
159
- 'public.qbosync_claim_renewal(text, integer)',
160
- 'public.qbosync_save_renewal(text, text, text, integer)',
161
- 'public.qbosync_release_renewal(text)',
162
- 'public.qbosync_end_connection(text, text)'
163
- ] loop
164
- execute format('revoke all on function %s from public', fn);
165
- if exists (select 1 from pg_roles where rolname = 'anon') then
166
- execute format('revoke all on function %s from anon', fn);
167
- end if;
168
- if exists (select 1 from pg_roles where rolname = 'authenticated') then
169
- execute format('revoke all on function %s from authenticated', fn);
170
- end if;
171
- if exists (select 1 from pg_roles where rolname = 'service_role') then
172
- execute format('grant execute on function %s to service_role', fn);
173
- end if;
174
- end loop;
175
- end $$;
176
-
177
- -- ── 1. The request ──────────────────────────────────────────────────────────────────
178
-
179
- create table if not exists public.qbosync_connect_request (
180
- id smallint primary key default 1,
181
- -- The qbosync it was opened with (the app's QBO Sync address then, no trailing slash); a row for another address is not used.
182
- base_url text not null,
183
- request_id uuid not null,
184
- -- The PKCE verifier its challenge was made from; wiped when the request finishes.
185
- code_verifier text,
186
- -- The client id the app sent, when it had one; null on a first Connect (qbosync then answers with one).
187
- client_id text,
188
- -- The return address sent with it; the connection stored from it keeps this address.
189
- redirect_uri text not null,
190
- started_by text not null,
191
- started_at timestamptz not null default now(),
192
- collect_claimed_until timestamptz,
193
- -- What happened: connected, denied, expired, or failed (qbosync refused the collect for another reason).
194
- outcome text,
195
- outcome_detail text,
196
- finished_at timestamptz,
197
- constraint qbosync_connect_request_one_row check (id = 1),
198
- constraint qbosync_connect_request_base_url_check check (base_url ~ '^https?://[^/?#\s]+$'),
199
- constraint qbosync_connect_request_client_id_check check (client_id is null or client_id ~ '^qbc_[0-9a-f]{32}$'),
200
- constraint qbosync_connect_request_redirect_uri_check check (redirect_uri ~ '^https?://[^?#\s]+$'),
201
- constraint qbosync_connect_request_started_by_check check (length(btrim(started_by)) > 0),
202
- constraint qbosync_connect_request_verifier_check check (code_verifier is null or code_verifier ~ '^[A-Za-z0-9._~-]{43,128}$'),
203
- constraint qbosync_connect_request_outcome_check check (outcome is null or outcome in ('connected', 'denied', 'expired', 'failed')),
204
- -- Open: a verifier, no outcome. Finished: an outcome, no verifier, no claim.
205
- constraint qbosync_connect_request_state_check check (
206
- (finished_at is null) = (outcome is null)
207
- and (finished_at is null) = (code_verifier is not null)
208
- and (finished_at is null or collect_claimed_until is null))
209
- );
210
-
211
- alter table public.qbosync_connect_request enable row level security;
212
-
213
- revoke all on table public.qbosync_connect_request from public;
214
- do $$
215
- begin
216
- if exists (select 1 from pg_roles where rolname = 'anon') then
217
- execute 'revoke all on table public.qbosync_connect_request from anon';
218
- end if;
219
- if exists (select 1 from pg_roles where rolname = 'authenticated') then
220
- execute 'revoke all on table public.qbosync_connect_request from authenticated';
221
- end if;
222
- end $$;
223
-
224
- -- ── 2. Collecting, one server at a time ─────────────────────────────────────────────
225
-
226
- -- Claims collecting this request for p_seconds (1 to 300). True for exactly one caller while the claim lasts; false when another
227
- -- server holds it, when the row is another request now (a newer Connect), or when it has finished.
228
- create or replace function public.qbosync_claim_connect_request(p_request_id uuid, p_seconds integer default 60)
229
- returns boolean
230
- language plpgsql
231
- set search_path = public
232
- as $$
233
- begin
234
- if p_seconds is null or p_seconds < 1 or p_seconds > 300 then
235
- raise exception 'qbosync_claim_connect_request: p_seconds must be between 1 and 300, got %', p_seconds;
236
- end if;
237
- update public.qbosync_connect_request
238
- set collect_claimed_until = now() + make_interval(secs => p_seconds)
239
- where id = 1
240
- and request_id = p_request_id
241
- and finished_at is null
242
- and (collect_claimed_until is null or collect_claimed_until <= now());
243
- return found;
244
- end;
245
- $$;
246
-
247
- -- Gives a claim back after an answer that is not final (still waiting for QBO Sync's administrator, or qbosync unreachable).
248
- create or replace function public.qbosync_release_connect_request(p_request_id uuid)
249
- returns void
250
- language sql
251
- set search_path = public
252
- as $$
253
- update public.qbosync_connect_request
254
- set collect_claimed_until = null
255
- where id = 1
256
- and request_id = p_request_id
257
- and finished_at is null;
258
- $$;
259
-
260
- -- Closes the request with a final refusal: denied, expired or failed (not connected: that is qbosync_save_collected_connection).
261
- -- Only while it is still this request and open. True when closed.
262
- create or replace function public.qbosync_finish_connect_request(p_request_id uuid, p_outcome text, p_detail text)
263
- returns boolean
264
- language plpgsql
265
- set search_path = public
266
- as $$
267
- begin
268
- if p_outcome is null or p_outcome not in ('denied', 'expired', 'failed') then
269
- raise exception 'qbosync_finish_connect_request: p_outcome must be denied, expired or failed, got %', p_outcome;
270
- end if;
271
- update public.qbosync_connect_request
272
- set outcome = p_outcome,
273
- outcome_detail = nullif(btrim(p_detail), ''),
274
- finished_at = now(),
275
- code_verifier = null,
276
- collect_claimed_until = null
277
- where id = 1
278
- and request_id = p_request_id
279
- and finished_at is null;
280
- return found;
281
- end;
282
- $$;
283
-
284
- -- Stores the connection qbosync answered a collect with, replacing any earlier one (as an admin's same-tab Connect does), and
285
- -- closes the request as connected, in one statement: never one without the other. The connection's qbosync, return address and
286
- -- who connected come from the request. Only while it is still this request and open; false otherwise (nothing written).
287
- create or replace function public.qbosync_save_collected_connection(
288
- p_request_id uuid,
289
- p_client_id text,
290
- p_refresh_token text,
291
- p_access_token text,
292
- p_expires_in integer
293
- )
294
- returns boolean
295
- language plpgsql
296
- set search_path = public
297
- as $$
298
- declare
299
- req public.qbosync_connect_request%rowtype;
300
- begin
301
- if p_expires_in is null or p_expires_in < 1 then
302
- raise exception 'qbosync_save_collected_connection: p_expires_in must be a positive number of seconds, got %', p_expires_in;
303
- end if;
304
- select * into req
305
- from public.qbosync_connect_request
306
- where id = 1
307
- and request_id = p_request_id
308
- and finished_at is null
309
- for update;
310
- if not found then
311
- return false;
312
- end if;
313
-
314
- insert into public.qbosync_connection as c (
315
- id, base_url, client_id, redirect_uri, refresh_token, access_token, access_expires_at, connected_by,
316
- connected_at, renewed_at, renewal_claimed_until, ended_at, ended_reason)
317
- values (
318
- 1, req.base_url, p_client_id, req.redirect_uri, p_refresh_token, p_access_token, now() + make_interval(secs => p_expires_in),
319
- req.started_by, now(), null, null, null, null)
320
- on conflict (id) do update
321
- set base_url = excluded.base_url,
322
- client_id = excluded.client_id,
323
- redirect_uri = excluded.redirect_uri,
324
- refresh_token = excluded.refresh_token,
325
- access_token = excluded.access_token,
326
- access_expires_at = excluded.access_expires_at,
327
- connected_by = excluded.connected_by,
328
- connected_at = excluded.connected_at,
329
- renewed_at = null,
330
- renewal_claimed_until = null,
331
- ended_at = null,
332
- ended_reason = null;
333
-
334
- update public.qbosync_connect_request
335
- set outcome = 'connected',
336
- outcome_detail = null,
337
- finished_at = now(),
338
- code_verifier = null,
339
- collect_claimed_until = null
340
- where id = 1;
341
- return true;
342
- end;
343
- $$;
344
-
345
- do $$
346
- declare
347
- fn text;
348
- begin
349
- foreach fn in array array[
350
- 'public.qbosync_claim_connect_request(uuid, integer)',
351
- 'public.qbosync_release_connect_request(uuid)',
352
- 'public.qbosync_finish_connect_request(uuid, text, text)',
353
- 'public.qbosync_save_collected_connection(uuid, text, text, text, integer)'
354
- ] loop
355
- execute format('revoke all on function %s from public', fn);
356
- if exists (select 1 from pg_roles where rolname = 'anon') then
357
- execute format('revoke all on function %s from anon', fn);
358
- end if;
359
- if exists (select 1 from pg_roles where rolname = 'authenticated') then
360
- execute format('revoke all on function %s from authenticated', fn);
361
- end if;
362
- if exists (select 1 from pg_roles where rolname = 'service_role') then
363
- execute format('grant execute on function %s to service_role', fn);
364
- end if;
365
- end loop;
366
- end $$;
367
-
368
- commit;
1
+ -- An app's connection to QBO Sync: run this once in the app's own Postgres database (the Supabase SQL
2
+ -- editor, for instance). One transaction; re-running it is a no-op.
3
+ --
4
+ -- qbosync_connection ONE row: the client id, the renewal token and the current access token.
5
+ -- Every server of the app reads the same row, so they share one access token.
6
+ -- qbosync_connect_request ONE row: the Connect in progress and its PKCE verifier.
7
+ --
8
+ -- QBO Sync replaces a renewal token on every use and ENDS the connection when an old one is used again, and it
9
+ -- hands a connect request's connection out only once. So a server first CLAIMS a renewal or a collect here (one
10
+ -- claim at a time, on the database clock, expiring by itself so a crashed server cannot hold it forever), and
11
+ -- the answer is saved only while the row still holds what was spent.
12
+ --
13
+ -- The tables have row level security on and no policy, and every function is granted to service_role only:
14
+ -- the tokens are read by the app's server alone. Outside Supabase, grant the functions and tables to the role
15
+ -- your server connects with.
16
+
17
+ begin;
18
+
19
+ -- ── 1. The connection ───────────────────────────────────────────────────────────────
20
+
21
+ create table if not exists public.qbosync_connection (
22
+ id smallint primary key default 1,
23
+ -- The qbosync this connection is with (the app's QBO Sync address when it was made, no trailing slash). A row for another
24
+ -- address is not used: a connection made against a local qbosync must never be sent to the real one, or the reverse.
25
+ base_url text not null,
26
+ client_id text not null,
27
+ -- The return address registered with qbosync on the first Connect. qbosync accepts only this one afterwards.
28
+ redirect_uri text not null,
29
+ refresh_token text not null,
30
+ access_token text,
31
+ access_expires_at timestamptz,
32
+ connected_by text not null,
33
+ connected_at timestamptz not null default now(),
34
+ renewed_at timestamptz,
35
+ renewal_claimed_until timestamptz,
36
+ ended_at timestamptz,
37
+ ended_reason text,
38
+ constraint qbosync_connection_one_row check (id = 1),
39
+ constraint qbosync_connection_base_url_check check (base_url ~ '^https?://[^/?#\s]+$'),
40
+ constraint qbosync_connection_client_id_check check (client_id ~ '^qbc_[0-9a-f]{32}$'),
41
+ constraint qbosync_connection_redirect_uri_check check (redirect_uri ~ '^https?://[^?#\s]+$'),
42
+ constraint qbosync_connection_refresh_token_check check (refresh_token ~ '^qbr_[0-9a-f]{64}$'),
43
+ constraint qbosync_connection_access_token_check check (access_token is null or access_token ~ '^qba_[0-9a-f]{64}$'),
44
+ constraint qbosync_connection_access_pair_check check ((access_token is null) = (access_expires_at is null)),
45
+ constraint qbosync_connection_connected_by_check check (length(btrim(connected_by)) > 0),
46
+ constraint qbosync_connection_ended_check check (
47
+ (ended_at is null) = (ended_reason is null)
48
+ and (ended_reason is null or length(btrim(ended_reason)) > 0)
49
+ -- An ended connection holds no usable access token and no renewal in progress.
50
+ and (ended_at is null or (access_token is null and renewal_claimed_until is null)))
51
+ );
52
+
53
+ alter table public.qbosync_connection enable row level security;
54
+
55
+ revoke all on table public.qbosync_connection from public;
56
+ do $$
57
+ begin
58
+ if exists (select 1 from pg_roles where rolname = 'anon') then
59
+ execute 'revoke all on table public.qbosync_connection from anon';
60
+ end if;
61
+ if exists (select 1 from pg_roles where rolname = 'authenticated') then
62
+ execute 'revoke all on table public.qbosync_connection from authenticated';
63
+ end if;
64
+ end $$;
65
+
66
+ -- ── 2. Renewing, one server at a time ───────────────────────────────────────────────
67
+
68
+ -- Claims the renewal of this renewal token for p_seconds (1 to 300). True for exactly one caller while the claim lasts; false when
69
+ -- another server holds it, when the token is no longer the row's (someone renewed or reconnected meanwhile), or when the
70
+ -- connection has ended.
71
+ create or replace function public.qbosync_claim_renewal(p_refresh_token text, p_seconds integer default 60)
72
+ returns boolean
73
+ language plpgsql
74
+ set search_path = public
75
+ as $$
76
+ begin
77
+ if p_seconds is null or p_seconds < 1 or p_seconds > 300 then
78
+ raise exception 'qbosync_claim_renewal: p_seconds must be between 1 and 300, got %', p_seconds;
79
+ end if;
80
+ update public.qbosync_connection
81
+ set renewal_claimed_until = now() + make_interval(secs => p_seconds)
82
+ where id = 1
83
+ and refresh_token = p_refresh_token
84
+ and ended_at is null
85
+ and (renewal_claimed_until is null or renewal_claimed_until <= now());
86
+ return found;
87
+ end;
88
+ $$;
89
+
90
+ -- Saves QBO Sync's answer to a renewal: the new renewal token, the access token and when it expires (p_expires_in seconds from
91
+ -- now, on the database clock). Writes only while the row still holds p_old_refresh_token, so an answer never overwrites a newer connection. Ends the
92
+ -- claim. True when saved.
93
+ create or replace function public.qbosync_save_renewal(
94
+ p_old_refresh_token text,
95
+ p_refresh_token text,
96
+ p_access_token text,
97
+ p_expires_in integer
98
+ )
99
+ returns boolean
100
+ language plpgsql
101
+ set search_path = public
102
+ as $$
103
+ begin
104
+ if p_expires_in is null or p_expires_in < 1 then
105
+ raise exception 'qbosync_save_renewal: p_expires_in must be a positive number of seconds, got %', p_expires_in;
106
+ end if;
107
+ update public.qbosync_connection
108
+ set refresh_token = p_refresh_token,
109
+ access_token = p_access_token,
110
+ access_expires_at = now() + make_interval(secs => p_expires_in),
111
+ renewed_at = now(),
112
+ renewal_claimed_until = null
113
+ where id = 1
114
+ and refresh_token = p_old_refresh_token
115
+ and ended_at is null;
116
+ return found;
117
+ end;
118
+ $$;
119
+
120
+ -- Gives a claim back after an attempt that did not renew (qbosync unreachable, or a server error), so the next call may try again
121
+ -- without waiting for the claim to expire.
122
+ create or replace function public.qbosync_release_renewal(p_refresh_token text)
123
+ returns void
124
+ language sql
125
+ set search_path = public
126
+ as $$
127
+ update public.qbosync_connection
128
+ set renewal_claimed_until = null
129
+ where id = 1
130
+ and refresh_token = p_refresh_token;
131
+ $$;
132
+
133
+ -- Records that qbosync ended the connection this renewal token belonged to (it refused the token: staff revoked the connection,
134
+ -- or a token was used twice). Only while the row still holds that token and has not ended. True when recorded.
135
+ create or replace function public.qbosync_end_connection(p_refresh_token text, p_reason text)
136
+ returns boolean
137
+ language plpgsql
138
+ set search_path = public
139
+ as $$
140
+ begin
141
+ update public.qbosync_connection
142
+ set ended_at = now(),
143
+ ended_reason = coalesce(nullif(btrim(p_reason), ''), 'qbosync refused the renewal token'),
144
+ access_token = null,
145
+ access_expires_at = null,
146
+ renewal_claimed_until = null
147
+ where id = 1
148
+ and refresh_token = p_refresh_token
149
+ and ended_at is null;
150
+ return found;
151
+ end;
152
+ $$;
153
+
154
+ do $$
155
+ declare
156
+ fn text;
157
+ begin
158
+ foreach fn in array array[
159
+ 'public.qbosync_claim_renewal(text, integer)',
160
+ 'public.qbosync_save_renewal(text, text, text, integer)',
161
+ 'public.qbosync_release_renewal(text)',
162
+ 'public.qbosync_end_connection(text, text)'
163
+ ] loop
164
+ execute format('revoke all on function %s from public', fn);
165
+ if exists (select 1 from pg_roles where rolname = 'anon') then
166
+ execute format('revoke all on function %s from anon', fn);
167
+ end if;
168
+ if exists (select 1 from pg_roles where rolname = 'authenticated') then
169
+ execute format('revoke all on function %s from authenticated', fn);
170
+ end if;
171
+ if exists (select 1 from pg_roles where rolname = 'service_role') then
172
+ execute format('grant execute on function %s to service_role', fn);
173
+ end if;
174
+ end loop;
175
+ end $$;
176
+
177
+ -- ── 1. The request ──────────────────────────────────────────────────────────────────
178
+
179
+ create table if not exists public.qbosync_connect_request (
180
+ id smallint primary key default 1,
181
+ -- The qbosync it was opened with (the app's QBO Sync address then, no trailing slash); a row for another address is not used.
182
+ base_url text not null,
183
+ request_id uuid not null,
184
+ -- The PKCE verifier its challenge was made from; wiped when the request finishes.
185
+ code_verifier text,
186
+ -- The client id the app sent, when it had one; null on a first Connect (qbosync then answers with one).
187
+ client_id text,
188
+ -- The return address sent with it; the connection stored from it keeps this address.
189
+ redirect_uri text not null,
190
+ started_by text not null,
191
+ started_at timestamptz not null default now(),
192
+ collect_claimed_until timestamptz,
193
+ -- What happened: connected, denied, expired, or failed (qbosync refused the collect for another reason).
194
+ outcome text,
195
+ outcome_detail text,
196
+ finished_at timestamptz,
197
+ constraint qbosync_connect_request_one_row check (id = 1),
198
+ constraint qbosync_connect_request_base_url_check check (base_url ~ '^https?://[^/?#\s]+$'),
199
+ constraint qbosync_connect_request_client_id_check check (client_id is null or client_id ~ '^qbc_[0-9a-f]{32}$'),
200
+ constraint qbosync_connect_request_redirect_uri_check check (redirect_uri ~ '^https?://[^?#\s]+$'),
201
+ constraint qbosync_connect_request_started_by_check check (length(btrim(started_by)) > 0),
202
+ constraint qbosync_connect_request_verifier_check check (code_verifier is null or code_verifier ~ '^[A-Za-z0-9._~-]{43,128}$'),
203
+ constraint qbosync_connect_request_outcome_check check (outcome is null or outcome in ('connected', 'denied', 'expired', 'failed')),
204
+ -- Open: a verifier, no outcome. Finished: an outcome, no verifier, no claim.
205
+ constraint qbosync_connect_request_state_check check (
206
+ (finished_at is null) = (outcome is null)
207
+ and (finished_at is null) = (code_verifier is not null)
208
+ and (finished_at is null or collect_claimed_until is null))
209
+ );
210
+
211
+ alter table public.qbosync_connect_request enable row level security;
212
+
213
+ revoke all on table public.qbosync_connect_request from public;
214
+ do $$
215
+ begin
216
+ if exists (select 1 from pg_roles where rolname = 'anon') then
217
+ execute 'revoke all on table public.qbosync_connect_request from anon';
218
+ end if;
219
+ if exists (select 1 from pg_roles where rolname = 'authenticated') then
220
+ execute 'revoke all on table public.qbosync_connect_request from authenticated';
221
+ end if;
222
+ end $$;
223
+
224
+ -- ── 2. Collecting, one server at a time ─────────────────────────────────────────────
225
+
226
+ -- Claims collecting this request for p_seconds (1 to 300). True for exactly one caller while the claim lasts; false when another
227
+ -- server holds it, when the row is another request now (a newer Connect), or when it has finished.
228
+ create or replace function public.qbosync_claim_connect_request(p_request_id uuid, p_seconds integer default 60)
229
+ returns boolean
230
+ language plpgsql
231
+ set search_path = public
232
+ as $$
233
+ begin
234
+ if p_seconds is null or p_seconds < 1 or p_seconds > 300 then
235
+ raise exception 'qbosync_claim_connect_request: p_seconds must be between 1 and 300, got %', p_seconds;
236
+ end if;
237
+ update public.qbosync_connect_request
238
+ set collect_claimed_until = now() + make_interval(secs => p_seconds)
239
+ where id = 1
240
+ and request_id = p_request_id
241
+ and finished_at is null
242
+ and (collect_claimed_until is null or collect_claimed_until <= now());
243
+ return found;
244
+ end;
245
+ $$;
246
+
247
+ -- Gives a claim back after an answer that is not final (still waiting for QBO Sync's administrator, or qbosync unreachable).
248
+ create or replace function public.qbosync_release_connect_request(p_request_id uuid)
249
+ returns void
250
+ language sql
251
+ set search_path = public
252
+ as $$
253
+ update public.qbosync_connect_request
254
+ set collect_claimed_until = null
255
+ where id = 1
256
+ and request_id = p_request_id
257
+ and finished_at is null;
258
+ $$;
259
+
260
+ -- Closes the request with a final refusal: denied, expired or failed (not connected: that is qbosync_save_collected_connection).
261
+ -- Only while it is still this request and open. True when closed.
262
+ create or replace function public.qbosync_finish_connect_request(p_request_id uuid, p_outcome text, p_detail text)
263
+ returns boolean
264
+ language plpgsql
265
+ set search_path = public
266
+ as $$
267
+ begin
268
+ if p_outcome is null or p_outcome not in ('denied', 'expired', 'failed') then
269
+ raise exception 'qbosync_finish_connect_request: p_outcome must be denied, expired or failed, got %', p_outcome;
270
+ end if;
271
+ update public.qbosync_connect_request
272
+ set outcome = p_outcome,
273
+ outcome_detail = nullif(btrim(p_detail), ''),
274
+ finished_at = now(),
275
+ code_verifier = null,
276
+ collect_claimed_until = null
277
+ where id = 1
278
+ and request_id = p_request_id
279
+ and finished_at is null;
280
+ return found;
281
+ end;
282
+ $$;
283
+
284
+ -- Stores the connection qbosync answered a collect with, replacing any earlier one (as an admin's same-tab Connect does), and
285
+ -- closes the request as connected, in one statement: never one without the other. The connection's qbosync, return address and
286
+ -- who connected come from the request. Only while it is still this request and open; false otherwise (nothing written).
287
+ create or replace function public.qbosync_save_collected_connection(
288
+ p_request_id uuid,
289
+ p_client_id text,
290
+ p_refresh_token text,
291
+ p_access_token text,
292
+ p_expires_in integer
293
+ )
294
+ returns boolean
295
+ language plpgsql
296
+ set search_path = public
297
+ as $$
298
+ declare
299
+ req public.qbosync_connect_request%rowtype;
300
+ begin
301
+ if p_expires_in is null or p_expires_in < 1 then
302
+ raise exception 'qbosync_save_collected_connection: p_expires_in must be a positive number of seconds, got %', p_expires_in;
303
+ end if;
304
+ select * into req
305
+ from public.qbosync_connect_request
306
+ where id = 1
307
+ and request_id = p_request_id
308
+ and finished_at is null
309
+ for update;
310
+ if not found then
311
+ return false;
312
+ end if;
313
+
314
+ insert into public.qbosync_connection as c (
315
+ id, base_url, client_id, redirect_uri, refresh_token, access_token, access_expires_at, connected_by,
316
+ connected_at, renewed_at, renewal_claimed_until, ended_at, ended_reason)
317
+ values (
318
+ 1, req.base_url, p_client_id, req.redirect_uri, p_refresh_token, p_access_token, now() + make_interval(secs => p_expires_in),
319
+ req.started_by, now(), null, null, null, null)
320
+ on conflict (id) do update
321
+ set base_url = excluded.base_url,
322
+ client_id = excluded.client_id,
323
+ redirect_uri = excluded.redirect_uri,
324
+ refresh_token = excluded.refresh_token,
325
+ access_token = excluded.access_token,
326
+ access_expires_at = excluded.access_expires_at,
327
+ connected_by = excluded.connected_by,
328
+ connected_at = excluded.connected_at,
329
+ renewed_at = null,
330
+ renewal_claimed_until = null,
331
+ ended_at = null,
332
+ ended_reason = null;
333
+
334
+ update public.qbosync_connect_request
335
+ set outcome = 'connected',
336
+ outcome_detail = null,
337
+ finished_at = now(),
338
+ code_verifier = null,
339
+ collect_claimed_until = null
340
+ where id = 1;
341
+ return true;
342
+ end;
343
+ $$;
344
+
345
+ do $$
346
+ declare
347
+ fn text;
348
+ begin
349
+ foreach fn in array array[
350
+ 'public.qbosync_claim_connect_request(uuid, integer)',
351
+ 'public.qbosync_release_connect_request(uuid)',
352
+ 'public.qbosync_finish_connect_request(uuid, text, text)',
353
+ 'public.qbosync_save_collected_connection(uuid, text, text, text, integer)'
354
+ ] loop
355
+ execute format('revoke all on function %s from public', fn);
356
+ if exists (select 1 from pg_roles where rolname = 'anon') then
357
+ execute format('revoke all on function %s from anon', fn);
358
+ end if;
359
+ if exists (select 1 from pg_roles where rolname = 'authenticated') then
360
+ execute format('revoke all on function %s from authenticated', fn);
361
+ end if;
362
+ if exists (select 1 from pg_roles where rolname = 'service_role') then
363
+ execute format('grant execute on function %s to service_role', fn);
364
+ end if;
365
+ end loop;
366
+ end $$;
367
+
368
+ commit;