@company-six/qbosync 0.1.0 → 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 CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
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
4
 
5
- Server-side only (Node 20 or later): it holds your app's tokens. TypeScript types are included.
5
+ Server-side only (Node 20 or later): it holds your app's tokens. TypeScript types are included (TypeScript 5 or later).
6
6
 
7
7
  ## Install
8
8
 
@@ -18,6 +18,8 @@ Your app keeps its connection in its own database. Run [`sql/001_connection.sql`
18
18
 
19
19
  Nothing else needs storing: status reports are checked with QBO Sync's public key, so your app keeps no signing secret.
20
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
+
21
23
  ## 2. Create the client
22
24
 
23
25
  On Supabase, with a **service-role** client:
@@ -33,6 +35,8 @@ export const qbosync = new QbosyncClient({
33
35
  });
34
36
  ```
35
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
+
36
40
  On another database, implement `ConnectionStore` and `ConnectRequestStore` (their comments say what each method must promise) and pass them as `connections` and `connectRequests`.
37
41
 
38
42
  ## 3. Connect
@@ -56,6 +60,13 @@ const collected = await qbosync.collectConnectRequest();
56
60
 
57
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.
58
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
+
59
70
  ## 4. Connect a company
60
71
 
61
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:
@@ -65,6 +76,8 @@ const link = await qbosync.createSignInLink({ email: user.email, company: "Acme"
65
76
  if (link.ok) redirect(link.url); // works once, for five minutes
66
77
  ```
67
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
+
68
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.
69
82
 
70
83
  ## 5. Send documents
@@ -97,20 +110,45 @@ export async function POST(req: Request) {
97
110
  const checked = await qbosync.checkStatusReports(await req.text(), req.headers.get(SIGNATURE_HEADER));
98
111
  if (!checked.ok) return Response.json({ error: checked.error }, { status: checked.status });
99
112
 
100
- const results = await Promise.all(
101
- checked.reports.map(async (report) => {
102
- const row = await findDocument(report.source_ref);
103
- if (!row) return { source_ref: report.source_ref, document_type: report.document_type, result: "unknown" };
104
- if (!isNewerReport(report, row.lastSequence)) return { source_ref: report.source_ref, document_type: report.document_type, result: "stale" };
113
+ // Every report in the order it came: one that reads, or why it does not.
114
+ const results = [];
115
+ for (const entry of checked.entries) {
116
+ if ("invalid" in entry) {
117
+ const { source_ref = "", document_type = "", reasons } = entry.invalid;
118
+ results.push({ source_ref, document_type, result: "error", reason: reasons.join("; ") });
119
+ continue;
120
+ }
121
+ const { report } = entry;
122
+ const id = { source_ref: report.source_ref, document_type: report.document_type };
123
+ const row = await findDocument(report.source_ref);
124
+ if (!row) results.push({ ...id, result: "unknown" });
125
+ else if (!isNewerReport(report, row.lastSequence)) results.push({ ...id, result: "stale" });
126
+ else {
105
127
  await saveStatus(row, report);
106
- return { source_ref: report.source_ref, document_type: report.document_type, result: "applied" };
107
- })
108
- );
128
+ results.push({ ...id, result: "applied" });
129
+ }
130
+ }
109
131
  return Response.json({ results });
110
132
  }
111
133
  ```
112
134
 
113
- Answer `error` for a report you could not apply, and for anything in `checked.invalid`: QBO Sync sends those again later. Keep the sequence you applied for each document: a delayed report must not hide a newer one.
135
+ Answer `error` for a report you could not apply, and for every invalid one: QBO Sync sends those again later. Keep the sequence you applied for each document: a delayed report must not hide a newer one. (`checked.reports` and `checked.invalid` hold the same reports split in two, for an app that does not answer in order.)
136
+
137
+ ### Testing your status report route
138
+
139
+ Only QBO Sync can sign a real report, so tests make their own key. `@company-six/qbosync/testing` signs a call the way QBO Sync does and answers the public half where the client looks for it:
140
+
141
+ ```ts
142
+ import { SIGNATURE_HEADER } from "@company-six/qbosync";
143
+ import { createTestSigningKey, signStatusReports, testKeysFetch } from "@company-six/qbosync/testing";
144
+
145
+ const key = createTestSigningKey();
146
+ const client = new QbosyncClient({ baseUrl, appName: "my-app", ...stores, fetch: testKeysFetch(baseUrl, [key]) });
147
+ const { body, headers } = signStatusReports(key, { reports: [report] }); // a third argument makes an old signature
148
+ const checked = await client.checkStatusReports(body, headers[SIGNATURE_HEADER]);
149
+ ```
150
+
151
+ Never use these outside tests: anyone can make such a key.
114
152
 
115
153
  ## 7. Compare
116
154
 
@@ -131,7 +169,10 @@ Nothing here throws for something QBO Sync or the network did. Every call answer
131
169
  | `ended` | QBO Sync ended the connection. | An admin presses Connect again. |
132
170
  | `unavailable` | QBO Sync or your database could not answer. | Try again later. |
133
171
  | `rate_limited` | Over your limit. `retryAfterSeconds` says how long to wait; a wait of five seconds or less is handled for you. | Try again after that. |
134
- | `rejected` | QBO Sync refused the request. | Read `error`. |
172
+ | `rejected` | QBO Sync refused the request. | Show `detail`, QBO Sync's own message, when there is one. |
173
+ | `unexpected_answer` | QBO Sync answered, but with something this version cannot use (a link to another address, a list that does not line up). Nothing was applied. | Try again later; if it keeps happening, update the package. |
174
+
175
+ `status` is set whenever QBO Sync answered. With `ended`, `error` says why in words and `endedReason` keeps QBO Sync's own reason for your logs; `endedReasonInWords(reason)` (also in `@company-six/qbosync/contract`, safe in a browser) says a stored reason the same way.
135
176
 
136
177
  ## Versions
137
178
 
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
- /** Why a call failed. `not_connected` and `ended` need an admin to press Connect; the others are worth trying again. */
28
- export type FailureReason = "not_connected" | "ended" | "unavailable" | "rate_limited" | "rejected";
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;
@@ -71,6 +111,8 @@ export declare class QbosyncClient {
71
111
  requestId?: string;
72
112
  waitMs?: number;
73
113
  }): Promise<CollectResult>;
114
+ /** The stored connection, asking QBO Sync nothing. Never throws. */
115
+ connectionState(): Promise<ConnectionState>;
74
116
  private credential;
75
117
  private failed;
76
118
  /** One authenticated call: renews on a 401, waits out a short rate limit once. */
@@ -112,6 +154,7 @@ export declare class QbosyncClient {
112
154
  url: string;
113
155
  expiresAt: string | null;
114
156
  } | Failure>;
157
+ private isSignInPage;
115
158
  /**
116
159
  * Checks a call to the app's status report route (`STATUS_REPORT_PATH`). Pass the body EXACTLY as it
117
160
  * 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 detail = typeof body?.error === "string" ? `: ${body.error}` : "";
15
- return { ok: false, reason: "rejected", status: res.status, error: `QBO Sync answered ${res.status}${detail}` };
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;
@@ -49,6 +64,29 @@ export class QbosyncClient {
49
64
  collectConnectRequest(options = {}) {
50
65
  return collectConnectRequest({ store: this.config.connectRequests, baseUrl: this.baseUrl, fetchImpl: this.fetchImpl, log: this.log, ...options });
51
66
  }
67
+ /** The stored connection, asking QBO Sync nothing. Never throws. */
68
+ async connectionState() {
69
+ let row;
70
+ try {
71
+ row = await this.config.connections.read();
72
+ }
73
+ catch (err) {
74
+ return { state: "unavailable", error: `The connection could not be read: ${err instanceof Error ? err.message : String(err)}` };
75
+ }
76
+ if (!row || row.base_url !== this.baseUrl)
77
+ return { state: "not_connected" };
78
+ if (row.ended_at) {
79
+ return {
80
+ state: "ended",
81
+ connectedBy: row.connected_by,
82
+ connectedAt: row.connected_at,
83
+ endedAt: row.ended_at,
84
+ error: endedReasonInWords(row.ended_reason),
85
+ endedReason: row.ended_reason,
86
+ };
87
+ }
88
+ return { state: "connected", connectedBy: row.connected_by, connectedAt: row.connected_at, renewedAt: row.renewed_at, clientId: row.client_id, redirectUri: row.redirect_uri };
89
+ }
52
90
  // ---- calling
53
91
  credential(refusedToken) {
54
92
  return currentCredential({ store: this.config.connections, baseUrl: this.baseUrl, refusedToken, fetchImpl: this.fetchImpl, log: this.log });
@@ -58,7 +96,7 @@ export class QbosyncClient {
58
96
  case "not_connected":
59
97
  return { ok: false, reason: "not_connected", error: "This app is not connected to QBO Sync yet: an admin must press Connect" };
60
98
  case "ended":
61
- return { ok: false, reason: "ended", error: `The connection to QBO Sync has ended (${credential.reason}): an admin must press Connect again` };
99
+ return endedFailure(credential.reason);
62
100
  case "unavailable":
63
101
  return { ok: false, reason: "unavailable", error: credential.error };
64
102
  }
@@ -148,13 +186,13 @@ export class QbosyncClient {
148
186
  return failureOf(res, body);
149
187
  const results = body?.results;
150
188
  if (!Array.isArray(results) || results.length !== documents.length) {
151
- return { ok: false, reason: "unavailable", status: res.status, error: `QBO Sync answered ${Array.isArray(results) ? results.length : "no"} results for ${documents.length} documents` };
189
+ return unexpected(res.status, `QBO Sync answered ${Array.isArray(results) ? results.length : "no"} results for ${documents.length} documents`);
152
190
  }
153
191
  // Answers are matched by position; when one names a source_ref it must be the one sent there.
154
192
  for (let i = 0; i < documents.length; i++) {
155
193
  const named = results[i]?.source_ref;
156
194
  if (typeof named === "string" && named !== refOf(documents[i])) {
157
- return { ok: false, reason: "unavailable", status: res.status, error: `QBO Sync's answer ${i} is for "${named}", not "${refOf(documents[i])}"` };
195
+ return unexpected(res.status, `QBO Sync's answer ${i} is for "${named}", not "${refOf(documents[i])}"`);
158
196
  }
