@company-six/qbosync 0.0.0-stage → 0.2.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 +178 -2
- package/dist/client.d.ts +163 -0
- package/dist/client.js +273 -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 +103 -0
- package/dist/contract/answers.js +47 -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 +82 -0
- package/dist/statusReports.js +129 -0
- package/dist/supabase.d.ts +38 -0
- package/dist/supabase.js +67 -0
- package/dist/testing.d.ts +38 -0
- package/dist/testing.js +31 -0
- package/package.json +42 -4
- package/sql/001_connection.sql +368 -0
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { type Log, type TokenAnswer } from "./connection.ts";
|
|
2
|
+
/** How a request ends, when it does not end connected. */
|
|
3
|
+
export type RequestRefusal = "denied" | "expired" | "failed";
|
|
4
|
+
/** The stored request. */
|
|
5
|
+
export interface ConnectRequestRow {
|
|
6
|
+
base_url: string;
|
|
7
|
+
request_id: string;
|
|
8
|
+
code_verifier: string | null;
|
|
9
|
+
client_id: string | null;
|
|
10
|
+
redirect_uri: string;
|
|
11
|
+
started_by: string;
|
|
12
|
+
started_at: string;
|
|
13
|
+
outcome: "connected" | RequestRefusal | null;
|
|
14
|
+
outcome_detail: string | null;
|
|
15
|
+
finished_at: string | null;
|
|
16
|
+
}
|
|
17
|
+
export interface NewConnectRequest {
|
|
18
|
+
baseUrl: string;
|
|
19
|
+
requestId: string;
|
|
20
|
+
verifier: string;
|
|
21
|
+
clientId: string | null;
|
|
22
|
+
redirectUri: string;
|
|
23
|
+
startedBy: string;
|
|
24
|
+
}
|
|
25
|
+
/** Where an app keeps its request. `createSupabaseStores` gives one ready. */
|
|
26
|
+
export interface ConnectRequestStore {
|
|
27
|
+
/** The row, or null when there is none. Throws on a failure to read. */
|
|
28
|
+
read(): Promise<ConnectRequestRow | null>;
|
|
29
|
+
/** Keeps a new request, replacing any earlier one. */
|
|
30
|
+
open(request: NewConnectRequest): Promise<void>;
|
|
31
|
+
/** True for exactly one caller while the claim lasts, and only while it is this request and open. */
|
|
32
|
+
claim(requestId: string, seconds: number): Promise<boolean>;
|
|
33
|
+
release(requestId: string): Promise<void>;
|
|
34
|
+
finish(requestId: string, outcome: RequestRefusal, detail: string): Promise<boolean>;
|
|
35
|
+
/** Stores the connection AND closes the request, in one statement. False when it is no longer this request. */
|
|
36
|
+
saveCollected(requestId: string, clientId: string, answer: TokenAnswer): Promise<boolean>;
|
|
37
|
+
}
|
|
38
|
+
/** How long a server holds the collect. Far longer than TOKEN_TIMEOUT_MS plus saving. */
|
|
39
|
+
export declare const COLLECT_CLAIM_SECONDS = 60;
|
|
40
|
+
export declare const COLLECT_WAIT_STEP_MS = 500;
|
|
41
|
+
/** 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. */
|
|
42
|
+
export declare function readOpenAnswer(body: unknown, baseUrl: string): {
|
|
43
|
+
ok: true;
|
|
44
|
+
requestId: string;
|
|
45
|
+
verificationUri: string;
|
|
46
|
+
} | {
|
|
47
|
+
ok: false;
|
|
48
|
+
error: string;
|
|
49
|
+
};
|
|
50
|
+
export type CollectAnswer = {
|
|
51
|
+
kind: "connected";
|
|
52
|
+
clientId: string;
|
|
53
|
+
answer: TokenAnswer;
|
|
54
|
+
}
|
|
55
|
+
/** No decision yet (or QBO Sync asks the app to slow down): ask again later. */
|
|
56
|
+
| {
|
|
57
|
+
kind: "waiting";
|
|
58
|
+
}
|
|
59
|
+
/** Final: the request is over. */
|
|
60
|
+
| {
|
|
61
|
+
kind: "refused";
|
|
62
|
+
outcome: RequestRefusal;
|
|
63
|
+
detail: string;
|
|
64
|
+
}
|
|
65
|
+
/** Not an answer about the request: ask again later. */
|
|
66
|
+
| {
|
|
67
|
+
kind: "unavailable";
|
|
68
|
+
error: string;
|
|
69
|
+
};
|
|
70
|
+
/** What QBO Sync's answer to a collect means (RFC 8628's answers). */
|
|
71
|
+
export declare function readCollectAnswer(status: number, body: unknown): CollectAnswer;
|
|
72
|
+
export type OpenResult = {
|
|
73
|
+
ok: true;
|
|
74
|
+
requestId: string;
|
|
75
|
+
verificationUri: string;
|
|
76
|
+
} | {
|
|
77
|
+
ok: false;
|
|
78
|
+
error: string;
|
|
79
|
+
};
|
|
80
|
+
/** Opens a connect request and keeps it. `clientId`: the one from an earlier Connect; without one, `appName` is sent. Never throws. */
|
|
81
|
+
export declare function openConnectRequest(input: {
|
|
82
|
+
baseUrl: string;
|
|
83
|
+
appName: string;
|
|
84
|
+
clientId: string | null;
|
|
85
|
+
redirectUri: string;
|
|
86
|
+
/** Who pressed Connect, for the record. */
|
|
87
|
+
startedBy: string;
|
|
88
|
+
store: ConnectRequestStore;
|
|
89
|
+
fetchImpl?: typeof fetch;
|
|
90
|
+
log?: Log;
|
|
91
|
+
}): Promise<OpenResult>;
|
|
92
|
+
export type CollectResult =
|
|
93
|
+
/** No request for this QBO Sync (none yet, or one made against another address). */
|
|
94
|
+
{
|
|
95
|
+
state: "none";
|
|
96
|
+
}
|
|
97
|
+
/** The request named is not the current one (a newer Connect replaced it). */
|
|
98
|
+
| {
|
|
99
|
+
state: "other";
|
|
100
|
+
} | {
|
|
101
|
+
state: "waiting";
|
|
102
|
+
} | {
|
|
103
|
+
state: "connected";
|
|
104
|
+
} | {
|
|
105
|
+
state: RequestRefusal;
|
|
106
|
+
detail: string | null;
|
|
107
|
+
}
|
|
108
|
+
/** Not known now: QBO Sync or the database unavailable, or another server still collecting. Ask again later. */
|
|
109
|
+
| {
|
|
110
|
+
state: "unavailable";
|
|
111
|
+
error: string;
|
|
112
|
+
};
|
|
113
|
+
export interface CollectDeps {
|
|
114
|
+
store: ConnectRequestStore;
|
|
115
|
+
baseUrl: string;
|
|
116
|
+
/** Only this request; another current one answers `other`. */
|
|
117
|
+
requestId?: string;
|
|
118
|
+
/** How long to wait for another server's collect of the same request. 0: answer `unavailable` at once. */
|
|
119
|
+
waitMs?: number;
|
|
120
|
+
fetchImpl?: typeof fetch;
|
|
121
|
+
now?: () => number;
|
|
122
|
+
sleep?: (ms: number) => Promise<void>;
|
|
123
|
+
log?: Log;
|
|
124
|
+
}
|
|
125
|
+
/** Collects the current request, when there is one still open. Never throws. */
|
|
126
|
+
export declare function collectConnectRequest(deps: CollectDeps): Promise<CollectResult>;
|
|
@@ -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
|
+
}
|