@company-six/qbosync 0.1.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 +187 -138
- package/dist/client.d.ts +50 -3
- package/dist/client.js +63 -10
- package/dist/connectRequest.d.ts +6 -0
- package/dist/connectRequest.js +1 -1
- package/dist/contract/answers.d.ts +6 -0
- package/dist/contract/answers.js +16 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/statusReports.d.ts +13 -1
- package/dist/statusReports.js +7 -3
- package/dist/testing.d.ts +38 -0
- package/dist/testing.js +31 -0
- package/package.json +44 -40
- package/sql/001_connection.sql +368 -368
package/README.md
CHANGED
|
@@ -1,138 +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.
|
|
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
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
```
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
##
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
```ts
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
if (
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
//
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
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
|
@@ -24,17 +24,57 @@ export interface QbosyncClientConfig {
|
|
|
24
24
|
/** How long one call may take. Default 60 seconds. */
|
|
25
25
|
timeoutMs?: number;
|
|
26
26
|
}
|
|
27
|
-
/**
|
|
28
|
-
|
|
27
|
+
/**
|
|
28
|
+
* Why a call failed. `not_connected` and `ended` need an admin to press Connect; `unavailable` and
|
|
29
|
+
* `rate_limited` are worth trying again; `rejected` is QBO Sync refusing the request (read `detail`);
|
|
30
|
+
* `unexpected_answer` is QBO Sync answering something this version cannot use, such as a link to another
|
|
31
|
+
* address or a list that does not line up with what was asked.
|
|
32
|
+
*/
|
|
33
|
+
export type FailureReason = "not_connected" | "ended" | "unavailable" | "rate_limited" | "rejected" | "unexpected_answer";
|
|
29
34
|
export interface Failure {
|
|
30
35
|
ok: false;
|
|
36
|
+
/** A sentence fit to show a person. */
|
|
31
37
|
error: string;
|
|
32
38
|
reason: FailureReason;
|
|
33
39
|
/** QBO Sync's status, when it answered. */
|
|
34
40
|
status?: number;
|
|
35
41
|
/** With `rate_limited`: how long QBO Sync asks to wait. */
|
|
36
42
|
retryAfterSeconds?: number;
|
|
43
|
+
/** With `rejected`: QBO Sync's own message, as it sent it. QBO Sync writes these for people. */
|
|
44
|
+
detail?: string;
|
|
45
|
+
/** With `ended`: QBO Sync's own reason, as stored (`invalid_grant: ...`), for logs; `error` says it in words. */
|
|
46
|
+
endedReason?: string;
|
|
37
47
|
}
|
|
48
|
+
/**
|
|
49
|
+
* The stored connection, without asking QBO Sync anything: for a settings page, or to decide whether an
|
|
50
|
+
* app has anything to send with. A connection made against another QBO Sync address counts as none.
|
|
51
|
+
*/
|
|
52
|
+
export type ConnectionState = {
|
|
53
|
+
state: "not_connected";
|
|
54
|
+
} | {
|
|
55
|
+
state: "connected";
|
|
56
|
+
connectedBy: string;
|
|
57
|
+
connectedAt: string;
|
|
58
|
+
renewedAt: string | null;
|
|
59
|
+
clientId: string;
|
|
60
|
+
redirectUri: string;
|
|
61
|
+
} | {
|
|
62
|
+
state: "ended";
|
|
63
|
+
connectedBy: string;
|
|
64
|
+
connectedAt: string;
|
|
65
|
+
endedAt: string;
|
|
66
|
+
/** Why, in words (`endedReasonInWords`). */
|
|
67
|
+
error: string;
|
|
68
|
+
/** QBO Sync's own reason, as stored. */
|
|
69
|
+
endedReason: string | null;
|
|
70
|
+
}
|
|
71
|
+
/** The store could not be read. */
|
|
72
|
+
| {
|
|
73
|
+
state: "unavailable";
|
|
74
|
+
error: string;
|
|
75
|
+
};
|
|
76
|
+
/** QBO Sync's sign-in page: the only page `createSignInLink` sends a browser to. */
|
|
77
|
+
export declare const SIGN_IN_PAGE_PATH = "/auth/link";
|
|
38
78
|
/** One document's result, in the order given. */
|
|
39
79
|
export interface DocumentResult {
|
|
40
80
|
index: number;
|
|
@@ -58,10 +98,14 @@ export declare class QbosyncClient {
|
|
|
58
98
|
private readonly log;
|
|
59
99
|
private readonly keys;
|
|
60
100
|
constructor(config: QbosyncClientConfig);
|
|
61
|
-
/**
|
|
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
|
+
*/
|
|
62
105
|
openConnectRequest(input: {
|
|
63
106
|
redirectUri: string;
|
|
64
107
|
startedBy: string;
|
|
108
|
+
ownCompany?: boolean;
|
|
65
109
|
}): Promise<OpenResult>;
|
|
66
110
|
/**
|
|
67
111
|
* Collects the connection once a QBO Sync administrator has decided. Safe to call often (on a
|
|
@@ -71,6 +115,8 @@ export declare class QbosyncClient {
|
|
|
71
115
|
requestId?: string;
|
|
72
116
|
waitMs?: number;
|
|
73
117
|
}): Promise<CollectResult>;
|
|
118
|
+
/** The stored connection, asking QBO Sync nothing. Never throws. */
|
|
119
|
+
connectionState(): Promise<ConnectionState>;
|
|
74
120
|
private credential;
|
|
75
121
|
private failed;
|
|
76
122
|
/** One authenticated call: renews on a 401, waits out a short rate limit once. */
|
|
@@ -112,6 +158,7 @@ export declare class QbosyncClient {
|
|
|
112
158
|
url: string;
|
|
113
159
|
expiresAt: string | null;
|
|
114
160
|
} | Failure>;
|
|
161
|
+
private isSignInPage;
|
|
115
162
|
/**
|
|
116
163
|
* Checks a call to the app's status report route (`STATUS_REPORT_PATH`). Pass the body EXACTLY as it
|
|
117
164
|
* arrived, before any parsing, and the `X-QBOSync-Signature` header.
|
package/dist/client.js
CHANGED
|
@@ -2,8 +2,10 @@ import { collectConnectRequest, openConnectRequest } from "./connectRequest.js";
|
|
|
2
2
|
import { currentCredential, sendRenewingOn401 } from "./connection.js";
|
|
3
3
|
import { checkDocument } from "./contract/index.js";
|
|
4
4
|
import { MAX_DOCUMENTS_PER_REQUEST, MAX_REPORT_REFS } from "./contract/protocol.js";
|
|
5
|
-
import { outcomeOf } from "./contract/answers.js";
|
|
5
|
+
import { endedReasonInWords, outcomeOf } from "./contract/answers.js";
|
|
6
6
|
import { checkStatusReports, SigningKeys } from "./statusReports.js";
|
|
7
|
+
/** QBO Sync's sign-in page: the only page `createSignInLink` sends a browser to. */
|
|
8
|
+
export const SIGN_IN_PAGE_PATH = "/auth/link";
|
|
7
9
|
const DEFAULT_TIMEOUT_MS = 60_000;
|
|
8
10
|
const DEFAULT_MAX_RETRY_AFTER_MS = 5_000;
|
|
9
11
|
const refOf = (document) => {
|
|
@@ -11,8 +13,21 @@ const refOf = (document) => {
|
|
|
11
13
|
return typeof ref === "string" ? ref : null;
|
|
12
14
|
};
|
|
13
15
|
function failureOf(res, body) {
|
|
14
|
-
const
|
|
15
|
-
|
|
16
|
+
const said = body?.error;
|
|
17
|
+
const detail = typeof said === "string" && said.trim() ? said.trim() : undefined;
|
|
18
|
+
return { ok: false, reason: "rejected", status: res.status, error: `QBO Sync answered ${res.status}${detail ? `: ${detail}` : ""}`, ...(detail ? { detail } : {}) };
|
|
19
|
+
}
|
|
20
|
+
/** QBO Sync answered, but with something this version cannot use. */
|
|
21
|
+
function unexpected(status, error) {
|
|
22
|
+
return { ok: false, reason: "unexpected_answer", status, error };
|
|
23
|
+
}
|
|
24
|
+
function endedFailure(reason) {
|
|
25
|
+
return {
|
|
26
|
+
ok: false,
|
|
27
|
+
reason: "ended",
|
|
28
|
+
error: `The connection to QBO Sync has ended. ${endedReasonInWords(reason)} An admin must press Connect again.`,
|
|
29
|
+
...(reason ? { endedReason: reason } : {}),
|
|
30
|
+
};
|
|
16
31
|
}
|
|
17
32
|
export class QbosyncClient {
|
|
18
33
|
config;
|
|
@@ -29,7 +44,10 @@ export class QbosyncClient {
|
|
|
29
44
|
this.keys = new SigningKeys(this.baseUrl, this.fetchImpl);
|
|
30
45
|
}
|
|
31
46
|
// ---- connecting
|
|
32
|
-
/**
|
|
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
|
+
*/
|
|
33
51
|
async openConnectRequest(input) {
|
|
34
52
|
const { baseUrl, config, fetchImpl, log } = this;
|
|
35
53
|
let clientId = null;
|
|
@@ -49,6 +67,29 @@ export class QbosyncClient {
|
|
|
49
67
|
collectConnectRequest(options = {}) {
|
|
50
68
|
return collectConnectRequest({ store: this.config.connectRequests, baseUrl: this.baseUrl, fetchImpl: this.fetchImpl, log: this.log, ...options });
|
|
51
69
|
}
|
|
70
|
+
/** The stored connection, asking QBO Sync nothing. Never throws. */
|
|
71
|
+
async connectionState() {
|
|
72
|
+
let row;
|
|
73
|
+
try {
|
|
74
|
+
row = await this.config.connections.read();
|
|
75
|
+
}
|
|
76
|
+
catch (err) {
|
|
77
|
+
return { state: "unavailable", error: `The connection could not be read: ${err instanceof Error ? err.message : String(err)}` };
|
|
78
|
+
}
|
|
79
|
+
if (!row || row.base_url !== this.baseUrl)
|
|
80
|
+
return { state: "not_connected" };
|
|
81
|
+
if (row.ended_at) {
|
|
82
|
+
return {
|
|
83
|
+
state: "ended",
|
|
84
|
+
connectedBy: row.connected_by,
|
|
85
|
+
connectedAt: row.connected_at,
|
|
86
|
+
endedAt: row.ended_at,
|
|
87
|
+
error: endedReasonInWords(row.ended_reason),
|
|
88
|
+
endedReason: row.ended_reason,
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
return { state: "connected", connectedBy: row.connected_by, connectedAt: row.connected_at, renewedAt: row.renewed_at, clientId: row.client_id, redirectUri: row.redirect_uri };
|
|
92
|
+
}
|
|
52
93
|
// ---- calling
|
|
53
94
|
credential(refusedToken) {
|
|
54
95
|
return currentCredential({ store: this.config.connections, baseUrl: this.baseUrl, refusedToken, fetchImpl: this.fetchImpl, log: this.log });
|
|
@@ -58,7 +99,7 @@ export class QbosyncClient {
|
|
|
58
99
|
case "not_connected":
|
|
59
100
|
return { ok: false, reason: "not_connected", error: "This app is not connected to QBO Sync yet: an admin must press Connect" };
|
|
60
101
|
case "ended":
|
|
61
|
-
return
|
|
102
|
+
return endedFailure(credential.reason);
|
|
62
103
|
case "unavailable":
|
|
63
104
|
return { ok: false, reason: "unavailable", error: credential.error };
|
|
64
105
|
}
|
|
@@ -148,13 +189,13 @@ export class QbosyncClient {
|
|
|
148
189
|
return failureOf(res, body);
|
|
149
190
|
const results = body?.results;
|
|
150
191
|
if (!Array.isArray(results) || results.length !== documents.length) {
|
|
151
|
-
return
|
|
192
|
+
return unexpected(res.status, `QBO Sync answered ${Array.isArray(results) ? results.length : "no"} results for ${documents.length} documents`);
|
|
152
193
|
}
|
|
153
194
|
// Answers are matched by position; when one names a source_ref it must be the one sent there.
|
|
154
195
|
for (let i = 0; i < documents.length; i++) {
|
|
155
196
|
const named = results[i]?.source_ref;
|
|
156
197
|
if (typeof named === "string" && named !== refOf(documents[i])) {
|
|
157
|
-
return
|
|
198
|
+
return unexpected(res.status, `QBO Sync's answer ${i} is for "${named}", not "${refOf(documents[i])}"`);
|
|
158
199
|
}
|
|
159
200
|
}
|
|
160
201
|
return { ok: true, answers: results };
|
|
@@ -172,7 +213,7 @@ export class QbosyncClient {
|
|
|
172
213
|
if (!called.res.ok)
|
|
173
214
|
return failureOf(called.res, body);
|
|
174
215
|
if (!Array.isArray(body?.documents) || body.documents.length !== batch.length) {
|
|
175
|
-
return
|
|
216
|
+
return unexpected(called.res.status, `QBO Sync's report answered ${Array.isArray(body?.documents) ? body.documents.length : "no"} entries for ${batch.length} refs`);
|
|
176
217
|
}
|
|
177
218
|
documents.push(...body.documents);
|
|
178
219
|
}
|
|
@@ -188,7 +229,7 @@ export class QbosyncClient {
|
|
|
188
229
|
if (!called.res.ok)
|
|
189
230
|
return failureOf(called.res, body);
|
|
190
231
|
if (!Array.isArray(body?.companies))
|
|
191
|
-
return
|
|
232
|
+
return unexpected(called.res.status, "QBO Sync's answer has no companies list");
|
|
192
233
|
return { ok: true, companies: body.companies };
|
|
193
234
|
}
|
|
194
235
|
/**
|
|
@@ -209,9 +250,21 @@ export class QbosyncClient {
|
|
|
209
250
|
if (!called.res.ok)
|
|
210
251
|
return failureOf(called.res, body);
|
|
211
252
|
if (typeof body?.url !== "string")
|
|
212
|
-
return
|
|
253
|
+
return unexpected(called.res.status, "QBO Sync's answer has no link");
|
|
254
|
+
// Apps send a signed-in person straight to it: only ever QBO Sync's own sign-in page, on the address called.
|
|
255
|
+
if (!this.isSignInPage(body.url))
|
|
256
|
+
return unexpected(called.res.status, "QBO Sync's answer links to a page other than its own sign-in page");
|
|
213
257
|
return { ok: true, url: body.url, expiresAt: typeof body.expires_at === "string" ? body.expires_at : null };
|
|
214
258
|
}
|
|
259
|
+
isSignInPage(url) {
|
|
260
|
+
try {
|
|
261
|
+
const link = new URL(url);
|
|
262
|
+
return link.origin === new URL(this.baseUrl).origin && link.pathname === SIGN_IN_PAGE_PATH;
|
|
263
|
+
}
|
|
264
|
+
catch {
|
|
265
|
+
return false;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
215
268
|
// ---- status reports
|
|
216
269
|
/**
|
|
217
270
|
* Checks a call to the app's status report route (`STATUS_REPORT_PATH`). Pass the body EXACTLY as it
|
package/dist/connectRequest.d.ts
CHANGED
|
@@ -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;
|
package/dist/connectRequest.js
CHANGED
|
@@ -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;
|
|
@@ -95,3 +95,9 @@ export interface AppCompanyStatus {
|
|
|
95
95
|
/** Whether the company's documents post to its QuickBooks (its sync switch). */
|
|
96
96
|
syncing: boolean;
|
|
97
97
|
}
|
|
98
|
+
/**
|
|
99
|
+
* Why QBO Sync ended a connection, as a sentence for the people who read it. QBO Sync's own answer
|
|
100
|
+
* (`invalid_grant: Invalid grant: refresh token is invalid`) is kept in `ended_reason` and logged, where
|
|
101
|
+
* it helps whoever investigates; pages and errors a person may see use this instead. Safe in a browser.
|
|
102
|
+
*/
|
|
103
|
+
export declare function endedReasonInWords(reason: string | null | undefined): string;
|
package/dist/contract/answers.js
CHANGED
|
@@ -29,3 +29,19 @@ export function outcomeOf(answer) {
|
|
|
29
29
|
return { kind: "failure", error: `QBO Sync answered ${JSON.stringify(answer?.result ?? null)}, which this version of the SDK does not know` };
|
|
30
30
|
}
|
|
31
31
|
}
|
|
32
|
+
/**
|
|
33
|
+
* Why QBO Sync ended a connection, as a sentence for the people who read it. QBO Sync's own answer
|
|
34
|
+
* (`invalid_grant: Invalid grant: refresh token is invalid`) is kept in `ended_reason` and logged, where
|
|
35
|
+
* it helps whoever investigates; pages and errors a person may see use this instead. Safe in a browser.
|
|
36
|
+
*/
|
|
37
|
+
export function endedReasonInWords(reason) {
|
|
38
|
+
const code = (reason ?? "").trim().split(":")[0].trim();
|
|
39
|
+
switch (code) {
|
|
40
|
+
case "invalid_grant":
|
|
41
|
+
return "QBO Sync no longer accepts this connection: QBO Sync staff revoked it, or it went unused for 90 days.";
|
|
42
|
+
case "invalid_client":
|
|
43
|
+
return "QBO Sync no longer recognises this app: its registration was removed or replaced in QBO Sync.";
|
|
44
|
+
default:
|
|
45
|
+
return "QBO Sync ended this connection.";
|
|
46
|
+
}
|
|
47
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/** The QBO Sync SDK for an app's server. See README.md. */
|
|
2
2
|
export * from "./contract/index.ts";
|
|
3
|
-
export { QbosyncClient, type DocumentResult, type Failure, type FailureReason, type QbosyncClientConfig, type SendResult } from "./client.ts";
|
|
3
|
+
export { QbosyncClient, SIGN_IN_PAGE_PATH, type ConnectionState, type DocumentResult, type Failure, type FailureReason, type QbosyncClientConfig, type SendResult, } from "./client.ts";
|
|
4
4
|
export type { CollectResult, ConnectRequestRow, ConnectRequestStore, NewConnectRequest, OpenResult, RequestRefusal } from "./connectRequest.ts";
|
|
5
5
|
export type { ConnectionRow, ConnectionStore, Log, TokenAnswer } from "./connection.ts";
|
|
6
|
-
export { isNewerReport, verifySignature, type CheckedStatusReports, type InvalidReport, type PublicSigningKey, type StatusReportResult, } from "./statusReports.ts";
|
|
6
|
+
export { isNewerReport, verifySignature, type CheckedStatusReports, type InvalidReport, type PublicSigningKey, type StatusReportEntry, type StatusReportResult, } from "./statusReports.ts";
|