159
197
  }
160
198
  return { ok: true, answers: results };
@@ -172,7 +210,7 @@ export class QbosyncClient {
172
210
  if (!called.res.ok)
173
211
  return failureOf(called.res, body);
174
212
  if (!Array.isArray(body?.documents) || body.documents.length !== batch.length) {
175
- return { ok: false, reason: "unavailable", status: called.res.status, error: `QBO Sync's report answered ${Array.isArray(body?.documents) ? body.documents.length : "no"} entries for ${batch.length} refs` };
213
+ return unexpected(called.res.status, `QBO Sync's report answered ${Array.isArray(body?.documents) ? body.documents.length : "no"} entries for ${batch.length} refs`);
176
214
  }
177
215
  documents.push(...body.documents);
178
216
  }
@@ -188,7 +226,7 @@ export class QbosyncClient {
188
226
  if (!called.res.ok)
189
227
  return failureOf(called.res, body);
190
228
  if (!Array.isArray(body?.companies))
191
- return { ok: false, reason: "unavailable", status: called.res.status, error: "QBO Sync's answer has no companies list" };
229
+ return unexpected(called.res.status, "QBO Sync's answer has no companies list");
192
230
  return { ok: true, companies: body.companies };
193
231
  }
194
232
  /**
@@ -209,9 +247,21 @@ export class QbosyncClient {
209
247
  if (!called.res.ok)
210
248
  return failureOf(called.res, body);
211
249
  if (typeof body?.url !== "string")
212
- return { ok: false, reason: "unavailable", status: called.res.status, error: "QBO Sync's answer has no link" };
250
+ return unexpected(called.res.status, "QBO Sync's answer has no link");
251
+ // Apps send a signed-in person straight to it: only ever QBO Sync's own sign-in page, on the address called.
252
+ if (!this.isSignInPage(body.url))
253
+ return unexpected(called.res.status, "QBO Sync's answer links to a page other than its own sign-in page");
213
254
  return { ok: true, url: body.url, expiresAt: typeof body.expires_at === "string" ? body.expires_at : null };
214
255
  }
256
+ isSignInPage(url) {
257
+ try {
258
+ const link = new URL(url);
259
+ return link.origin === new URL(this.baseUrl).origin && link.pathname === SIGN_IN_PAGE_PATH;
260
+ }
261
+ catch {
262
+ return false;
263
+ }
264
+ }
215
265
  // ---- status reports
216
266
  /**
217
267
  * Checks a call to the app's status report route (`STATUS_REPORT_PATH`). Pass the body EXACTLY as it
@@ -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;
@@ -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";
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
1
  /** The QBO Sync SDK for an app's server. See README.md. */
