@company-six/qbosync 0.0.0-stage → 0.1.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 +137 -2
- package/dist/client.d.ts +120 -0
- package/dist/client.js +223 -0
- package/dist/connectRequest.d.ts +126 -0
- package/dist/connectRequest.js +188 -0
- package/dist/connection.d.ts +108 -0
- package/dist/connection.js +191 -0
- package/dist/contract/answers.d.ts +97 -0
- package/dist/contract/answers.js +31 -0
- package/dist/contract/common.d.ts +107 -0
- package/dist/contract/common.js +86 -0
- package/dist/contract/creditMemo.d.ts +77 -0
- package/dist/contract/creditMemo.js +65 -0
- package/dist/contract/index.d.ts +145 -0
- package/dist/contract/index.js +39 -0
- package/dist/contract/invoice.d.ts +88 -0
- package/dist/contract/invoice.js +74 -0
- package/dist/contract/protocol.d.ts +28 -0
- package/dist/contract/protocol.js +26 -0
- package/dist/contract/statusReport.d.ts +20 -0
- package/dist/contract/statusReport.js +17 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +4 -0
- package/dist/statusReports.d.ts +70 -0
- package/dist/statusReports.js +125 -0
- package/dist/supabase.d.ts +38 -0
- package/dist/supabase.js +67 -0
- package/package.json +38 -4
- package/sql/001_connection.sql +368 -0
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { isClientId, newPkce, postTokenForm, readTokenAnswer, TOKEN_TIMEOUT_MS } from "./connection.js";
|
|
2
|
+
import { CONNECT_REQUEST_GRANT, CONNECT_REQUESTS_PATH } from "./contract/protocol.js";
|
|
3
|
+
/**
|
|
4
|
+
* Connecting an app to QBO Sync: a connect request.
|
|
5
|
+
*
|
|
6
|
+
* 1. An admin presses Connect in the app. The app's SERVER opens a request (`openConnectRequest`) and
|
|
7
|
+
* keeps its PKCE verifier.
|
|
8
|
+
* 2. The app sends the admin's browser to `verificationUri`. A QBO Sync administrator approves there at
|
|
9
|
+
* once, or later from a list, so nobody needs to be signed in to QBO Sync in that browser.
|
|
10
|
+
* 3. The app COLLECTS the connection (`collectConnectRequest`) from its own schedule, and when QBO Sync
|
|
11
|
+
* sends the admin's tab back: `waiting` until there is a decision, then the tokens, once.
|
|
12
|
+
*
|
|
13
|
+
* ## Collecting, once
|
|
14
|
+
*
|
|
15
|
+
* QBO Sync hands a request's connection out ONCE and treats a second collect as a copy: refused, and
|
|
16
|
+
* the connection it made is revoked. So a server first CLAIMS the collect in the database, and the
|
|
17
|
+
* connection is stored and the request closed in one statement. A server that loses the claim waits
|
|
18
|
+
* for the winner (up to `waitMs`) and reads what happened.
|
|
19
|
+
*
|
|
20
|
+
* What cannot be helped, as with renewals: if QBO Sync answers but the app cannot store it, the next
|
|
21
|
+
* collect is the second one, QBO Sync revokes the connection, and the request ends `failed`. An admin
|
|
22
|
+
* connects again.
|
|
23
|
+
*/
|
|
24
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
25
|
+
/** How long a server holds the collect. Far longer than TOKEN_TIMEOUT_MS plus saving. */
|
|
26
|
+
export const COLLECT_CLAIM_SECONDS = 60;
|
|
27
|
+
export const COLLECT_WAIT_STEP_MS = 500;
|
|
28
|
+
/** Reads the 201 to opening a request. The page must be on QBO Sync's own origin: an admin is never sent to an address the app was merely told about. */
|
|
29
|
+
export function readOpenAnswer(body, baseUrl) {
|
|
30
|
+
const b = body;
|
|
31
|
+
if (!b || typeof b !== "object")
|
|
32
|
+
return { ok: false, error: "QBO Sync's answer to the connect request is not an object" };
|
|
33
|
+
if (typeof b.request_id !== "string" || !UUID.test(b.request_id))
|
|
34
|
+
return { ok: false, error: "QBO Sync's answer has no request id of the expected shape" };
|
|
35
|
+
let page;
|
|
36
|
+
try {
|
|
37
|
+
page = new URL(String(b.verification_uri));
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return { ok: false, error: "QBO Sync's answer has no page to approve the request on" };
|
|
41
|
+
}
|
|
42
|
+
if (page.origin !== new URL(baseUrl).origin)
|
|
43
|
+
return { ok: false, error: "QBO Sync's answer points the approval to another address" };
|
|
44
|
+
return { ok: true, requestId: b.request_id.toLowerCase(), verificationUri: page.toString() };
|
|
45
|
+
}
|
|
46
|
+
/** What QBO Sync's answer to a collect means (RFC 8628's answers). */
|
|
47
|
+
export function readCollectAnswer(status, body) {
|
|
48
|
+
const b = (body && typeof body === "object" ? body : {});
|
|
49
|
+
if (status === 200) {
|
|
50
|
+
if (!isClientId(b.client_id))
|
|
51
|
+
return { kind: "refused", outcome: "failed", detail: "QBO Sync's answer carries no client id of the expected shape" };
|
|
52
|
+
const read = readTokenAnswer(body);
|
|
53
|
+
if (!read.ok)
|
|
54
|
+
return { kind: "refused", outcome: "failed", detail: read.error };
|
|
55
|
+
return { kind: "connected", clientId: b.client_id, answer: read.answer };
|
|
56
|
+
}
|
|
57
|
+
// A 5xx, a rate limit or an answer without an OAuth error says nothing about the request.
|
|
58
|
+
if (status >= 500 || status < 400 || status === 429 || typeof b.error !== "string")
|
|
59
|
+
return { kind: "unavailable", error: `QBO Sync answered ${status} to the collect` };
|
|
60
|
+
const description = typeof b.error_description === "string" && b.error_description.trim() ? b.error_description.trim() : null;
|
|
61
|
+
switch (b.error) {
|
|
62
|
+
case "authorization_pending":
|
|
63
|
+
case "slow_down":
|
|
64
|
+
return { kind: "waiting" };
|
|
65
|
+
case "access_denied":
|
|
66
|
+
return { kind: "refused", outcome: "denied", detail: description ?? "access_denied" };
|
|
67
|
+
case "expired_token":
|
|
68
|
+
return { kind: "refused", outcome: "expired", detail: description ?? "expired_token" };
|
|
69
|
+
default:
|
|
70
|
+
// invalid_grant (no such request, a verifier that does not match, already used), invalid_client, and the like.
|
|
71
|
+
return { kind: "refused", outcome: "failed", detail: description ? `${b.error}: ${description}` : b.error };
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
/** Opens a connect request and keeps it. `clientId`: the one from an earlier Connect; without one, `appName` is sent. Never throws. */
|
|
75
|
+
export async function openConnectRequest(input) {
|
|
76
|
+
const { verifier, challenge } = newPkce();
|
|
77
|
+
const form = {
|
|
78
|
+
redirect_uri: input.redirectUri,
|
|
79
|
+
code_challenge: challenge,
|
|
80
|
+
code_challenge_method: "S256",
|
|
81
|
+
...(input.clientId ? { client_id: input.clientId } : { client_name: input.appName }),
|
|
82
|
+
};
|
|
83
|
+
let status;
|
|
84
|
+
let body;
|
|
85
|
+
try {
|
|
86
|
+
const res = await (input.fetchImpl ?? fetch)(`${input.baseUrl}${CONNECT_REQUESTS_PATH}`, {
|
|
87
|
+
method: "POST",
|
|
88
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
|
|
89
|
+
body: new URLSearchParams(form).toString(),
|
|
90
|
+
signal: AbortSignal.timeout(TOKEN_TIMEOUT_MS),
|
|
91
|
+
cache: "no-store",
|
|
92
|
+
});
|
|
93
|
+
status = res.status;
|
|
94
|
+
body = await res.json().catch(() => null);
|
|
95
|
+
}
|
|
96
|
+
catch (err) {
|
|
97
|
+
return { ok: false, error: `QBO Sync could not be reached to start the connection: ${err instanceof Error ? err.message : String(err)}` };
|
|
98
|
+
}
|
|
99
|
+
if (status !== 201) {
|
|
100
|
+
const b = body;
|
|
101
|
+
const detail = [b?.error, b?.error_description].filter((v) => typeof v === "string" && v).join(": ");
|
|
102
|
+
return { ok: false, error: `QBO Sync refused to start the connection (${status}${detail ? `, ${detail}` : ""})` };
|
|
103
|
+
}
|
|
104
|
+
const read = readOpenAnswer(body, input.baseUrl);
|
|
105
|
+
if (!read.ok)
|
|
106
|
+
return read;
|
|
107
|
+
try {
|
|
108
|
+
await input.store.open({
|
|
109
|
+
baseUrl: input.baseUrl,
|
|
110
|
+
requestId: read.requestId,
|
|
111
|
+
verifier,
|
|
112
|
+
clientId: input.clientId,
|
|
113
|
+
redirectUri: input.redirectUri,
|
|
114
|
+
startedBy: input.startedBy,
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
catch (err) {
|
|
118
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
119
|
+
(input.log ?? console.error)(`[qbosync] could not keep the connect request: ${message}`);
|
|
120
|
+
return { ok: false, error: `The connect request could not be saved: ${message}` };
|
|
121
|
+
}
|
|
122
|
+
return { ok: true, requestId: read.requestId, verificationUri: read.verificationUri };
|
|
123
|
+
}
|
|
124
|
+
/** Collects the current request, when there is one still open. Never throws. */
|
|
125
|
+
export async function collectConnectRequest(deps) {
|
|
126
|
+
const now = deps.now ?? Date.now;
|
|
127
|
+
const sleep = deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
128
|
+
const waitUntil = now() + (deps.waitMs ?? 0);
|
|
129
|
+
try {
|
|
130
|
+
for (;;) {
|
|
131
|
+
const row = await deps.store.read();
|
|
132
|
+
if (!row || row.base_url !== deps.baseUrl)
|
|
133
|
+
return { state: "none" };
|
|
134
|
+
if (deps.requestId && row.request_id !== deps.requestId.toLowerCase())
|
|
135
|
+
return { state: "other" };
|
|
136
|
+
if (row.finished_at)
|
|
137
|
+
return row.outcome === "connected" ? { state: "connected" } : { state: row.outcome ?? "failed", detail: row.outcome_detail };
|
|
138
|
+
if (await deps.store.claim(row.request_id, COLLECT_CLAIM_SECONDS))
|
|
139
|
+
return await collect(deps, row);
|
|
140
|
+
if (now() >= waitUntil)
|
|
141
|
+
return { state: "unavailable", error: "Another server is collecting this connection; try again" };
|
|
142
|
+
await sleep(COLLECT_WAIT_STEP_MS);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
catch (err) {
|
|
146
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
147
|
+
(deps.log ?? console.error)(`[qbosync] ${message}`);
|
|
148
|
+
return { state: "unavailable", error: `The connect request could not be read: ${message}` };
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
/** Collects the request this server has claimed. */
|
|
152
|
+
async function collect(deps, row) {
|
|
153
|
+
const { store, baseUrl } = deps;
|
|
154
|
+
const id = row.request_id;
|
|
155
|
+
let status;
|
|
156
|
+
let body;
|
|
157
|
+
try {
|
|
158
|
+
({ status, body } = await postTokenForm(baseUrl, { grant_type: CONNECT_REQUEST_GRANT, request_id: id, code_verifier: row.code_verifier ?? "", ...(row.client_id ? { client_id: row.client_id } : {}) }, deps.fetchImpl));
|
|
159
|
+
}
|
|
160
|
+
catch (err) {
|
|
161
|
+
await store.release(id);
|
|
162
|
+
return { state: "unavailable", error: `QBO Sync could not be reached to collect the connection: ${err instanceof Error ? err.message : String(err)}` };
|
|
163
|
+
}
|
|
164
|
+
const answer = readCollectAnswer(status, body);
|
|
165
|
+
switch (answer.kind) {
|
|
166
|
+
case "waiting":
|
|
167
|
+
await store.release(id);
|
|
168
|
+
return { state: "waiting" };
|
|
169
|
+
case "unavailable":
|
|
170
|
+
await store.release(id);
|
|
171
|
+
return { state: "unavailable", error: answer.error };
|
|
172
|
+
case "refused":
|
|
173
|
+
await store.finish(id, answer.outcome, answer.detail);
|
|
174
|
+
return { state: answer.outcome, detail: answer.detail };
|
|
175
|
+
}
|
|
176
|
+
try {
|
|
177
|
+
// False: a newer Connect replaced the request meanwhile; that one wins.
|
|
178
|
+
if (!(await store.saveCollected(id, answer.clientId, answer.answer)))
|
|
179
|
+
return { state: "other" };
|
|
180
|
+
}
|
|
181
|
+
catch (err) {
|
|
182
|
+
await store.release(id);
|
|
183
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
184
|
+
(deps.log ?? console.error)(`[qbosync] QBO Sync answered with the connection but it could not be stored: ${message}`);
|
|
185
|
+
return { state: "unavailable", error: `The connection could not be saved: ${message}` };
|
|
186
|
+
}
|
|
187
|
+
return { state: "connected" };
|
|
188
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
export declare function isClientId(value: unknown): value is string;
|
|
2
|
+
/** A new PKCE pair: the verifier stays on the app's server, the challenge goes to QBO Sync (RFC 7636, S256). */
|
|
3
|
+
export declare function newPkce(random?: (size: number) => Buffer): {
|
|
4
|
+
verifier: string;
|
|
5
|
+
challenge: string;
|
|
6
|
+
};
|
|
7
|
+
/** QBO Sync's successful token answer, checked. */
|
|
8
|
+
export interface TokenAnswer {
|
|
9
|
+
accessToken: string;
|
|
10
|
+
refreshToken: string;
|
|
11
|
+
expiresIn: number;
|
|
12
|
+
}
|
|
13
|
+
/** Reads a 200 answer from the token route. Anything not in the promised shape is an error, never a half-read answer. */
|
|
14
|
+
export declare function readTokenAnswer(body: unknown): {
|
|
15
|
+
ok: true;
|
|
16
|
+
answer: TokenAnswer;
|
|
17
|
+
} | {
|
|
18
|
+
ok: false;
|
|
19
|
+
error: string;
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Why a refused token request means the connection is OVER, or null when it is worth trying again.
|
|
23
|
+
* `invalid_grant` is a renewal token QBO Sync no longer accepts (revoked, already used, unused for 90
|
|
24
|
+
* days) and `invalid_client` an unknown client id; both need an admin to connect again. Anything else
|
|
25
|
+
* (a 5xx, a timeout, an answer that is not JSON) is QBO Sync being unavailable.
|
|
26
|
+
*/
|
|
27
|
+
export declare function connectionEndedBy(status: number, body: unknown): string | null;
|
|
28
|
+
/** The stored connection. */
|
|
29
|
+
export interface ConnectionRow {
|
|
30
|
+
base_url: string;
|
|
31
|
+
client_id: string;
|
|
32
|
+
redirect_uri: string;
|
|
33
|
+
refresh_token: string;
|
|
34
|
+
access_token: string | null;
|
|
35
|
+
access_expires_at: string | null;
|
|
36
|
+
connected_by: string;
|
|
37
|
+
connected_at: string;
|
|
38
|
+
renewed_at: string | null;
|
|
39
|
+
ended_at: string | null;
|
|
40
|
+
ended_reason: string | null;
|
|
41
|
+
}
|
|
42
|
+
/** Where an app keeps its connection. `createSupabaseStores` gives one ready; any other database writes these five. */
|
|
43
|
+
export interface ConnectionStore {
|
|
44
|
+
/** The row, or null when there is none. Throws on a failure to read. */
|
|
45
|
+
read(): Promise<ConnectionRow | null>;
|
|
46
|
+
/** True for exactly one caller while the claim lasts, and only while the row still holds this token. */
|
|
47
|
+
claimRenewal(refreshToken: string, seconds: number): Promise<boolean>;
|
|
48
|
+
/** Stores the new tokens only while the row still holds the old one, and ends the claim. True when saved. */
|
|
49
|
+
saveRenewal(oldRefreshToken: string, answer: TokenAnswer): Promise<boolean>;
|
|
50
|
+
releaseRenewal(refreshToken: string): Promise<void>;
|
|
51
|
+
/** Records that QBO Sync ended the connection. True when it did. */
|
|
52
|
+
endConnection(refreshToken: string, reason: string): Promise<boolean>;
|
|
53
|
+
}
|
|
54
|
+
/** What a call to QBO Sync may authenticate with. */
|
|
55
|
+
export type Credential = {
|
|
56
|
+
kind: "token";
|
|
57
|
+
accessToken: string;
|
|
58
|
+
} | {
|
|
59
|
+
kind: "not_connected";
|
|
60
|
+
} | {
|
|
61
|
+
kind: "ended";
|
|
62
|
+
reason: string;
|
|
63
|
+
} | {
|
|
64
|
+
kind: "unavailable";
|
|
65
|
+
error: string;
|
|
66
|
+
};
|
|
67
|
+
/** An access token is used only while it has more than this left, so it does not expire on the way to QBO Sync. */
|
|
68
|
+
export declare const ACCESS_MARGIN_MS = 60000;
|
|
69
|
+
/** How long a server holds the renewal. Far longer than TOKEN_TIMEOUT_MS plus saving. */
|
|
70
|
+
export declare const RENEWAL_CLAIM_SECONDS = 60;
|
|
71
|
+
export declare const TOKEN_TIMEOUT_MS = 15000;
|
|
72
|
+
/** How long a server that lost the claim waits for the winner's token, in steps of WAIT_STEP_MS. */
|
|
73
|
+
export declare const WAIT_FOR_RENEWAL_MS = 20000;
|
|
74
|
+
export declare const WAIT_STEP_MS = 500;
|
|
75
|
+
/** How the SDK reports what it cannot return: a renewal it could not save, a connection that ended. */
|
|
76
|
+
export type Log = (message: string) => void;
|
|
77
|
+
/** POSTs a form to QBO Sync's token route. Answers the status and the parsed body, or throws when it cannot be reached. */
|
|
78
|
+
export declare function postTokenForm(baseUrl: string, form: Record<string, string>, fetchImpl?: typeof fetch): Promise<{
|
|
79
|
+
status: number;
|
|
80
|
+
body: unknown;
|
|
81
|
+
}>;
|
|
82
|
+
export interface CredentialDeps {
|
|
83
|
+
store: ConnectionStore;
|
|
84
|
+
baseUrl: string;
|
|
85
|
+
/**
|
|
86
|
+
* The access token QBO Sync just answered 401 to. While the row still holds it, it is renewed
|
|
87
|
+
* whatever its expiry; a token another server has already put in its place is used as it is.
|
|
88
|
+
*/
|
|
89
|
+
refusedToken?: string;
|
|
90
|
+
fetchImpl?: typeof fetch;
|
|
91
|
+
now?: () => number;
|
|
92
|
+
sleep?: (ms: number) => Promise<void>;
|
|
93
|
+
log?: Log;
|
|
94
|
+
}
|
|
95
|
+
/** The credential for the next call, renewing the access token when it is due. Never throws. */
|
|
96
|
+
export declare function currentCredential(deps: CredentialDeps): Promise<Credential>;
|
|
97
|
+
/**
|
|
98
|
+
* Sends one request with `credential`; when QBO Sync answers 401, asks `renewed` for a credential
|
|
99
|
+
* naming the refused token and sends once more. Once only: a 401 to the new token is answered as it
|
|
100
|
+
* is. `refused` says why no new token could be had, the first 401 then standing. Throws only when
|
|
101
|
+
* `send` throws (QBO Sync unreachable).
|
|
102
|
+
*/
|
|
103
|
+
export declare function sendRenewingOn401(accessToken: string, renewed: (refusedToken: string) => Promise<Credential>, send: (accessToken: string) => Promise<Response>): Promise<{
|
|
104
|
+
res: Response;
|
|
105
|
+
refused?: Exclude<Credential, {
|
|
106
|
+
kind: "token";
|
|
107
|
+
}>;
|
|
108
|
+
}>;
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import { TOKEN_PATH } from "./contract/protocol.js";
|
|
3
|
+
/**
|
|
4
|
+
* An app's OAuth connection to QBO Sync: renewing its access token, and what every call carries.
|
|
5
|
+
*
|
|
6
|
+
* ## Where the connection lives
|
|
7
|
+
*
|
|
8
|
+
* In the app's own database (`sql/001_connection.sql`, or your own `ConnectionStore`): the client id,
|
|
9
|
+
* the renewal token and the current access token. Every server of the app reads the same row, so they
|
|
10
|
+
* share one access token.
|
|
11
|
+
*
|
|
12
|
+
* ## Renewing, one server at a time
|
|
13
|
+
*
|
|
14
|
+
* QBO Sync replaces the renewal token on every use and ENDS the connection when an old one is used
|
|
15
|
+
* again. Two servers renewing at the same moment with the same token would end it, so a server first
|
|
16
|
+
* claims the renewal in the database (one claim at a time, expiring by itself), renews, and saves the
|
|
17
|
+
* answer only while the row still holds the token it spent. A server that loses the claim waits and
|
|
18
|
+
* reads the row again: the winner's new access token is there.
|
|
19
|
+
*
|
|
20
|
+
* What cannot be helped: if QBO Sync renews but its answer is lost, the app still holds the spent
|
|
21
|
+
* token, the next renewal reuses it, and QBO Sync ends the connection. That is recorded as ended and
|
|
22
|
+
* an admin connects again.
|
|
23
|
+
*
|
|
24
|
+
* ## A 401 renews at once
|
|
25
|
+
*
|
|
26
|
+
* Staff revoking a connection stops the access token at once, but the app would only learn it at the
|
|
27
|
+
* next renewal, up to 15 minutes later. So a 401 renews straight away and the call is made once more
|
|
28
|
+
* (`sendRenewingOn401`). QBO Sync answers the same 401 whatever the reason, so the 401 alone never
|
|
29
|
+
* ends the connection: the renewal's answer does.
|
|
30
|
+
*/
|
|
31
|
+
const ACCESS_TOKEN = /^qba_[0-9a-f]{64}$/;
|
|
32
|
+
const REFRESH_TOKEN = /^qbr_[0-9a-f]{64}$/;
|
|
33
|
+
const CLIENT_ID = /^qbc_[0-9a-f]{32}$/;
|
|
34
|
+
export function isClientId(value) {
|
|
35
|
+
return typeof value === "string" && CLIENT_ID.test(value);
|
|
36
|
+
}
|
|
37
|
+
/** A new PKCE pair: the verifier stays on the app's server, the challenge goes to QBO Sync (RFC 7636, S256). */
|
|
38
|
+
export function newPkce(random = crypto.randomBytes) {
|
|
39
|
+
const verifier = random(32).toString("base64url");
|
|
40
|
+
return { verifier, challenge: crypto.createHash("sha256").update(verifier, "ascii").digest("base64url") };
|
|
41
|
+
}
|
|
42
|
+
/** Reads a 200 answer from the token route. Anything not in the promised shape is an error, never a half-read answer. */
|
|
43
|
+
export function readTokenAnswer(body) {
|
|
44
|
+
const b = body;
|
|
45
|
+
if (!b || typeof b !== "object")
|
|
46
|
+
return { ok: false, error: "QBO Sync's token answer is not an object" };
|
|
47
|
+
if (typeof b.access_token !== "string" || !ACCESS_TOKEN.test(b.access_token)) {
|
|
48
|
+
return { ok: false, error: "QBO Sync's token answer has no access token of the expected shape" };
|
|
49
|
+
}
|
|
50
|
+
if (typeof b.refresh_token !== "string" || !REFRESH_TOKEN.test(b.refresh_token)) {
|
|
51
|
+
return { ok: false, error: "QBO Sync's token answer has no renewal token of the expected shape" };
|
|
52
|
+
}
|
|
53
|
+
if (typeof b.expires_in !== "number" || !Number.isInteger(b.expires_in) || b.expires_in < 1) {
|
|
54
|
+
return { ok: false, error: "QBO Sync's token answer has no expiry" };
|
|
55
|
+
}
|
|
56
|
+
return { ok: true, answer: { accessToken: b.access_token, refreshToken: b.refresh_token, expiresIn: b.expires_in } };
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Why a refused token request means the connection is OVER, or null when it is worth trying again.
|
|
60
|
+
* `invalid_grant` is a renewal token QBO Sync no longer accepts (revoked, already used, unused for 90
|
|
61
|
+
* days) and `invalid_client` an unknown client id; both need an admin to connect again. Anything else
|
|
62
|
+
* (a 5xx, a timeout, an answer that is not JSON) is QBO Sync being unavailable.
|
|
63
|
+
*/
|
|
64
|
+
export function connectionEndedBy(status, body) {
|
|
65
|
+
if (status < 400 || status >= 500)
|
|
66
|
+
return null;
|
|
67
|
+
const error = body?.error;
|
|
68
|
+
if (error !== "invalid_grant" && error !== "invalid_client")
|
|
69
|
+
return null;
|
|
70
|
+
const description = body.error_description;
|
|
71
|
+
return typeof description === "string" && description.trim() ? `${error}: ${description.trim()}` : error;
|
|
72
|
+
}
|
|
73
|
+
/** An access token is used only while it has more than this left, so it does not expire on the way to QBO Sync. */
|
|
74
|
+
export const ACCESS_MARGIN_MS = 60_000;
|
|
75
|
+
/** How long a server holds the renewal. Far longer than TOKEN_TIMEOUT_MS plus saving. */
|
|
76
|
+
export const RENEWAL_CLAIM_SECONDS = 60;
|
|
77
|
+
export const TOKEN_TIMEOUT_MS = 15_000;
|
|
78
|
+
/** How long a server that lost the claim waits for the winner's token, in steps of WAIT_STEP_MS. */
|
|
79
|
+
export const WAIT_FOR_RENEWAL_MS = 20_000;
|
|
80
|
+
export const WAIT_STEP_MS = 500;
|
|
81
|
+
const SAVE_ATTEMPTS = 3;
|
|
82
|
+
/** POSTs a form to QBO Sync's token route. Answers the status and the parsed body, or throws when it cannot be reached. */
|
|
83
|
+
export async function postTokenForm(baseUrl, form, fetchImpl = fetch) {
|
|
84
|
+
const res = await fetchImpl(`${baseUrl}${TOKEN_PATH}`, {
|
|
85
|
+
method: "POST",
|
|
86
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
|
|
87
|
+
body: new URLSearchParams(form).toString(),
|
|
88
|
+
signal: AbortSignal.timeout(TOKEN_TIMEOUT_MS),
|
|
89
|
+
cache: "no-store",
|
|
90
|
+
});
|
|
91
|
+
return { status: res.status, body: await res.json().catch(() => null) };
|
|
92
|
+
}
|
|
93
|
+
function accessUsable(row, now) {
|
|
94
|
+
if (!row.access_token || !row.access_expires_at)
|
|
95
|
+
return false;
|
|
96
|
+
return Date.parse(row.access_expires_at) - now > ACCESS_MARGIN_MS;
|
|
97
|
+
}
|
|
98
|
+
/** The credential for the next call, renewing the access token when it is due. Never throws. */
|
|
99
|
+
export async function currentCredential(deps) {
|
|
100
|
+
const now = deps.now ?? Date.now;
|
|
101
|
+
const sleep = deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
102
|
+
const log = deps.log ?? console.error;
|
|
103
|
+
const { store, baseUrl } = deps;
|
|
104
|
+
const waitUntil = now() + WAIT_FOR_RENEWAL_MS;
|
|
105
|
+
try {
|
|
106
|
+
for (;;) {
|
|
107
|
+
const stored = await store.read();
|
|
108
|
+
// A row made against another address (a local test) does not count.
|
|
109
|
+
const row = stored && stored.base_url === baseUrl ? stored : null;
|
|
110
|
+
if (!row)
|
|
111
|
+
return { kind: "not_connected" };
|
|
112
|
+
if (row.ended_at)
|
|
113
|
+
return { kind: "ended", reason: row.ended_reason ?? "QBO Sync ended the connection" };
|
|
114
|
+
if (accessUsable(row, now()) && row.access_token !== deps.refusedToken)
|
|
115
|
+
return { kind: "token", accessToken: row.access_token };
|
|
116
|
+
if (await store.claimRenewal(row.refresh_token, RENEWAL_CLAIM_SECONDS)) {
|
|
117
|
+
return await renew(store, baseUrl, row, deps.fetchImpl ?? fetch, log);
|
|
118
|
+
}
|
|
119
|
+
// Another server is renewing (or the row changed under us): wait for its token.
|
|
120
|
+
if (now() >= waitUntil)
|
|
121
|
+
return { kind: "unavailable", error: "The access token is being renewed by another server; try again" };
|
|
122
|
+
await sleep(WAIT_STEP_MS);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
catch (err) {
|
|
126
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
127
|
+
log(`[qbosync] ${message}`);
|
|
128
|
+
return { kind: "unavailable", error: `The connection could not be read: ${message}` };
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
/** Renews with the row's renewal token, which this server has claimed. */
|
|
132
|
+
async function renew(store, baseUrl, row, fetchImpl, log) {
|
|
133
|
+
let status;
|
|
134
|
+
let body;
|
|
135
|
+
try {
|
|
136
|
+
({ status, body } = await postTokenForm(baseUrl, { grant_type: "refresh_token", refresh_token: row.refresh_token, client_id: row.client_id }, fetchImpl));
|
|
137
|
+
}
|
|
138
|
+
catch (err) {
|
|
139
|
+
await store.releaseRenewal(row.refresh_token);
|
|
140
|
+
return { kind: "unavailable", error: `QBO Sync could not be reached to renew the access token: ${err instanceof Error ? err.message : String(err)}` };
|
|
141
|
+
}
|
|
142
|
+
if (status !== 200) {
|
|
143
|
+
const ended = connectionEndedBy(status, body);
|
|
144
|
+
if (ended) {
|
|
145
|
+
await store.endConnection(row.refresh_token, ended);
|
|
146
|
+
log(`[qbosync] QBO Sync ended the connection (${ended}); an admin must connect again`);
|
|
147
|
+
return { kind: "ended", reason: ended };
|
|
148
|
+
}
|
|
149
|
+
await store.releaseRenewal(row.refresh_token);
|
|
150
|
+
return { kind: "unavailable", error: `QBO Sync answered ${status} to the renewal` };
|
|
151
|
+
}
|
|
152
|
+
const read = readTokenAnswer(body);
|
|
153
|
+
if (!read.ok) {
|
|
154
|
+
// A 200 means the token sent in is spent, and what came back cannot be used. Nothing to save: the
|
|
155
|
+
// next renewal reuses the spent token and QBO Sync ends the connection, which an admin then sees.
|
|
156
|
+
await store.releaseRenewal(row.refresh_token);
|
|
157
|
+
return { kind: "unavailable", error: read.error };
|
|
158
|
+
}
|
|
159
|
+
let lastError = null;
|
|
160
|
+
for (let attempt = 1; attempt <= SAVE_ATTEMPTS; attempt++) {
|
|
161
|
+
try {
|
|
162
|
+
// Not saved: an admin connected again meanwhile. That newer connection wins.
|
|
163
|
+
if (!(await store.saveRenewal(row.refresh_token, read.answer))) {
|
|
164
|
+
return { kind: "unavailable", error: "The connection changed while renewing; try again" };
|
|
165
|
+
}
|
|
166
|
+
return { kind: "token", accessToken: read.answer.accessToken };
|
|
167
|
+
}
|
|
168
|
+
catch (err) {
|
|
169
|
+
lastError = err;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
log(`[qbosync] renewed but could not save the new tokens: ${lastError instanceof Error ? lastError.message : String(lastError)}`);
|
|
173
|
+
// The access token itself is good for this call even though it could not be stored.
|
|
174
|
+
return { kind: "token", accessToken: read.answer.accessToken };
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Sends one request with `credential`; when QBO Sync answers 401, asks `renewed` for a credential
|
|
178
|
+
* naming the refused token and sends once more. Once only: a 401 to the new token is answered as it
|
|
179
|
+
* is. `refused` says why no new token could be had, the first 401 then standing. Throws only when
|
|
180
|
+
* `send` throws (QBO Sync unreachable).
|
|
181
|
+
*/
|
|
182
|
+
export async function sendRenewingOn401(accessToken, renewed, send) {
|
|
183
|
+
const res = await send(accessToken);
|
|
184
|
+
if (res.status !== 401)
|
|
185
|
+
return { res };
|
|
186
|
+
const again = await renewed(accessToken);
|
|
187
|
+
if (again.kind !== "token")
|
|
188
|
+
return { res, refused: again };
|
|
189
|
+
await res.body?.cancel().catch(() => undefined);
|
|
190
|
+
return { res: await send(again.accessToken) };
|
|
191
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What QBO Sync answers an app. qbosync's own routes build these same types.
|
|
3
|
+
*/
|
|
4
|
+
export type ReceiveResultCode = "accepted" | "unchanged" | "stale" | "version_conflict" | "refused" | "ignored" | "error";
|
|
5
|
+
/** One document's result, in the order sent. */
|
|
6
|
+
export interface ReceiveResult {
|
|
7
|
+
index: number;
|
|
8
|
+
result: ReceiveResultCode;
|
|
9
|
+
type?: string;
|
|
10
|
+
source_ref?: string;
|
|
11
|
+
version?: number;
|
|
12
|
+
reasons?: string[];
|
|
13
|
+
changed_since_posted?: boolean;
|
|
14
|
+
}
|
|
15
|
+
/** What an app should do about one document's answer. */
|
|
16
|
+
export type SendOutcome =
|
|
17
|
+
/** QBO Sync holds it. Never send it again. */
|
|
18
|
+
{
|
|
19
|
+
kind: "sent";
|
|
20
|
+
unchanged: boolean;
|
|
21
|
+
changedSincePosted: boolean;
|
|
22
|
+
}
|
|
23
|
+
/** Sending it again changes nothing: a person has to look at it. */
|
|
24
|
+
| {
|
|
25
|
+
kind: "parked";
|
|
26
|
+
status: "refused" | "conflict";
|
|
27
|
+
error: string;
|
|
28
|
+
}
|
|
29
|
+
/** Not the document's fault: try again later. */
|
|
30
|
+
| {
|
|
31
|
+
kind: "failure";
|
|
32
|
+
error: string;
|
|
33
|
+
};
|
|
34
|
+
/** One entry of an answer, as read: a newer QBO Sync may answer something this version does not know. */
|
|
35
|
+
export interface SendAnswer {
|
|
36
|
+
result?: unknown;
|
|
37
|
+
reasons?: unknown;
|
|
38
|
+
changed_since_posted?: unknown;
|
|
39
|
+
}
|
|
40
|
+
/** Turns one answer into what the app should do about the document. */
|
|
41
|
+
export declare function outcomeOf(answer: SendAnswer | null | undefined): SendOutcome;
|
|
42
|
+
export interface PostedLine {
|
|
43
|
+
/** An invoice line's own ref. */
|
|
44
|
+
line_ref?: string;
|
|
45
|
+
/** A credit memo line: the invoice line it gives back, when it names one. */
|
|
46
|
+
applies_to_line_ref?: string;
|
|
47
|
+
quantity: number;
|
|
48
|
+
amount_cents: number;
|
|
49
|
+
}
|
|
50
|
+
/** What was posted, in the app's own terms. A credit memo has no discount. */
|
|
51
|
+
export interface PostedAmounts {
|
|
52
|
+
total_cents: number;
|
|
53
|
+
shipping_cents: number;
|
|
54
|
+
tax_cents: number;
|
|
55
|
+
discount_cents?: number;
|
|
56
|
+
lines: PostedLine[];
|
|
57
|
+
}
|
|
58
|
+
export interface PostedCheck {
|
|
59
|
+
result: "matches" | "differs" | "missing" | "not_checked";
|
|
60
|
+
/** When the nightly check last read it from QuickBooks; null when not checked. */
|
|
61
|
+
checked_at: string | null;
|
|
62
|
+
/** What differs, as sentences; empty unless `differs` or `missing`. */
|
|
63
|
+
differences: string[];
|
|
64
|
+
}
|
|
65
|
+
export interface UnknownEntry {
|
|
66
|
+
source_ref: string;
|
|
67
|
+
sync_status: "unknown";
|
|
68
|
+
}
|
|
69
|
+
export interface KnownEntry {
|
|
70
|
+
source_ref: string;
|
|
71
|
+
document_type: "invoice" | "credit_memo";
|
|
72
|
+
company_key: string | null;
|
|
73
|
+
company: string;
|
|
74
|
+
latest_version: number | null;
|
|
75
|
+
posted_version: number | null;
|
|
76
|
+
sync_status: string;
|
|
77
|
+
qbo_number: string | null;
|
|
78
|
+
synced_at: string | null;
|
|
79
|
+
error: string | null;
|
|
80
|
+
posted: PostedAmounts | null;
|
|
81
|
+
check: PostedCheck | null;
|
|
82
|
+
}
|
|
83
|
+
/** QBO Sync's answer about one document; `sync_status: "unknown"` means it never received it. */
|
|
84
|
+
export type ReportEntry = UnknownEntry | KnownEntry;
|
|
85
|
+
export type AppQuickBooksStatus = "connected" | "needs_reauth" | "not_connected";
|
|
86
|
+
export interface AppCompanyStatus {
|
|
87
|
+
/** The name this app uses for the company: its documents' `company_key`. */
|
|
88
|
+
company_key: string;
|
|
89
|
+
/** The company's name in QBO Sync. */
|
|
90
|
+
name: string;
|
|
91
|
+
connected: boolean;
|
|
92
|
+
/** The first time someone came in through this app for the company; null while not connected. */
|
|
93
|
+
connected_at: string | null;
|
|
94
|
+
quickbooks: AppQuickBooksStatus;
|
|
95
|
+
/** Whether the company's documents post to its QuickBooks (its sync switch). */
|
|
96
|
+
syncing: boolean;
|
|
97
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What QBO Sync answers an app. qbosync's own routes build these same types.
|
|
3
|
+
*/
|
|
4
|
+
function reasonsOf(answer) {
|
|
5
|
+
if (!Array.isArray(answer.reasons))
|
|
6
|
+
return "";
|
|
7
|
+
return answer.reasons.filter((x) => typeof x === "string" && x.trim() !== "").join("; ");
|
|
8
|
+
}
|
|
9
|
+
/** Turns one answer into what the app should do about the document. */
|
|
10
|
+
export function outcomeOf(answer) {
|
|
11
|
+
const result = typeof answer?.result === "string" ? answer.result : "";
|
|
12
|
+
const reasons = answer ? reasonsOf(answer) : "";
|
|
13
|
+
switch (result) {
|
|
14
|
+
case "accepted":
|
|
15
|
+
return { kind: "sent", unchanged: false, changedSincePosted: answer?.changed_since_posted === true };
|
|
16
|
+
case "unchanged":
|
|
17
|
+
return { kind: "sent", unchanged: true, changedSincePosted: false };
|
|
18
|
+
case "refused":
|
|
19
|
+
return { kind: "parked", status: "refused", error: reasons || "QBO Sync refused the document (no reason given)" };
|
|
20
|
+
case "stale":
|
|
21
|
+
return { kind: "parked", status: "conflict", error: `stale: ${reasons || "QBO Sync already holds a higher version"}` };
|
|
22
|
+
case "version_conflict":
|
|
23
|
+
return { kind: "parked", status: "conflict", error: `version_conflict: ${reasons || "QBO Sync holds this version with different content"}` };
|
|
24
|
+
case "ignored":
|
|
25
|
+
return { kind: "failure", error: `ignored: ${reasons || "QBO Sync did not take the document"}` };
|
|
26
|
+
case "error":
|
|
27
|
+
return { kind: "failure", error: `QBO Sync could not store it: ${reasons || "no reason given"}` };
|
|
28
|
+
default:
|
|
29
|
+
return { kind: "failure", error: `QBO Sync answered ${JSON.stringify(answer?.result ?? null)}, which this version of the SDK does not know` };
|
|
30
|
+
}
|
|
31
|
+
}
|