@company-six/qbosync 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,179 +1,187 @@
1
- # @company-six/qbosync
2
-
3
- Connect your app to QBO Sync, which posts your sales to each company's QuickBooks. Your app sends invoices and credit memos; QBO Sync checks them, posts them and tells your app what happened to each one.
4
-
5
- Server-side only (Node 20 or later): it holds your app's tokens. TypeScript types are included (TypeScript 5 or later).
6
-
7
- ## Install
8
-
9
- ```bash
10
- npm install @company-six/qbosync zod
11
- ```
12
-
13
- Before you start, ask Company Six staff to set your app's **callback address**, the https address QBO Sync sends status reports to, and to turn on **Sign people in** if your app has a Connect button for its companies.
14
-
15
- ## 1. Add the two tables
16
-
17
- Your app keeps its connection in its own database. Run [`sql/001_connection.sql`](sql/001_connection.sql) once (in the Supabase SQL editor, for instance). It adds two one-row tables that only your server can read, with the locks that keep two servers from spending the same renewal token.
18
-
19
- Nothing else needs storing: status reports are checked with QBO Sync's public key, so your app keeps no signing secret.
20
-
21
- **Coming from a hand-built client?** Compare your functions with `sql/001_connection.sql` before switching. Supabase finds a function by the names of its arguments, so one that takes an extra argument (an old `p_signing_secret`, say) or names one differently is not found, and every renewal save fails. A renewal that cannot be saved loses the new renewal token, and QBO Sync then ends the connection. Change the functions first, in a way the old code still works with (give the extra argument a default), switch, then drop what is left.
22
-
23
- ## 2. Create the client
24
-
25
- On Supabase, with a **service-role** client:
26
-
27
- ```ts
28
- import { QbosyncClient } from "@company-six/qbosync";
29
- import { createSupabaseStores } from "@company-six/qbosync/supabase";
30
-
31
- export const qbosync = new QbosyncClient({
32
- baseUrl: process.env.QBOSYNC_URL!,
33
- appName: "my-app",
34
- ...createSupabaseStores(supabase),
35
- });
36
- ```
37
-
38
- Make **one client per server** and reuse it, as above: it keeps QBO Sync's public keys once fetched, so a client made per request would fetch them again for every status report.
39
-
40
- On another database, implement `ConnectionStore` and `ConnectRequestStore` (their comments say what each method must promise) and pass them as `connections` and `connectRequests`.
41
-
42
- ## 3. Connect
43
-
44
- When an admin of your app presses Connect:
45
-
46
- ```ts
47
- const opened = await qbosync.openConnectRequest({
48
- redirectUri: "https://my-app.com/qbosync/callback",
49
- startedBy: admin.email,
50
- });
51
- if (opened.ok) redirect(opened.verificationUri);
52
- ```
53
-
54
- A QBO Sync administrator approves then, or later. Collect the connection from a job your app runs on a schedule, and from the page the admin comes back to. It is safe to call often: only one server collects.
55
-
56
- ```ts
57
- const collected = await qbosync.collectConnectRequest();
58
- // collected.state: "connected", "waiting", "denied", "expired", "failed", "none", "other" or "unavailable"
59
- ```
60
-
61
- From then on the client renews its tokens by itself. If QBO Sync ends the connection, calls answer `reason: "ended"` and an admin presses Connect again.
62
-
63
- For a settings page, or to know whether there is anything to send with, read the connection without calling QBO Sync:
64
-
65
- ```ts
66
- const now = await qbosync.connectionState();
67
- // now.state: "connected" (who, when), "ended" (when, and why in words), "not_connected" or "unavailable"
68
- ```
69
-
70
- ## 4. Connect a company
71
-
72
- A company comes to exist in QBO Sync when your app asks for a sign-in link for it. This is what a company's own Connect button calls:
73
-
74
- ```ts
75
- const link = await qbosync.createSignInLink({ email: user.email, company: "Acme", role: "company_user" });
76
- if (link.ok) redirect(link.url); // works once, for five minutes
77
- ```
78
-
79
- The link is always QBO Sync's own sign-in page on the address the client calls; any other answer is refused as `unexpected_answer`. If QBO Sync refuses (the app may not sign people in yet, say), `link.detail` is its message, written for the person.
80
-
81
- `company` is the name your documents carry as `company_key`. Ask which of your companies have connected with `qbosync.listCompanies()`, and send a company's documents only once it has: QBO Sync refuses the rest.
82
-
83
- ## 5. Send documents
84
-
85
- ```ts
86
- const sent = await qbosync.sendDocuments([invoice, creditMemo]);
87
-
88
- for (const { source_ref, outcome } of sent.results) {
89
- if (outcome.kind === "sent") markSent(source_ref); // QBO Sync holds it. Never send it again.
90
- if (outcome.kind === "parked") needsAPerson(source_ref, outcome.error); // sending again changes nothing
91
- if (outcome.kind === "failure") retryLater(source_ref); // not the document's fault
92
- }
93
- if (!sent.ok) console.error(sent.error); // a batch failed; what has no result here is safe to send again
94
- ```
95
-
96
- Each document is checked against the contract first; one that fails is not sent and does not stop the others. You can run the same check yourself, in the browser too, with `checkDocument` from `@company-six/qbosync/contract`.
97
-
98
- **A document is sent once.** QBO Sync keeps it exactly as first received, so `version` is 1 and a later version is refused. To correct an invoice, send a credit memo, or have a person roll it back in QBO Sync. Sending again after a failure is always safe: QBO Sync answers `unchanged`.
99
-
100
- Apps send invoices and credit memos only. Payments, refunds and payouts reach QBO Sync through its own connectors, matched to your invoices by `order_ref`, so give every invoice the `order_ref` of its order.
101
-
102
- ## 6. Receive status reports
103
-
104
- QBO Sync posts what happened to your documents to your callback address + `STATUS_REPORT_PATH` (`/api/qbosync/status`). Pass the body **exactly as it arrived**, before any parsing:
105
-
106
- ```ts
107
- import { SIGNATURE_HEADER, isNewerReport } from "@company-six/qbosync";
108
-
109
- export async function POST(req: Request) {
110
- const checked = await qbosync.checkStatusReports(await req.text(), req.headers.get(SIGNATURE_HEADER));
111
- if (!checked.ok) return Response.json({ error: checked.error }, { status: checked.status });
112
-
113
- // Every report in the order it came: one that reads, or why it does not.
114
- const results = [];
115
- for (const entry of checked.entries) {
116
- if ("invalid" in entry) {
117
- const { source_ref = "", document_type = "", reasons } = entry.invalid;
118
- results.push({ source_ref, document_type, result: "error", reason: reasons.join("; ") });
119
- continue;
120
- }
121
- const { report } = entry;
122
- const id = { source_ref: report.source_ref, document_type: report.document_type };
123
- const row = await findDocument(report.source_ref);
124
- if (!row) results.push({ ...id, result: "unknown" });
125
- else if (!isNewerReport(report, row.lastSequence)) results.push({ ...id, result: "stale" });
126
- else {
127
- await saveStatus(row, report);
128
- results.push({ ...id, result: "applied" });
129
- }
130
- }
131
- return Response.json({ results });
132
- }
133
- ```
134
-
135
- Answer `error` for a report you could not apply, and for every invalid one: QBO Sync sends those again later. Keep the sequence you applied for each document: a delayed report must not hide a newer one. (`checked.reports` and `checked.invalid` hold the same reports split in two, for an app that does not answer in order.)
136
-
137
- ### Testing your status report route
138
-
139
- Only QBO Sync can sign a real report, so tests make their own key. `@company-six/qbosync/testing` signs a call the way QBO Sync does and answers the public half where the client looks for it:
140
-
141
- ```ts
142
- import { SIGNATURE_HEADER } from "@company-six/qbosync";
143
- import { createTestSigningKey, signStatusReports, testKeysFetch } from "@company-six/qbosync/testing";
144
-
145
- const key = createTestSigningKey();
146
- const client = new QbosyncClient({ baseUrl, appName: "my-app", ...stores, fetch: testKeysFetch(baseUrl, [key]) });
147
- const { body, headers } = signStatusReports(key, { reports: [report] }); // a third argument makes an old signature
148
- const checked = await client.checkStatusReports(body, headers[SIGNATURE_HEADER]);
149
- ```
150
-
151
- Never use these outside tests: anyone can make such a key.
152
-
153
- ## 7. Compare
154
-
155
- For a daily report, name the documents your app created that day:
156
-
157
- ```ts
158
- const report = await qbosync.documentReport(refs);
159
- // each entry: its status, QuickBooks number, what was posted and the nightly check, or sync_status "unknown" if never received
160
- ```
161
-
162
- ## When a call fails
163
-
164
- Nothing here throws for something QBO Sync or the network did. Every call answers `{ ok: true, ... }` or a failure with an `error` you can show a person, and a `reason`:
165
-
166
- | `reason` | Meaning | What to do |
167
- |---|---|---|
168
- | `not_connected` | Nobody has connected the app yet. | An admin presses Connect. |
169
- | `ended` | QBO Sync ended the connection. | An admin presses Connect again. |
170
- | `unavailable` | QBO Sync or your database could not answer. | Try again later. |
171
- | `rate_limited` | Over your limit. `retryAfterSeconds` says how long to wait; a wait of five seconds or less is handled for you. | Try again after that. |
172
- | `rejected` | QBO Sync refused the request. | Show `detail`, QBO Sync's own message, when there is one. |
173
- | `unexpected_answer` | QBO Sync answered, but with something this version cannot use (a link to another address, a list that does not line up). Nothing was applied. | Try again later; if it keeps happening, update the package. |
174
-
175
- `status` is set whenever QBO Sync answered. With `ended`, `error` says why in words and `endedReason` keeps QBO Sync's own reason for your logs; `endedReasonInWords(reason)` (also in `@company-six/qbosync/contract`, safe in a browser) says a stored reason the same way.
176
-
177
- ## Versions
178
-
179
- Version 1 of the protocol only grows: new fields are optional, and none is removed or renamed. This package follows semver: a patch fixes something, a minor adds something, and a major may break your code.
1
+ # @company-six/qbosync
2
+
3
+ Connect your app to QBO Sync, which posts your sales to each company's QuickBooks. Your app sends invoices and credit memos; QBO Sync checks them, posts them and tells your app what happened to each one.
4
+
5
+ Server-side only (Node 20 or later): it holds your app's tokens. TypeScript types are included (TypeScript 5 or later).
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install @company-six/qbosync zod
11
+ ```
12
+
13
+ Before you start, ask Company Six staff to set your app's **callback address**, the https address QBO Sync sends status reports to, and to turn on **Sign people in** if your app has a Connect button for its companies.
14
+
15
+ ## 1. Add the two tables
16
+
17
+ Your app keeps its connection in its own database. Run [`sql/001_connection.sql`](sql/001_connection.sql) once (in the Supabase SQL editor, for instance). It adds two one-row tables that only your server can read, with the locks that keep two servers from spending the same renewal token.
18
+
19
+ Nothing else needs storing: status reports are checked with QBO Sync's public key, so your app keeps no signing secret.
20
+
21
+ **Coming from a hand-built client?** Compare your functions with `sql/001_connection.sql` before switching. Supabase finds a function by the names of its arguments, so one that takes an extra argument (an old `p_signing_secret`, say) or names one differently is not found, and every renewal save fails. A renewal that cannot be saved loses the new renewal token, and QBO Sync then ends the connection. Change the functions first, in a way the old code still works with (give the extra argument a default), switch, then drop what is left.
22
+
23
+ ## 2. Create the client
24
+
25
+ On Supabase, with a **service-role** client:
26
+
27
+ ```ts
28
+ import { QbosyncClient } from "@company-six/qbosync";
29
+ import { createSupabaseStores } from "@company-six/qbosync/supabase";
30
+
31
+ export const qbosync = new QbosyncClient({
32
+ baseUrl: process.env.QBOSYNC_URL!,
33
+ appName: "my-app",
34
+ ...createSupabaseStores(supabase),
35
+ });
36
+ ```
37
+
38
+ Make **one client per server** and reuse it, as above: it keeps QBO Sync's public keys once fetched, so a client made per request would fetch them again for every status report.
39
+
40
+ On another database, implement `ConnectionStore` and `ConnectRequestStore` (their comments say what each method must promise) and pass them as `connections` and `connectRequests`.
41
+
42
+ ## 3. Connect
43
+
44
+ When an admin of your app presses Connect:
45
+
46
+ ```ts
47
+ const opened = await qbosync.openConnectRequest({
48
+ redirectUri: "https://my-app.com/qbosync/callback",
49
+ startedBy: admin.email,
50
+ });
51
+ if (opened.ok) redirect(opened.verificationUri);
52
+ ```
53
+
54
+ A QBO Sync administrator approves then, or later. Collect the connection from a job your app runs on a schedule, and from the page the admin comes back to. It is safe to call often: only one server collects.
55
+
56
+ ```ts
57
+ const collected = await qbosync.collectConnectRequest();
58
+ // collected.state: "connected", "waiting", "denied", "expired", "failed", "none", "other" or "unavailable"
59
+ ```
60
+
61
+ From then on the client renews its tokens by itself. If QBO Sync ends the connection, calls answer `reason: "ended"` and an admin presses Connect again.
62
+
63
+ For a settings page, or to know whether there is anything to send with, read the connection without calling QBO Sync:
64
+
65
+ ```ts
66
+ const now = await qbosync.connectionState();
67
+ // now.state: "connected" (who, when), "ended" (when, and why in words), "not_connected" or "unavailable"
68
+ ```
69
+
70
+ ## 4. Connect a company
71
+
72
+ A company comes to exist in QBO Sync when your app asks for a sign-in link for it. This is what a company's own Connect button calls:
73
+
74
+ ```ts
75
+ const link = await qbosync.createSignInLink({ email: user.email, company: "Acme", role: "company_user" });
76
+ if (link.ok) redirect(link.url); // works once, for five minutes
77
+ ```
78
+
79
+ The link is always QBO Sync's own sign-in page on the address the client calls; any other answer is refused as `unexpected_answer`. If QBO Sync refuses (the app may not sign people in yet, say), `link.detail` is its message, written for the person.
80
+
81
+ `company` is the name your documents carry as `company_key`. Ask which of your companies have connected with `qbosync.listCompanies()`, and send a company's documents only once it has: QBO Sync refuses the rest.
82
+
83
+ **Does your app sell for itself?** Then it is a company too. Say so on its first Connect:
84
+
85
+ ```ts
86
+ const opened = await qbosync.openConnectRequest({ redirectUri, startedBy: admin.email, ownCompany: true });
87
+ ```
88
+
89
+ The approval page offers to create a company under your app's name, already connected (`listCompanies()` says so), and the approving admin keeps it ticked. Send your own documents with that name as `company_key`: you need no sign-in links and no Connect button for that company. (Staff can also set this up before your first Connect, by adding your app as one that sends for *only itself*.) It is not a lasting mode: if your app later sells for other companies too, add a Connect button for them as above; nothing about your own company changes.
90
+
91
+ ## 5. Send documents
92
+
93
+ ```ts
94
+ const sent = await qbosync.sendDocuments([invoice, creditMemo]);
95
+
96
+ for (const { source_ref, outcome } of sent.results) {
97
+ if (outcome.kind === "sent") markSent(source_ref); // QBO Sync holds it. Never send it again.
98
+ if (outcome.kind === "parked") needsAPerson(source_ref, outcome.error); // sending again changes nothing
99
+ if (outcome.kind === "failure") retryLater(source_ref); // not the document's fault
100
+ }
101
+ if (!sent.ok) console.error(sent.error); // a batch failed; what has no result here is safe to send again
102
+ ```
103
+
104
+ Each document is checked against the contract first; one that fails is not sent and does not stop the others. You can run the same check yourself, in the browser too, with `checkDocument` from `@company-six/qbosync/contract`.
105
+
106
+ **A document is sent once.** QBO Sync keeps it exactly as first received, so `version` is 1 and a later version is refused. To correct an invoice, send a credit memo, or have a person roll it back in QBO Sync. Sending again after a failure is always safe: QBO Sync answers `unchanged`.
107
+
108
+ Apps send invoices and credit memos only. Payments, refunds and payouts reach QBO Sync through its own connectors, matched to your invoices by `order_ref`, so give every invoice the `order_ref` of its order.
109
+
110
+ ## 6. Receive status reports
111
+
112
+ QBO Sync posts what happened to your documents to your callback address + `STATUS_REPORT_PATH` (`/api/qbosync/status`). Pass the body **exactly as it arrived**, before any parsing:
113
+
114
+ ```ts
115
+ import { SIGNATURE_HEADER, isNewerReport } from "@company-six/qbosync";
116
+
117
+ export async function POST(req: Request) {
118
+ const checked = await qbosync.checkStatusReports(await req.text(), req.headers.get(SIGNATURE_HEADER));
119
+ if (!checked.ok) return Response.json({ error: checked.error }, { status: checked.status });
120
+
121
+ // Every report in the order it came: one that reads, or why it does not.
122
+ const results = [];
123
+ for (const entry of checked.entries) {
124
+ if ("invalid" in entry) {
125
+ const { source_ref = "", document_type = "", reasons } = entry.invalid;
126
+ results.push({ source_ref, document_type, result: "error", reason: reasons.join("; ") });
127
+ continue;
128
+ }
129
+ const { report } = entry;
130
+ const id = { source_ref: report.source_ref, document_type: report.document_type };
131
+ const row = await findDocument(report.source_ref);
132
+ if (!row) results.push({ ...id, result: "unknown" });
133
+ else if (!isNewerReport(report, row.lastSequence)) results.push({ ...id, result: "stale" });
134
+ else {
135
+ await saveStatus(row, report);
136
+ results.push({ ...id, result: "applied" });
137
+ }
138
+ }
139
+ return Response.json({ results });
140
+ }
141
+ ```
142
+
143
+ Answer `error` for a report you could not apply, and for every invalid one: QBO Sync sends those again later. Keep the sequence you applied for each document: a delayed report must not hide a newer one. (`checked.reports` and `checked.invalid` hold the same reports split in two, for an app that does not answer in order.)
144
+
145
+ ### Testing your status report route
146
+
147
+ Only QBO Sync can sign a real report, so tests make their own key. `@company-six/qbosync/testing` signs a call the way QBO Sync does and answers the public half where the client looks for it:
148
+
149
+ ```ts
150
+ import { SIGNATURE_HEADER } from "@company-six/qbosync";
151
+ import { createTestSigningKey, signStatusReports, testKeysFetch } from "@company-six/qbosync/testing";
152
+
153
+ const key = createTestSigningKey();
154
+ const client = new QbosyncClient({ baseUrl, appName: "my-app", ...stores, fetch: testKeysFetch(baseUrl, [key]) });
155
+ const { body, headers } = signStatusReports(key, { reports: [report] }); // a third argument makes an old signature
156
+ const checked = await client.checkStatusReports(body, headers[SIGNATURE_HEADER]);
157
+ ```
158
+
159
+ Never use these outside tests: anyone can make such a key.
160
+
161
+ ## 7. Compare
162
+
163
+ For a daily report, name the documents your app created that day:
164
+
165
+ ```ts
166
+ const report = await qbosync.documentReport(refs);
167
+ // each entry: its status, QuickBooks number, what was posted and the nightly check, or sync_status "unknown" if never received
168
+ ```
169
+
170
+ ## When a call fails
171
+
172
+ Nothing here throws for something QBO Sync or the network did. Every call answers `{ ok: true, ... }` or a failure with an `error` you can show a person, and a `reason`:
173
+
174
+ | `reason` | Meaning | What to do |
175
+ |---|---|---|
176
+ | `not_connected` | Nobody has connected the app yet. | An admin presses Connect. |
177
+ | `ended` | QBO Sync ended the connection. | An admin presses Connect again. |
178
+ | `unavailable` | QBO Sync or your database could not answer. | Try again later. |
179
+ | `rate_limited` | Over your limit. `retryAfterSeconds` says how long to wait; a wait of five seconds or less is handled for you. | Try again after that. |
180
+ | `rejected` | QBO Sync refused the request. | Show `detail`, QBO Sync's own message, when there is one. |
181
+ | `unexpected_answer` | QBO Sync answered, but with something this version cannot use (a link to another address, a list that does not line up). Nothing was applied. | Try again later; if it keeps happening, update the package. |
182
+
183
+ `status` is set whenever QBO Sync answered. With `ended`, `error` says why in words and `endedReason` keeps QBO Sync's own reason for your logs; `endedReasonInWords(reason)` (also in `@company-six/qbosync/contract`, safe in a browser) says a stored reason the same way.
184
+
185
+ ## Versions
186
+
187
+ Version 1 of the protocol only grows: new fields are optional, and none is removed or renamed. This package follows semver: a patch fixes something, a minor adds something, and a major may break your code.
package/dist/client.d.ts CHANGED
@@ -98,10 +98,14 @@ export declare class QbosyncClient {
98
98
  private readonly log;
99
99
  private readonly keys;
100
100
  constructor(config: QbosyncClientConfig);
101
- /** An admin pressed Connect: opens a connect request. Send their browser to `verificationUri`. */
101
+ /**
102
+ * An admin pressed Connect: opens a connect request. Send their browser to `verificationUri`. `ownCompany`: the app sells
103
+ * for itself, so on its first Connect QBO Sync offers to make it a company too (0.3.0).
104
+ */
102
105
  openConnectRequest(input: {
103
106
  redirectUri: string;
104
107
  startedBy: string;
108
+ ownCompany?: boolean;
105
109
  }): Promise<OpenResult>;
106
110
  /**
107
111
  * Collects the connection once a QBO Sync administrator has decided. Safe to call often (on a
package/dist/client.js CHANGED
@@ -44,7 +44,10 @@ export class QbosyncClient {
44
44
  this.keys = new SigningKeys(this.baseUrl, this.fetchImpl);
45
45
  }
46
46
  // ---- connecting
47
- /** An admin pressed Connect: opens a connect request. Send their browser to `verificationUri`. */
47
+ /**
48
+ * An admin pressed Connect: opens a connect request. Send their browser to `verificationUri`. `ownCompany`: the app sells
49
+ * for itself, so on its first Connect QBO Sync offers to make it a company too (0.3.0).
50
+ */
48
51
  async openConnectRequest(input) {
49
52
  const { baseUrl, config, fetchImpl, log } = this;
50
53
  let clientId = null;
@@ -85,6 +85,12 @@ export declare function openConnectRequest(input: {
85
85
  redirectUri: string;
86
86
  /** Who pressed Connect, for the record. */
87
87
  startedBy: string;
88
+ /**
89
+ * The app sells for itself, so it is a company too (0.3.0). On a first Connect, QBO Sync's approval page then offers to
90
+ * create that company, under the app's name and connected; the approving admin can untick it. Ignored once the app is
91
+ * registered. It is not a lasting mode: the app can still sign other companies in later.
92
+ */
93
+ ownCompany?: boolean;
88
94
  store: ConnectRequestStore;
89
95
  fetchImpl?: typeof fetch;
90
96
  log?: Log;
@@ -78,7 +78,7 @@ export async function openConnectRequest(input) {
78
78
  redirect_uri: input.redirectUri,
79
79
  code_challenge: challenge,
80
80
  code_challenge_method: "S256",
81
- ...(input.clientId ? { client_id: input.clientId } : { client_name: input.appName }),
81
+ ...(input.clientId ? { client_id: input.clientId } : { client_name: input.appName, ...(input.ownCompany ? { own_company: "true" } : {}) }),
82
82
  };
83
83
  let status;
84
84
  let body;
package/package.json CHANGED
@@ -1,44 +1,44 @@
1
- {
2
- "name": "@company-six/qbosync",
3
- "version": "0.2.0",
4
- "description": "Connect an app to QBO Sync: send invoices and credit memos to QuickBooks, and hear back what happened to them.",
5
- "license": "UNLICENSED",
6
- "type": "module",
7
- "sideEffects": false,
8
- "engines": {
9
- "node": ">=20"
10
- },
11
- "exports": {
12
- ".": {
13
- "types": "./dist/index.d.ts",
14
- "default": "./dist/index.js"
15
- },
16
- "./contract": {
17
- "types": "./dist/contract/index.d.ts",
18
- "default": "./dist/contract/index.js"
19
- },
20
- "./supabase": {
21
- "types": "./dist/supabase.d.ts",
22
- "default": "./dist/supabase.js"
23
- },
24
- "./testing": {
25
- "types": "./dist/testing.d.ts",
26
- "default": "./dist/testing.js"
27
- }
28
- },
29
- "files": [
30
- "dist",
31
- "sql/*.sql",
32
- "README.md"
33
- ],
34
- "scripts": {
35
- "build": "tsc -p tsconfig.json",
36
- "prepublishOnly": "npm run build"
37
- },
38
- "peerDependencies": {
39
- "zod": "^4.1.13"
40
- },
41
- "publishConfig": {
42
- "access": "public"
43
- }
44
- }
1
+ {
2
+ "name": "@company-six/qbosync",
3
+ "version": "0.3.0",
4
+ "description": "Connect an app to QBO Sync: send invoices and credit memos to QuickBooks, and hear back what happened to them.",
5
+ "license": "UNLICENSED",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "engines": {
9
+ "node": ">=20"
10
+ },
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "default": "./dist/index.js"
15
+ },
16
+ "./contract": {
17
+ "types": "./dist/contract/index.d.ts",
18
+ "default": "./dist/contract/index.js"
19
+ },
20
+ "./supabase": {
21
+ "types": "./dist/supabase.d.ts",
22
+ "default": "./dist/supabase.js"
23
+ },
24
+ "./testing": {
25
+ "types": "./dist/testing.d.ts",
26
+ "default": "./dist/testing.js"
27
+ }
28
+ },
29
+ "files": [
30
+ "dist",
31
+ "sql/*.sql",
32
+ "README.md"
33
+ ],
34
+ "scripts": {
35
+ "build": "tsc -p tsconfig.json",
36
+ "prepublishOnly": "npm run build"
37
+ },
38
+ "peerDependencies": {
39
+ "zod": "^4.1.13"
40
+ },
41
+ "publishConfig": {
42
+ "access": "public"
43
+ }
44
+ }
@@ -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;