2
2
  export * from "./contract/index.js";
3
- export { QbosyncClient } from "./client.js";
3
+ export { QbosyncClient, SIGN_IN_PAGE_PATH, } from "./client.js";
4
4
  export { isNewerReport, verifySignature, } from "./statusReports.js";
@@ -44,12 +44,24 @@ export interface InvalidReport {
44
44
  document_type?: string;
45
45
  reasons: string[];
46
46
  }
47
+ /** One report of a call, in its place: one that reads, or why it does not. */
48
+ export type StatusReportEntry = {
49
+ index: number;
50
+ report: SyncStatusReport;
51
+ } | {
52
+ index: number;
53
+ invalid: InvalidReport;
54
+ };
47
55
  export type CheckedStatusReports =
48
- /** Genuine. Apply `reports`, answer each with a `StatusReportResult`, and answer `invalid` ones "error". */
56
+ /**
57
+ * Genuine. Apply `reports`, answer each with a `StatusReportResult`, and answer `invalid` ones "error".
58
+ * `entries` holds the same, every report in the order it came, for an app that answers them in order.
59
+ */
49
60
  {
50
61
  ok: true;
51
62
  reports: SyncStatusReport[];
52
63
  invalid: InvalidReport[];
64
+ entries: StatusReportEntry[];
53
65
  }
