@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.
@@ -0,0 +1,88 @@
1
+ import { z } from "zod";
2
+ /** One invoice line. `line_ref` is stable (say, the shop's line item id); credit memos point at it. */
3
+ export declare const invoiceLine: z.ZodObject<{
4
+ line_ref: z.ZodString;
5
+ item_code: z.ZodOptional<z.ZodString>;
6
+ description: z.ZodString;
7
+ quantity: z.ZodNumber;
8
+ unit_price_cents: z.ZodInt;
9
+ amount_cents: z.ZodInt;
10
+ }, z.core.$strict>;
11
+ /**
12
+ * The sale's payment terms: `net_<days>`, due that many days after the invoice date, 1 to 365, with
13
+ * no leading zero (`net_30`). QBO Sync defines what a code means, so every app sends the same words;
14
+ * each company maps a code once to one of its own QuickBooks terms, and an invoice whose code is not
15
+ * mapped WAITS in QBO Sync until it is. An invoice due on receipt carries no code. Any other value
16
+ * is refused here, never stored.
17
+ */
18
+ export declare const termsCode: z.ZodString;
19
+ /**
20
+ * A sale to a customer: posted as an Invoice, plus the commission from `accrued_fees`.
21
+ *
22
+ * Refused on its own: a line whose amount is not quantity × unit price; a total that is
23
+ * not lines + shipping + tax − discount; two lines with the same `line_ref` (a credit
24
+ * memo could not say which one it reverses).
25
+ */
26
+ export declare const invoiceSchema: z.ZodObject<{
27
+ type: z.ZodLiteral<"invoice">;
28
+ number: z.ZodPipe<z.ZodString, z.ZodString>;
29
+ issue_date: z.ZodString;
30
+ due_date: z.ZodOptional<z.ZodString>;
31
+ terms_code: z.ZodOptional<z.ZodString>;
32
+ currency: z.ZodString;
33
+ order_ref: z.ZodOptional<z.ZodString>;
34
+ references: z.ZodOptional<z.ZodArray<z.ZodObject<{
35
+ label: z.ZodString;
36
+ value: z.ZodString;
37
+ }, z.core.$strict>>>;
38
+ class_key: z.ZodOptional<z.ZodString>;
39
+ customer: z.ZodObject<{
40
+ ref: z.ZodString;
41
+ name: z.ZodString;
42
+ company: z.ZodOptional<z.ZodString>;
43
+ email: z.ZodOptional<z.ZodString>;
44
+ bill_to: z.ZodOptional<z.ZodObject<{
45
+ line1: z.ZodOptional<z.ZodString>;
46
+ line2: z.ZodOptional<z.ZodString>;
47
+ city: z.ZodOptional<z.ZodString>;
48
+ region: z.ZodOptional<z.ZodString>;
49
+ postal_code: z.ZodOptional<z.ZodString>;
50
+ country: z.ZodOptional<z.ZodString>;
51
+ }, z.core.$strict>>;
52
+ ship_to: z.ZodOptional<z.ZodObject<{
53
+ line1: z.ZodOptional<z.ZodString>;
54
+ line2: z.ZodOptional<z.ZodString>;
55
+ city: z.ZodOptional<z.ZodString>;
56
+ region: z.ZodOptional<z.ZodString>;
57
+ postal_code: z.ZodOptional<z.ZodString>;
58
+ country: z.ZodOptional<z.ZodString>;
59
+ }, z.core.$strict>>;
60
+ }, z.core.$strict>;
61
+ lines: z.ZodArray<z.ZodObject<{
62
+ line_ref: z.ZodString;
63
+ item_code: z.ZodOptional<z.ZodString>;
64
+ description: z.ZodString;
65
+ quantity: z.ZodNumber;
66
+ unit_price_cents: z.ZodInt;
67
+ amount_cents: z.ZodInt;
68
+ }, z.core.$strict>>;
69
+ shipping_cents: z.ZodInt;
70
+ tax_cents: z.ZodInt;
71
+ discount_cents: z.ZodInt;
72
+ total_cents: z.ZodInt;
73
+ accrued_fees: z.ZodOptional<z.ZodArray<z.ZodObject<{
74
+ code: z.ZodString;
75
+ amount_cents: z.ZodInt;
76
+ description: z.ZodOptional<z.ZodString>;
77
+ }, z.core.$strict>>>;
78
+ schema_version: z.ZodLiteral<"1">;
79
+ source_ref: z.ZodString;
80
+ company_key: z.ZodString;
81
+ version: z.ZodInt;
82
+ status: z.ZodEnum<{
83
+ active: "active";
84
+ voided: "voided";
85
+ }>;
86
+ }, z.core.$strict>;
87
+ export type InvoiceDTO = z.infer<typeof invoiceSchema>;
88
+ export type InvoiceLine = z.infer<typeof invoiceLine>;
@@ -0,0 +1,74 @@
1
+ import { z } from "zod";
2
+ import { cents, currency, customer, docNumber, envelope, fee, isoDate, lineAmountMatches, orderRef, references, sum, text, } from "./common.js";
3
+ /** One invoice line. `line_ref` is stable (say, the shop's line item id); credit memos point at it. */
4
+ export const invoiceLine = z.strictObject({
5
+ line_ref: text,
6
+ item_code: z.string().optional(),
7
+ description: text,
8
+ quantity: z.number().positive("must be more than zero"),
9
+ unit_price_cents: cents,
10
+ amount_cents: cents,
11
+ });
12
+ /**
13
+ * The sale's payment terms: `net_<days>`, due that many days after the invoice date, 1 to 365, with
14
+ * no leading zero (`net_30`). QBO Sync defines what a code means, so every app sends the same words;
15
+ * each company maps a code once to one of its own QuickBooks terms, and an invoice whose code is not
16
+ * mapped WAITS in QBO Sync until it is. An invoice due on receipt carries no code. Any other value
17
+ * is refused here, never stored.
18
+ */
19
+ export const termsCode = z
20
+ .string()
21
+ .regex(/^net_([1-9]|[1-9][0-9]|[12][0-9]{2}|3[0-5][0-9]|36[0-5])$/, "must be net_<days>, the days from 1 to 365 with no leading zero (for example net_30)");
22
+ /**
23
+ * A sale to a customer: posted as an Invoice, plus the commission from `accrued_fees`.
24
+ *
25
+ * Refused on its own: a line whose amount is not quantity × unit price; a total that is
26
+ * not lines + shipping + tax − discount; two lines with the same `line_ref` (a credit
27
+ * memo could not say which one it reverses).
28
+ */
29
+ export const invoiceSchema = z
30
+ .strictObject({
31
+ ...envelope,
32
+ type: z.literal("invoice"),
33
+ number: docNumber,
34
+ issue_date: isoDate,
35
+ due_date: isoDate.optional(),
36
+ terms_code: termsCode.optional(),
37
+ currency,
38
+ order_ref: orderRef.optional(),
39
+ references: references.optional(),
40
+ class_key: z.string().optional(),
41
+ customer,
42
+ lines: z.array(invoiceLine).min(1, "an invoice needs at least one line"),
43
+ shipping_cents: cents,
44
+ tax_cents: cents,
45
+ discount_cents: cents,
46
+ total_cents: cents,
47
+ accrued_fees: z.array(fee).optional(),
48
+ })
49
+ .superRefine((doc, ctx) => {
50
+ doc.lines.forEach((line, i) => {
51
+ if (!lineAmountMatches(line)) {
52
+ ctx.addIssue({
53
+ code: "custom",
54
+ path: ["lines", i, "amount_cents"],
55
+ message: `must equal quantity × unit_price_cents (${line.quantity} × ${line.unit_price_cents})`,
56
+ });
57
+ }
58
+ });
59
+ const seen = new Set();
60
+ doc.lines.forEach((line, i) => {
61
+ if (seen.has(line.line_ref)) {
62
+ ctx.addIssue({ code: "custom", path: ["lines", i, "line_ref"], message: `"${line.line_ref}" is used by another line` });
63
+ }
64
+ seen.add(line.line_ref);
65
+ });
66
+ const expected = sum(doc.lines.map((l) => l.amount_cents)) + doc.shipping_cents + doc.tax_cents - doc.discount_cents;
67
+ if (doc.total_cents !== expected) {
68
+ ctx.addIssue({
69
+ code: "custom",
70
+ path: ["total_cents"],
71
+ message: `must equal lines + shipping + tax − discount (${expected})`,
72
+ });
73
+ }
74
+ });
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The protocol's fixed values. A test in qbosync (`app/__tests__/sdkContract.test.ts`) checks each one
3
+ * against the code that enforces it, so these cannot drift from what QBO Sync does.
4
+ */
5
+ /** Every document type there is. Apps send only `APP_DOCUMENT_TYPES`; status reports may name any of them. */
6
+ export declare const DOCUMENT_TYPES: readonly ["invoice", "credit_memo", "payment", "refund", "payout"];
7
+ export type DocumentType = (typeof DOCUMENT_TYPES)[number];
8
+ /** What an app sends. Payments, refunds and payouts reach QBO Sync through its own connectors, never from an app. */
9
+ export declare const APP_DOCUMENT_TYPES: readonly ["invoice", "credit_memo"];
10
+ /** The most documents one request may carry. */
11
+ export declare const MAX_DOCUMENTS_PER_REQUEST = 100;
12
+ /** The most document refs one report request may name. */
13
+ export declare const MAX_REPORT_REFS = 100;
14
+ /** The most status reports one call from QBO Sync carries. */
15
+ export declare const MAX_STATUS_REPORTS = 100;
16
+ /** Where QBO Sync posts status reports, under the callback address set for the app. */
17
+ export declare const STATUS_REPORT_PATH = "/api/qbosync/status";
18
+ export declare const SIGNATURE_HEADER = "X-QBOSync-Signature";
19
+ /** How far from now a signed call may be, in seconds. */
20
+ export declare const SIGNATURE_TOLERANCE_SECONDS: number;
21
+ /** Where QBO Sync publishes the public keys its calls are checked with. */
22
+ export declare const JWKS_PATH = "/.well-known/jwks.json";
23
+ export declare const TOKEN_PATH = "/api/oauth/token";
24
+ export declare const CONNECT_REQUESTS_PATH = "/api/oauth/requests";
25
+ /** The token route's grant for collecting a connect request. */
26
+ export declare const CONNECT_REQUEST_GRANT = "urn:qbosync:params:oauth:grant-type:connect-request";
27
+ export declare const SIGN_IN_ROLES: readonly ["company_user", "app_admin"];
28
+ export type SignInRole = (typeof SIGN_IN_ROLES)[number];
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The protocol's fixed values. A test in qbosync (`app/__tests__/sdkContract.test.ts`) checks each one
3
+ * against the code that enforces it, so these cannot drift from what QBO Sync does.
4
+ */
5
+ /** Every document type there is. Apps send only `APP_DOCUMENT_TYPES`; status reports may name any of them. */
6
+ export const DOCUMENT_TYPES = ["invoice", "credit_memo", "payment", "refund", "payout"];
7
+ /** What an app sends. Payments, refunds and payouts reach QBO Sync through its own connectors, never from an app. */
8
+ export const APP_DOCUMENT_TYPES = ["invoice", "credit_memo"];
9
+ /** The most documents one request may carry. */
10
+ export const MAX_DOCUMENTS_PER_REQUEST = 100;
11
+ /** The most document refs one report request may name. */
12
+ export const MAX_REPORT_REFS = 100;
13
+ /** The most status reports one call from QBO Sync carries. */
14
+ export const MAX_STATUS_REPORTS = 100;
15
+ /** Where QBO Sync posts status reports, under the callback address set for the app. */
16
+ export const STATUS_REPORT_PATH = "/api/qbosync/status";
17
+ export const SIGNATURE_HEADER = "X-QBOSync-Signature";
18
+ /** How far from now a signed call may be, in seconds. */
19
+ export const SIGNATURE_TOLERANCE_SECONDS = 5 * 60;
20
+ /** Where QBO Sync publishes the public keys its calls are checked with. */
21
+ export const JWKS_PATH = "/.well-known/jwks.json";
22
+ export const TOKEN_PATH = "/api/oauth/token";
23
+ export const CONNECT_REQUESTS_PATH = "/api/oauth/requests";
24
+ /** The token route's grant for collecting a connect request. */
25
+ export const CONNECT_REQUEST_GRANT = "urn:qbosync:params:oauth:grant-type:connect-request";
26
+ export const SIGN_IN_ROLES = ["company_user", "app_admin"];
@@ -0,0 +1,20 @@
1
+ import { z } from "zod";
2
+ /** QBO Sync to the app, never the other way. Apply one only if `sequence` is higher than the one stored for that document. */
3
+ export declare const syncStatusReportSchema: z.ZodObject<{
4
+ source_ref: z.ZodString;
5
+ document_type: z.ZodEnum<{
6
+ invoice: "invoice";
7
+ credit_memo: "credit_memo";
8
+ payment: "payment";
9
+ refund: "refund";
10
+ payout: "payout";
11
+ }>;
12
+ sync_status: z.ZodString;
13
+ synced_at: z.ZodOptional<z.ZodString>;
14
+ qbo_id: z.ZodOptional<z.ZodString>;
15
+ qbo_number: z.ZodOptional<z.ZodString>;
16
+ applied_invoice_numbers: z.ZodOptional<z.ZodArray<z.ZodString>>;
17
+ error: z.ZodOptional<z.ZodString>;
18
+ sequence: z.ZodInt;
19
+ }, z.core.$strict>;
20
+ export type SyncStatusReport = z.infer<typeof syncStatusReportSchema>;
@@ -0,0 +1,17 @@
1
+ import { z } from "zod";
2
+ import { text } from "./common.js";
3
+ import { DOCUMENT_TYPES } from "./protocol.js";
4
+ /** QBO Sync to the app, never the other way. Apply one only if `sequence` is higher than the one stored for that document. */
5
+ export const syncStatusReportSchema = z.strictObject({
6
+ source_ref: text,
7
+ document_type: z.enum(DOCUMENT_TYPES),
8
+ sync_status: text,
9
+ synced_at: z.string().optional(),
10
+ qbo_id: z.string().optional(),
11
+ // The number QuickBooks holds.
12
+ qbo_number: z.string().optional(),
13
+ // Payments: every invoice applied to so far.
14
+ applied_invoice_numbers: z.array(z.string()).optional(),
15
+ error: z.string().optional(),
16
+ sequence: z.int("must be a whole number").min(1, "must be 1 or more"),
17
+ });
@@ -0,0 +1,6 @@
1
+ /** The QBO Sync SDK for an app's server. See README.md. */
2
+ export * from "./contract/index.ts";
3
+ export { QbosyncClient, SIGN_IN_PAGE_PATH, type ConnectionState, type DocumentResult, type Failure, type FailureReason, type QbosyncClientConfig, type SendResult, } from "./client.ts";
4
+ export type { CollectResult, ConnectRequestRow, ConnectRequestStore, NewConnectRequest, OpenResult, RequestRefusal } from "./connectRequest.ts";
5
+ export type { ConnectionRow, ConnectionStore, Log, TokenAnswer } from "./connection.ts";
6
+ export { isNewerReport, verifySignature, type CheckedStatusReports, type InvalidReport, type PublicSigningKey, type StatusReportEntry, type StatusReportResult, } from "./statusReports.ts";
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ /** The QBO Sync SDK for an app's server. See README.md. */
2
+ export * from "./contract/index.js";
3
+ export { QbosyncClient, SIGN_IN_PAGE_PATH, } from "./client.js";
4
+ export { isNewerReport, verifySignature, } from "./statusReports.js";
@@ -0,0 +1,82 @@
1
+ import { type SyncStatusReport } from "./contract/statusReport.ts";
2
+ /**
3
+ * Checking the status reports QBO Sync posts to an app.
4
+ *
5
+ * X-QBOSync-Signature: t=<unix seconds>,kid=<key id>,ed25519=<base64url signature of "<t>." + raw body>
6
+ *
7
+ * QBO Sync signs with a private key only it holds and publishes the PUBLIC keys at
8
+ * `/.well-known/jwks.json`, so an app stores nothing secret for this. The RAW body is checked, byte for
9
+ * byte, before anything is parsed. The timestamp is inside the signed string, and anything more than
10
+ * five minutes from now is refused, so a captured call cannot be replayed later.
11
+ */
12
+ /** One public key as QBO Sync publishes it (RFC 8037). */
13
+ export interface PublicSigningKey {
14
+ kty: "OKP";
15
+ crv: "Ed25519";
16
+ x: string;
17
+ kid: string;
18
+ }
19
+ /** The key id a signature names, or null. */
20
+ export declare function signatureKid(header: string | null | undefined): string | null;
21
+ /** Whether `header` is a valid signature of `body` by one of `keys`, made within the tolerance. Never throws. */
22
+ export declare function verifySignature(keys: readonly PublicSigningKey[], body: string, header: string | null | undefined, now?: number, toleranceSeconds?: number): boolean;
23
+ /** How long after a fetch an unknown key id may fetch again, so made-up key ids cannot cause a fetch per call. */
24
+ export declare const REFETCH_AFTER_MS = 60000;
25
+ /**
26
+ * QBO Sync's public keys, fetched on first use and kept in memory. When a call names a key not held
27
+ * (QBO Sync changed its key) they are fetched again, at most once a minute.
28
+ */
29
+ export declare class SigningKeys {
30
+ private readonly fetchImpl;
31
+ private readonly now;
32
+ private keys;
33
+ private fetchedAt;
34
+ private readonly url;
35
+ constructor(baseUrl: string, fetchImpl?: typeof fetch, now?: () => number);
36
+ private load;
37
+ /** Whether `header` is QBO Sync's valid signature of `raw`. Throws when the keys cannot be fetched. */
38
+ verify(raw: string, header: string | null | undefined): Promise<boolean>;
39
+ }
40
+ /** A report that could not be read, for the answer. */
41
+ export interface InvalidReport {
42
+ index: number;
43
+ source_ref?: string;
44
+ document_type?: string;
45
+ reasons: string[];
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
+ };
55
+ export type CheckedStatusReports =
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
+ */
60
+ {
61
+ ok: true;
62
+ reports: SyncStatusReport[];
63
+ invalid: InvalidReport[];
64
+ entries: StatusReportEntry[];
65
+ }
66
+ /** 400 not a report call, 401 not from QBO Sync, 503 the keys could not be fetched (QBO Sync sends it again). */
67
+ | {
68
+ ok: false;
69
+ status: 400 | 401 | 503;
70
+ error: string;
71
+ };
72
+ /** What the app answers for one report. Anything but `error` is final; an `error`, or a call that does not answer 2xx, is sent again later. */
73
+ export interface StatusReportResult {
74
+ source_ref: string;
75
+ document_type: string;
76
+ result: "applied" | "stale" | "unknown" | "error";
77
+ reason?: string;
78
+ }
79
+ /** Checks one call from QBO Sync: the signature first, over the raw body, then what it carries. Never throws. */
80
+ export declare function checkStatusReports(keys: SigningKeys, rawBody: string, signature: string | null | undefined): Promise<CheckedStatusReports>;
81
+ /** Whether a report should be applied: only one newer than the last applied, so a delayed report never hides a newer one. */
82
+ export declare function isNewerReport(report: Pick<SyncStatusReport, "sequence">, lastAppliedSequence: number | null | undefined): boolean;
@@ -0,0 +1,129 @@
1
+ import crypto from "node:crypto";
2
+ import { formatIssue } from "./contract/index.js";
3
+ import { JWKS_PATH, MAX_STATUS_REPORTS, SIGNATURE_TOLERANCE_SECONDS } from "./contract/protocol.js";
4
+ import { syncStatusReportSchema } from "./contract/statusReport.js";
5
+ function parts(header) {
6
+ return new Map(header.split(",").map((p) => {
7
+ const i = p.indexOf("=");
8
+ return [p.slice(0, i).trim(), p.slice(i + 1).trim()];
9
+ }));
10
+ }
11
+ /** The key id a signature names, or null. */
12
+ export function signatureKid(header) {
13
+ return header ? parts(header).get("kid") || null : null;
14
+ }
15
+ /** Whether `header` is a valid signature of `body` by one of `keys`, made within the tolerance. Never throws. */
16
+ export function verifySignature(keys, body, header, now = Math.floor(Date.now() / 1000), toleranceSeconds = SIGNATURE_TOLERANCE_SECONDS) {
17
+ if (!header)
18
+ return false;
19
+ const p = parts(header);
20
+ const t = Number(p.get("t"));
21
+ if (!Number.isFinite(t) || Math.abs(now - t) > toleranceSeconds)
22
+ return false;
23
+ const jwk = keys.find((k) => k.kid === p.get("kid"));
24
+ if (!jwk)
25
+ return false;
26
+ try {
27
+ // A malformed `x` throws here; a signature of the wrong length is simply false.
28
+ const key = crypto.createPublicKey({ key: { kty: jwk.kty, crv: jwk.crv, x: jwk.x }, format: "jwk" });
29
+ return crypto.verify(null, Buffer.from(`${t}.${body}`, "utf8"), key, Buffer.from(p.get("ed25519") ?? "", "base64url"));
30
+ }
31
+ catch {
32
+ return false;
33
+ }
34
+ }
35
+ /** How long after a fetch an unknown key id may fetch again, so made-up key ids cannot cause a fetch per call. */
36
+ export const REFETCH_AFTER_MS = 60_000;
37
+ const FETCH_TIMEOUT_MS = 5_000;
38
+ async function fetchKeys(url, fetchImpl) {
39
+ const res = await fetchImpl(url, { cache: "no-store", signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
40
+ if (!res.ok)
41
+ throw new Error(`${url} answered ${res.status}`);
42
+ const body = (await res.json().catch(() => null));
43
+ if (!body || !Array.isArray(body.keys))
44
+ throw new Error(`${url} did not answer a key list`);
45
+ return body.keys.filter((k) => {
46
+ const key = k;
47
+ return !!key && key.kty === "OKP" && key.crv === "Ed25519" && typeof key.x === "string" && typeof key.kid === "string";
48
+ });
49
+ }
50
+ /**
51
+ * QBO Sync's public keys, fetched on first use and kept in memory. When a call names a key not held
52
+ * (QBO Sync changed its key) they are fetched again, at most once a minute.
53
+ */
54
+ export class SigningKeys {
55
+ fetchImpl;
56
+ now;
57
+ keys = null;
58
+ fetchedAt = 0;
59
+ url;
60
+ constructor(baseUrl, fetchImpl = fetch, now = Date.now) {
61
+ this.fetchImpl = fetchImpl;
62
+ this.now = now;
63
+ this.url = `${baseUrl}${JWKS_PATH}`;
64
+ }
65
+ async load() {
66
+ this.keys = await fetchKeys(this.url, this.fetchImpl);
67
+ this.fetchedAt = this.now();
68
+ return this.keys;
69
+ }
70
+ /** Whether `header` is QBO Sync's valid signature of `raw`. Throws when the keys cannot be fetched. */
71
+ async verify(raw, header) {
72
+ const keys = this.keys ?? (await this.load());
73
+ if (verifySignature(keys, raw, header))
74
+ return true;
75
+ const kid = signatureKid(header);
76
+ if (kid === null || keys.some((k) => k.kid === kid) || this.now() - this.fetchedAt < REFETCH_AFTER_MS)
77
+ return false;
78
+ return verifySignature(await this.load(), raw, header);
79
+ }
80
+ }
81
+ /** Checks one call from QBO Sync: the signature first, over the raw body, then what it carries. Never throws. */
82
+ export async function checkStatusReports(keys, rawBody, signature) {
83
+ let signed;
84
+ try {
85
+ signed = await keys.verify(rawBody, signature);
86
+ }
87
+ catch (err) {
88
+ return { ok: false, status: 503, error: `QBO Sync's public keys could not be fetched: ${err instanceof Error ? err.message : String(err)}` };
89
+ }
90
+ if (!signed)
91
+ return { ok: false, status: 401, error: "Unauthorized" };
92
+ let body;
93
+ try {
94
+ body = JSON.parse(rawBody);
95
+ }
96
+ catch {
97
+ return { ok: false, status: 400, error: "Invalid JSON" };
98
+ }
99
+ const list = body?.reports;
100
+ if (!Array.isArray(list) || list.length === 0)
101
+ return { ok: false, status: 400, error: "Send { reports: [...] } with at least one report" };
102
+ if (list.length > MAX_STATUS_REPORTS)
103
+ return { ok: false, status: 400, error: `At most ${MAX_STATUS_REPORTS} reports a request; this one has ${list.length}` };
104
+ const reports = [];
105
+ const invalid = [];
106
+ const entries = [];
107
+ list.forEach((entry, index) => {
108
+ const parsed = syncStatusReportSchema.safeParse(entry);
109
+ if (parsed.success) {
110
+ reports.push(parsed.data);
111
+ entries.push({ index, report: parsed.data });
112
+ return;
113
+ }
114
+ const e = (entry ?? {});
115
+ const bad = {
116
+ index,
117
+ ...(typeof e.source_ref === "string" ? { source_ref: e.source_ref } : {}),
118
+ ...(typeof e.document_type === "string" ? { document_type: e.document_type } : {}),
119
+ reasons: parsed.error.issues.map(formatIssue),
120
+ };
121
+ invalid.push(bad);
122
+ entries.push({ index, invalid: bad });
123
+ });
124
+ return { ok: true, reports, invalid, entries };
125
+ }
126
+ /** Whether a report should be applied: only one newer than the last applied, so a delayed report never hides a newer one. */
127
+ export function isNewerReport(report, lastAppliedSequence) {
128
+ return report.sequence > (lastAppliedSequence ?? 0);
129
+ }
@@ -0,0 +1,38 @@
1
+ import type { ConnectRequestStore } from "./connectRequest.ts";
2
+ import type { ConnectionStore } from "./connection.ts";
3
+ /**
4
+ * The connection's stores on Supabase: the tables and functions of `sql/001_connection.sql`, through a
5
+ * SERVICE-ROLE client. The tables hold the app's tokens and have row level security on with no policy,
6
+ * so no other client can read them.
7
+ *
8
+ * `client` only has to look like supabase-js, so this package does not depend on it. Another database
9
+ * implements `ConnectionStore` and `ConnectRequestStore` instead.
10
+ */
11
+ interface DbError {
12
+ message?: string;
13
+ }
14
+ interface DbAnswer {
15
+ data: unknown;
16
+ error: DbError | null;
17
+ }
18
+ /** The parts of a supabase-js client this uses. */
19
+ export interface SupabaseLike {
20
+ from(table: string): {
21
+ select(columns: string): {
22
+ eq(column: string, value: number): {
23
+ maybeSingle(): PromiseLike<DbAnswer>;
24
+ };
25
+ };
26
+ upsert(row: Record<string, unknown>, options: {
27
+ onConflict: string;
28
+ }): PromiseLike<{
29
+ error: DbError | null;
30
+ }>;
31
+ };
32
+ rpc(name: string, args: Record<string, unknown>): PromiseLike<DbAnswer>;
33
+ }
34
+ export declare function createSupabaseStores(client: SupabaseLike): {
35
+ connections: ConnectionStore;
36
+ connectRequests: ConnectRequestStore;
37
+ };
38
+ export {};
@@ -0,0 +1,67 @@
1
+ const CONNECTION_COLUMNS = "base_url, client_id, redirect_uri, refresh_token, access_token, access_expires_at, connected_by, connected_at, renewed_at, ended_at, ended_reason";
2
+ const REQUEST_COLUMNS = "base_url, request_id, code_verifier, client_id, redirect_uri, started_by, started_at, outcome, outcome_detail, finished_at";
3
+ function fail(what, error) {
4
+ throw new Error(`${what}: ${error.message ?? "unknown error"}`);
5
+ }
6
+ export function createSupabaseStores(client) {
7
+ const call = async (name, args) => {
8
+ const { data, error } = await client.rpc(name, args);
9
+ if (error)
10
+ fail(name, error);
11
+ return data === true;
12
+ };
13
+ const readRow = async (table, columns) => {
14
+ const { data, error } = await client.from(table).select(columns).eq("id", 1).maybeSingle();
15
+ if (error)
16
+ fail(`${table} read`, error);
17
+ return data ?? null;
18
+ };
19
+ const connections = {
20
+ read: () => readRow("qbosync_connection", CONNECTION_COLUMNS),
21
+ claimRenewal: (refreshToken, seconds) => call("qbosync_claim_renewal", { p_refresh_token: refreshToken, p_seconds: seconds }),
22
+ saveRenewal: (oldRefreshToken, answer) => call("qbosync_save_renewal", {
23
+ p_old_refresh_token: oldRefreshToken,
24
+ p_refresh_token: answer.refreshToken,
25
+ p_access_token: answer.accessToken,
26
+ p_expires_in: answer.expiresIn,
27
+ }),
28
+ async releaseRenewal(refreshToken) {
29
+ await call("qbosync_release_renewal", { p_refresh_token: refreshToken });
30
+ },
31
+ endConnection: (refreshToken, reason) => call("qbosync_end_connection", { p_refresh_token: refreshToken, p_reason: reason }),
32
+ };
33
+ const connectRequests = {
34
+ read: () => readRow("qbosync_connect_request", REQUEST_COLUMNS),
35
+ async open(r) {
36
+ const { error } = await client.from("qbosync_connect_request").upsert({
37
+ id: 1,
38
+ base_url: r.baseUrl,
39
+ request_id: r.requestId,
40
+ code_verifier: r.verifier,
41
+ client_id: r.clientId,
42
+ redirect_uri: r.redirectUri,
43
+ started_by: r.startedBy,
44
+ started_at: new Date().toISOString(),
45
+ collect_claimed_until: null,
46
+ outcome: null,
47
+ outcome_detail: null,
48
+ finished_at: null,
49
+ }, { onConflict: "id" });
50
+ if (error)
51
+ fail("qbosync_connect_request open", error);
52
+ },
53
+ claim: (requestId, seconds) => call("qbosync_claim_connect_request", { p_request_id: requestId, p_seconds: seconds }),
54
+ async release(requestId) {
55
+ await call("qbosync_release_connect_request", { p_request_id: requestId });
56
+ },
57
+ finish: (requestId, outcome, detail) => call("qbosync_finish_connect_request", { p_request_id: requestId, p_outcome: outcome, p_detail: detail }),
58
+ saveCollected: (requestId, clientId, answer) => call("qbosync_save_collected_connection", {
59
+ p_request_id: requestId,
60
+ p_client_id: clientId,
61
+ p_refresh_token: answer.refreshToken,
62
+ p_access_token: answer.accessToken,
63
+ p_expires_in: answer.expiresIn,
64
+ }),
65
+ };
66
+ return { connections, connectRequests };
67
+ }
@@ -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
+ }