54
66
  /** 400 not a report call, 401 not from QBO Sync, 503 the keys could not be fetched (QBO Sync sends it again). */
55
67
  | {
@@ -103,21 +103,25 @@ export async function checkStatusReports(keys, rawBody, signature) {
103
103
  return { ok: false, status: 400, error: `At most ${MAX_STATUS_REPORTS} reports a request; this one has ${list.length}` };
104
104
  const reports = [];
105
105
  const invalid = [];
106
+ const entries = [];
106
107
  list.forEach((entry, index) => {
107
108
  const parsed = syncStatusReportSchema.safeParse(entry);
108
109
  if (parsed.success) {
109
110
  reports.push(parsed.data);
111
+ entries.push({ index, report: parsed.data });
110
112
  return;
111
113
  }
112
114
  const e = (entry ?? {});
113
- invalid.push({
115
+ const bad = {
114
116
  index,
115
117
  ...(typeof e.source_ref === "string" ? { source_ref: e.source_ref } : {}),
116
118
  ...(typeof e.document_type === "string" ? { document_type: e.document_type } : {}),
117
119
  reasons: parsed.error.issues.map(formatIssue),
118
- });
120
+ };
121
+ invalid.push(bad);
122
+ entries.push({ index, invalid: bad });
119
123
  });
120
- return { ok: true, reports, invalid };
124
+ return { ok: true, reports, invalid, entries };
121
125
  }
122
126
  /** Whether a report should be applied: only one newer than the last applied, so a delayed report never hides a newer one. */
123
127
  export function isNewerReport(report, lastAppliedSequence) {
@@ -0,0 +1,38 @@
1
+ import crypto from "node:crypto";
2
+ import type { PublicSigningKey } from "./statusReports.ts";
3
+ /**
4
+ * For an app's TESTS only: calls to its status report route as QBO Sync would make them.
5
+ *
6
+ * Only QBO Sync signs real reports, with a private key only it holds. These helpers make a throwaway key
7
+ * pair, sign a body with it the way QBO Sync does, and answer the public half where the SDK looks for it,
8
+ * so a test can drive `checkStatusReports` (or the app's route) end to end:
9
+ *
10
+ * const key = createTestSigningKey();
11
+ * const client = new QbosyncClient({ baseUrl, appName, ...stores, fetch: testKeysFetch(baseUrl, [key]) });
12
+ * const { body, headers } = signStatusReports(key, { reports: [report] });
13
+ * await client.checkStatusReports(body, headers[SIGNATURE_HEADER]);
14
+ *
15
+ * Never use a key from here outside a test: anyone can make one.
16
+ */
17
+ export interface TestSigningKey {
18
+ kid: string;
19
+ privateKey: crypto.KeyObject;
20
+ /** The public half, as QBO Sync publishes it at `/.well-known/jwks.json`. */
21
+ publicKey: PublicSigningKey;
22
+ }
23
+ /** A new Ed25519 key pair, `kid` naming it as QBO Sync names its keys. */
24
+ export declare function createTestSigningKey(kid?: string): TestSigningKey;
25
+ /**
26
+ * Signs a call's body as QBO Sync does: `t=<unix seconds>,kid=<key id>,ed25519=<base64url signature of
27
+ * "<t>." + body>`. An object is sent as JSON; a string is signed exactly as given (to test a body that is not
28
+ * JSON). `now` (unix seconds) makes an old or a future signature.
29
+ */
30
+ export declare function signStatusReports(key: Pick<TestSigningKey, "kid" | "privateKey">, body: unknown, now?: number): {
31
+ body: string;
32
+ headers: Record<string, string>;
33
+ };
34
+ /**
35
+ * A `fetch` for the client's `fetch` option that answers `<baseUrl>/.well-known/jwks.json` with these keys'
36
+ * public halves, and passes every other request to `fallback` (the real `fetch` by default).
37
+ */
38
+ export declare function testKeysFetch(baseUrl: string, keys: ReadonlyArray<Pick<TestSigningKey, "publicKey">>, fallback?: typeof fetch): typeof fetch;
@@ -0,0 +1,31 @@
1
+ import crypto from "node:crypto";
2
+ import { JWKS_PATH, SIGNATURE_HEADER } from "./contract/protocol.js";
3
+ /** A new Ed25519 key pair, `kid` naming it as QBO Sync names its keys. */
4
+ export function createTestSigningKey(kid = "test-key") {
5
+ const { privateKey, publicKey } = crypto.generateKeyPairSync("ed25519");
6
+ const { x } = publicKey.export({ format: "jwk" });
7
+ return { kid, privateKey, publicKey: { kty: "OKP", crv: "Ed25519", x, kid } };
8
+ }
9
+ /**
10
+ * Signs a call's body as QBO Sync does: `t=<unix seconds>,kid=<key id>,ed25519=<base64url signature of
11
+ * "<t>." + body>`. An object is sent as JSON; a string is signed exactly as given (to test a body that is not
12
+ * JSON). `now` (unix seconds) makes an old or a future signature.
13
+ */
14
+ export function signStatusReports(key, body, now = Math.floor(Date.now() / 1000)) {
15
+ const raw = typeof body === "string" ? body : JSON.stringify(body);
16
+ const signature = crypto.sign(null, Buffer.from(`${now}.${raw}`, "utf8"), key.privateKey).toString("base64url");
17
+ return { body: raw, headers: { "Content-Type": "application/json", [SIGNATURE_HEADER]: `t=${now},kid=${key.kid},ed25519=${signature}` } };
18
+ }
19
+ /**
20
+ * A `fetch` for the client's `fetch` option that answers `<baseUrl>/.well-known/jwks.json` with these keys'
21
+ * public halves, and passes every other request to `fallback` (the real `fetch` by default).
22
+ */
23
+ export function testKeysFetch(baseUrl, keys, fallback = (...args) => fetch(...args)) {
24
+ const jwks = `${baseUrl.trim().replace(/\/+$/, "")}${JWKS_PATH}`;
25
+ return (async (input, init) => {
26
+ const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
27
+ if (url === jwks)
28
+ return Response.json({ keys: keys.map((k) => k.publicKey) });
29
+ return fallback(input, init);
30
+ });
31
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@company-six/qbosync",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Connect an app to QBO Sync: send invoices and credit memos to QuickBooks, and hear back what happened to them.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
@@ -20,6 +20,10 @@
20
20
  "./supabase": {
21
21
  "types": "./dist/supabase.d.ts",
22
22
  "default": "./dist/supabase.js"
23
+ },
24
+ "./testing": {
25
+ "types": "./dist/testing.d.ts",
26
+ "default": "./dist/testing.js"
23
27
  }
24
28
  },
25
29
  "files": [