@neuctra/finance 0.0.0-stage → 1.0.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
@@ -1,3 +1,136 @@
1
- # Temporary Holding Version
1
+ # @neuctra/finance
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Record where business money goes from any JavaScript app. Zero dependencies.
4
+ Works in Node.js 18+, browsers, React and Next.js.
5
+
6
+ ```bash
7
+ npm install @neuctra/finance
8
+ ```
9
+
10
+ ```js
11
+ import { NeuctraFinance } from "@neuctra/finance";
12
+
13
+ const finance = new NeuctraFinance({
14
+ serverUrl: process.env.NEUCTRA_FINANCE_URL,
15
+ apiKey: process.env.NEUCTRA_FINANCE_KEY, // nf_sk_... from the dashboard
16
+ });
17
+
18
+ const { account } = await finance.expenses.record({
19
+ accountId: "acc_3f9a1c",
20
+ amount: 12000,
21
+ category: "Rent",
22
+ reference: "RENT-2026-11",
23
+ });
24
+ console.log("Left:", account.balance);
25
+ ```
26
+
27
+ ## When an account runs out
28
+
29
+ ```js
30
+ try {
31
+ await finance.expenses.record({ accountId, amount: 6000 });
32
+ } catch (err) {
33
+ if (err.isInsufficientFunds) {
34
+ console.log(err.details); // { balance, held, available, requested, shortBy, currency, accountId }
35
+ }
36
+ }
37
+
38
+ await finance.accounts.canSpend(accountId, 6000); // true or false (counts held money as spent)
39
+ ```
40
+
41
+ ## Reserve first, spend later (holds)
42
+
43
+ Like a card payment: reserve the money when an order is placed, then spend what it really cost.
44
+ Reserved money cannot be spent by anything else. Server keys with the `holds:write` permission only.
45
+
46
+ ```js
47
+ const { hold } = await finance.holds.authorize({ accountId, amount: 500, description: "Stock order" });
48
+ await finance.holds.capture(hold.id, { amount: 480 }); // the real cost, up to the held amount
49
+ // or give it back: await finance.holds.void(hold.id);
50
+ ```
51
+
52
+ A hold expires after 7 days (pass `expiresInMinutes`, up to 30 days, to change that) and its
53
+ money comes back by itself.
54
+
55
+ ## Approvals
56
+
57
+ When an account has an approval line, spending above it is refused with `APPROVAL_REQUIRED`.
58
+ Ask instead:
59
+
60
+ ```js
61
+ try {
62
+ await finance.expenses.record({ accountId, amount: 25000 });
63
+ } catch (err) {
64
+ if (err.isApprovalRequired) {
65
+ const request = await finance.spendRequests.create({ accountId, amount: 25000, description: "New laptop" });
66
+ // Later: once approved, request.holdId is set. Capture that hold when you pay.
67
+ const decided = await finance.spendRequests.get(request.id);
68
+ if (decided.status === "approved") await finance.holds.capture(decided.holdId);
69
+ }
70
+ }
71
+ ```
72
+
73
+ ## Mistakes
74
+
75
+ Transactions are never edited. Undo one with an opposite entry (`reversals:write` permission):
76
+
77
+ ```js
78
+ await finance.transactions.reverse(transactionId, { reason: "Charged the wrong account" });
79
+ ```
80
+
81
+ ## Everything else
82
+
83
+ ```js
84
+ await finance.me(); // business and key permissions
85
+ await finance.summary(); // balance, invested, spent, debts, low accounts
86
+ await finance.accounts.list();
87
+ await finance.accounts.get(accountId); // balance, held, available
88
+
89
+ await finance.income.record({ accountId, amount, category });
90
+ await finance.transfers.create({ fromAccountId, toAccountId, amount });
91
+
92
+ await finance.transactions.list({ accountId, kind: "expense", limit: 50, cursor });
93
+ for await (const t of finance.transactions.iterate({ accountId })) { /* every page */ }
94
+
95
+ await finance.debts.create({ direction: "payable", counterparty: "City Bank", amount: 50000, accountId });
96
+ await finance.debts.pay(debtId, { amount: 5000 });
97
+ await finance.debts.list({ status: "open" });
98
+ ```
99
+
100
+ Amounts are in major units with the currency's decimals (`1500.5` means 1,500.50; yen has none).
101
+
102
+ ## Webhooks
103
+
104
+ Your server gets a signed POST when money moves, a hold changes or a request is decided. Check
105
+ it with the endpoint's `nf_whsec_` secret, using the raw body exactly as received:
106
+
107
+ ```js
108
+ import { verifyWebhook } from "@neuctra/finance";
109
+
110
+ app.post("/neuctra", express.text({ type: "*/*" }), async (req, res) => {
111
+ const event = await verifyWebhook(req.get("Neuctra-Signature"), req.body, process.env.NEUCTRA_WEBHOOK_SECRET);
112
+ // event.id is unique: ignore ids you have already handled.
113
+ res.sendStatus(200);
114
+ });
115
+ ```
116
+
117
+ ## Retries
118
+
119
+ Every write sends an idempotency key, which the SDK generates when you do not pass one. Network
120
+ errors, 502/503/504 responses and `BUSY` answers are retried with the same key, so nothing is
121
+ recorded twice. Pass your own `idempotencyKey` (for example a purchase-order number) to stay safe
122
+ across process restarts too.
123
+
124
+ ## Limits
125
+
126
+ Each key is limited per minute (`RATE_LIMITED`, wait for `Retry-After`). The business owner's
127
+ plan also allows a number of API requests a month (`PLAN_LIMIT`, `err.isPlanLimit`); it resets
128
+ on the 1st (UTC).
129
+
130
+ ## Keys in the browser
131
+
132
+ Server keys (`nf_sk_`) throw if used in a browser. For browser apps, create a public key
133
+ (`nf_pk_`) in the dashboard, list your website on it, and give it a per-transaction limit.
134
+
135
+ Errors are `NeuctraFinanceError` with `status`, `code`, `message`, `hint` and `details`. The full
136
+ API is described at `GET /v1/openapi.json` on your server.
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "@neuctra/finance",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Record expenses, income, transfers and debts, reserve money with holds and ask for spending approval against your Neuctra Finance accounts from any JavaScript app.",
5
+ "type": "module",
6
+ "main": "./src/index.js",
7
+ "module": "./src/index.js",
8
+ "types": "./src/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./src/index.d.ts",
12
+ "import": "./src/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "src",
17
+ "README.md"
18
+ ],
19
+ "sideEffects": false,
20
+ "engines": {
21
+ "node": ">=18"
22
+ },
23
+ "keywords": [
24
+ "neuctra",
25
+ "finance",
26
+ "ledger",
27
+ "expenses",
28
+ "accounting",
29
+ "sdk"
30
+ ],
31
+ "license": "MIT"
32
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,349 @@
1
+ export type AccountType = "investment" | "operating" | "savings" | "petty_cash";
2
+ export type AccountStatus = "active" | "frozen" | "closed";
3
+ export type TransactionKind =
4
+ | "investment"
5
+ | "income"
6
+ | "loan_received"
7
+ | "debt_collected"
8
+ | "transfer_in"
9
+ | "expense"
10
+ | "withdrawal"
11
+ | "loan_given"
12
+ | "debt_paid"
13
+ | "transfer_out"
14
+ | "reversal";
15
+ export type Scope =
16
+ | "read"
17
+ | "expenses:write"
18
+ | "income:write"
19
+ | "transfers:write"
20
+ | "debts:write"
21
+ | "holds:write"
22
+ | "requests:write"
23
+ | "reversals:write";
24
+
25
+ export interface Account {
26
+ id: string;
27
+ name: string;
28
+ type: AccountType;
29
+ status: AccountStatus;
30
+ currency: string;
31
+ /** Money in the account. Never below zero. */
32
+ balance: number;
33
+ /** Part of the balance reserved by holds. */
34
+ held: number;
35
+ /** What can be spent right now: balance minus held. */
36
+ available: number;
37
+ /** Spending above this needs an approved spend request. null = never. */
38
+ approvalAbove: number | null;
39
+ totalIn: number;
40
+ totalOut: number;
41
+ /** Total the owner has invested into this account. */
42
+ invested: number;
43
+ /** Total recorded as expenses. */
44
+ spent: number;
45
+ lowBalanceAlert: number | null;
46
+ isLow: boolean;
47
+ description: string | null;
48
+ lastActivityAt: string | null;
49
+ }
50
+
51
+ export interface Transaction {
52
+ id: string;
53
+ accountId: string;
54
+ accountName: string | null;
55
+ kind: TransactionKind;
56
+ direction: "in" | "out";
57
+ amount: number;
58
+ /** The account balance right after this transaction. */
59
+ balanceAfter: number;
60
+ currency: string;
61
+ category: string | null;
62
+ description: string | null;
63
+ reference: string | null;
64
+ counterparty: string | null;
65
+ debtId: string | null;
66
+ transferId: string | null;
67
+ holdId: string | null;
68
+ requestId: string | null;
69
+ /** On a reversal: the transaction it undoes. */
70
+ reversalOf: string | null;
71
+ /** On a reversed transaction: the reversal that undid it. */
72
+ reversedBy: string | null;
73
+ reconciled: boolean;
74
+ idempotencyKey: string | null;
75
+ metadata: Record<string, unknown> | null;
76
+ source: { kind: "dashboard"; by?: string } | { kind: "api"; keyId: string; keyName: string } | { kind: "schedule"; by: string };
77
+ /** The month it belongs to, like "2026-11", in the business's timezone. */
78
+ period: string | null;
79
+ occurredAt: string;
80
+ }
81
+
82
+ export interface Hold {
83
+ id: string;
84
+ accountId: string;
85
+ accountName: string | null;
86
+ amount: number;
87
+ /** How much was spent when it was captured. */
88
+ captured: number | null;
89
+ currency: string;
90
+ status: "authorized" | "captured" | "voided" | "expired";
91
+ expiresAt: string;
92
+ category: string | null;
93
+ description: string | null;
94
+ reference: string | null;
95
+ counterparty: string | null;
96
+ requestId: string | null;
97
+ transactionId: string | null;
98
+ authorizedAt: string | null;
99
+ }
100
+
101
+ export interface SpendRequest {
102
+ id: string;
103
+ accountId: string;
104
+ accountName: string | null;
105
+ amount: number;
106
+ currency: string;
107
+ status: "pending" | "approved" | "denied" | "cancelled" | "expired";
108
+ category: string | null;
109
+ description: string | null;
110
+ counterparty: string | null;
111
+ reference: string | null;
112
+ receiptUrl: string | null;
113
+ /** Why it was denied. */
114
+ reason: string | null;
115
+ /** Set once approved: capture this hold when you pay. */
116
+ holdId: string | null;
117
+ requestedAt: string | null;
118
+ decidedAt: string | null;
119
+ expiresAt: string | null;
120
+ }
121
+
122
+ export interface Debt {
123
+ id: string;
124
+ /** payable: the business owes. receivable: the business is owed. */
125
+ direction: "payable" | "receivable";
126
+ counterparty: string;
127
+ currency: string;
128
+ principal: number;
129
+ outstanding: number;
130
+ paid: number;
131
+ status: "open" | "settled" | "cancelled";
132
+ dueDate: string | null;
133
+ isOverdue: boolean;
134
+ accountId: string | null;
135
+ notes: string | null;
136
+ openedAt: string | null;
137
+ settledAt: string | null;
138
+ }
139
+
140
+ export interface Summary {
141
+ business: { id: string; name: string; currency: string; timezone: string; createdAt: string | null };
142
+ currency: string;
143
+ balance: number;
144
+ invested: number;
145
+ spent: number;
146
+ totalIn: number;
147
+ totalOut: number;
148
+ /** Outstanding on open payables. */
149
+ owed: number;
150
+ /** Outstanding on open receivables. */
151
+ owedToYou: number;
152
+ netPosition: number;
153
+ accounts: number;
154
+ lowAccounts: string[];
155
+ openDebts: number;
156
+ }
157
+
158
+ export interface MovementDetails {
159
+ /** e.g. "Ads", "Rent", "Salaries" */
160
+ category?: string;
161
+ description?: string;
162
+ /** Your own id: invoice number, order id, payroll run. */
163
+ reference?: string;
164
+ counterparty?: string;
165
+ metadata?: Record<string, unknown>;
166
+ /** When it happened, if not now. ISO date or date-time. Not before the business's lock date. */
167
+ occurredAt?: string;
168
+ /** Generated for you when omitted. Reuse it to retry safely. */
169
+ idempotencyKey?: string;
170
+ }
171
+
172
+ export interface MoneyInput extends MovementDetails {
173
+ accountId: string;
174
+ /** In major units: 1500.5 means 1,500.50. Decimals follow the currency (0 for JPY, 3 for KWD). */
175
+ amount: number;
176
+ }
177
+
178
+ export interface MovementResult {
179
+ transaction: Transaction;
180
+ account: Account;
181
+ /** True when this was a repeat of an earlier request with the same idempotency key. */
182
+ replayed: boolean;
183
+ }
184
+
185
+ export interface TransferInput extends MovementDetails {
186
+ fromAccountId: string;
187
+ toAccountId: string;
188
+ amount: number;
189
+ }
190
+
191
+ export interface TransferResult {
192
+ transferId: string;
193
+ from?: Account;
194
+ to?: Account;
195
+ transactions?: [Transaction, Transaction];
196
+ replayed: boolean;
197
+ }
198
+
199
+ export interface CreateDebtInput {
200
+ direction: "payable" | "receivable";
201
+ counterparty: string;
202
+ amount: number;
203
+ /** When set, the cash moves too: a loan lands in (payable) or leaves (receivable) this account. */
204
+ accountId?: string;
205
+ dueDate?: string;
206
+ notes?: string;
207
+ description?: string;
208
+ idempotencyKey?: string;
209
+ }
210
+
211
+ export interface DebtResult {
212
+ debt: Debt;
213
+ transaction: Transaction | null;
214
+ account: Account | null;
215
+ replayed: boolean;
216
+ }
217
+
218
+ export interface DebtPaymentInput extends MovementDetails {
219
+ amount: number;
220
+ /** Defaults to the account the debt was opened with. */
221
+ accountId?: string;
222
+ }
223
+
224
+ export interface HoldInput extends Omit<MovementDetails, "occurredAt"> {
225
+ accountId: string;
226
+ amount: number;
227
+ /** How long the money stays reserved. Default 10080 (7 days), at most 43200 (30 days). */
228
+ expiresInMinutes?: number;
229
+ }
230
+
231
+ export interface CaptureInput extends MovementDetails {
232
+ /** Defaults to the held amount. Can be less, never more. */
233
+ amount?: number;
234
+ }
235
+
236
+ export interface CaptureResult {
237
+ hold: Hold;
238
+ transaction: Transaction;
239
+ account: Account;
240
+ replayed: boolean;
241
+ }
242
+
243
+ export interface SpendRequestInput {
244
+ accountId: string;
245
+ amount: number;
246
+ /** What the money is for. Required. */
247
+ description: string;
248
+ category?: string;
249
+ counterparty?: string;
250
+ reference?: string;
251
+ /** A link to a quote or invoice the approver can check. */
252
+ receiptUrl?: string;
253
+ idempotencyKey?: string;
254
+ }
255
+
256
+ export interface Page<T> {
257
+ data: T[];
258
+ nextCursor: string | null;
259
+ }
260
+
261
+ export interface NeuctraFinanceConfig {
262
+ serverUrl: string;
263
+ /** nf_sk_... on a server, nf_pk_... in a browser. */
264
+ apiKey: string;
265
+ timeoutMs?: number;
266
+ /** Retries for network errors, 502/503/504 and BUSY. Default 2. */
267
+ retries?: number;
268
+ fetch?: typeof fetch;
269
+ }
270
+
271
+ export declare class NeuctraFinanceError extends Error {
272
+ status: number;
273
+ code: string;
274
+ hint: string | null;
275
+ details: Record<string, any> | null;
276
+ readonly isInsufficientFunds: boolean;
277
+ readonly isApprovalRequired: boolean;
278
+ /** The business owner's plan allowance is used up (for example API requests this month). */
279
+ readonly isPlanLimit: boolean;
280
+ }
281
+
282
+ export declare class NeuctraFinance {
283
+ constructor(config: NeuctraFinanceConfig);
284
+ me(): Promise<{
285
+ business: Summary["business"];
286
+ key: { id: string; name: string; type: "server" | "public"; scopes: Scope[]; accountIds: string[]; maxAmount: number | null };
287
+ }>;
288
+ summary(): Promise<Summary>;
289
+ accounts: {
290
+ list(): Promise<Account[]>;
291
+ get(accountId: string): Promise<Account>;
292
+ canSpend(accountId: string, amount: number): Promise<boolean>;
293
+ };
294
+ expenses: { record(input: MoneyInput): Promise<MovementResult> };
295
+ income: { record(input: MoneyInput): Promise<MovementResult> };
296
+ transfers: { create(input: TransferInput): Promise<TransferResult> };
297
+ holds: {
298
+ authorize(input: HoldInput): Promise<{ hold: Hold; replayed: boolean }>;
299
+ get(holdId: string): Promise<Hold>;
300
+ capture(holdId: string, input?: CaptureInput): Promise<CaptureResult>;
301
+ void(holdId: string): Promise<Hold>;
302
+ };
303
+ spendRequests: {
304
+ create(input: SpendRequestInput): Promise<SpendRequest>;
305
+ get(requestId: string): Promise<SpendRequest>;
306
+ cancel(requestId: string): Promise<SpendRequest>;
307
+ };
308
+ transactions: {
309
+ list(query?: { accountId?: string; kind?: TransactionKind; limit?: number; cursor?: string }): Promise<Page<Transaction>>;
310
+ get(transactionId: string): Promise<Transaction>;
311
+ iterate(query?: { accountId?: string; kind?: TransactionKind }): AsyncGenerator<Transaction, void, unknown>;
312
+ reverse(transactionId: string, input: { reason: string }): Promise<{ reversals: Transaction[]; accounts: Account[] }>;
313
+ };
314
+ debts: {
315
+ list(query?: { status?: "open" | "settled" | "cancelled"; direction?: "payable" | "receivable" }): Promise<Debt[]>;
316
+ get(debtId: string): Promise<Debt>;
317
+ create(input: CreateDebtInput): Promise<DebtResult>;
318
+ pay(debtId: string, input: DebtPaymentInput): Promise<DebtResult | MovementResult>;
319
+ };
320
+ }
321
+
322
+ export interface WebhookEvent<T = Record<string, any>> {
323
+ /** Ignore ids you have already handled. */
324
+ id: string;
325
+ type:
326
+ | "transaction.created"
327
+ | "transaction.reversed"
328
+ | "hold.authorized"
329
+ | "hold.captured"
330
+ | "hold.voided"
331
+ | "spend_request.created"
332
+ | "spend_request.approved"
333
+ | "spend_request.denied"
334
+ | "account.low_balance"
335
+ | "budget.threshold";
336
+ createdAt: string;
337
+ businessId: string;
338
+ data: T;
339
+ }
340
+
341
+ /** Checks the Neuctra-Signature header against the raw body and your nf_whsec_ secret. */
342
+ export declare function verifyWebhook(
343
+ signatureHeader: string,
344
+ rawBody: string,
345
+ secret: string,
346
+ options?: { toleranceSeconds?: number },
347
+ ): Promise<WebhookEvent>;
348
+
349
+ export default NeuctraFinance;
package/src/index.js ADDED
@@ -0,0 +1,233 @@
1
+ // @neuctra/finance: one call to record where business money goes.
2
+ // Zero dependencies. Works in Node 18+, browsers, React and Next.js.
3
+
4
+ const RETRYABLE = new Set([502, 503, 504]);
5
+
6
+ export class NeuctraFinanceError extends Error {
7
+ constructor({ status = 0, code = "NETWORK_ERROR", message, hint = null, details = null }) {
8
+ super(message);
9
+ this.name = "NeuctraFinanceError";
10
+ this.status = status;
11
+ this.code = code;
12
+ this.hint = hint;
13
+ this.details = details;
14
+ }
15
+
16
+ /** The account does not hold enough money. `details` has balance, held, available, requested and shortBy. */
17
+ get isInsufficientFunds() {
18
+ return this.code === "INSUFFICIENT_FUNDS";
19
+ }
20
+
21
+ /** The amount is above the account's approval line. Send a spend request instead. */
22
+ get isApprovalRequired() {
23
+ return this.code === "APPROVAL_REQUIRED";
24
+ }
25
+
26
+ /** The business owner's plan allowance is used up (for example API requests this month). */
27
+ get isPlanLimit() {
28
+ return this.code === "PLAN_LIMIT";
29
+ }
30
+ }
31
+
32
+ const newIdempotencyKey = () =>
33
+ globalThis.crypto?.randomUUID?.() ?? `nf-${Date.now()}-${Math.random().toString(16).slice(2)}`;
34
+
35
+ const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
36
+
37
+ export class NeuctraFinance {
38
+ /**
39
+ * @param {object} config
40
+ * @param {string} config.serverUrl Your Neuctra Finance API, e.g. https://finance-api.example.com
41
+ * @param {string} config.apiKey nf_sk_... on a server, nf_pk_... in a browser
42
+ * @param {number} [config.timeoutMs=15000]
43
+ * @param {number} [config.retries=2] Retries for network errors and 502/503/504
44
+ * @param {typeof fetch} [config.fetch]
45
+ */
46
+ constructor({ serverUrl, apiKey, timeoutMs = 15000, retries = 2, fetch: fetchImpl } = {}) {
47
+ if (!serverUrl) throw new Error("NeuctraFinance: serverUrl is required.");
48
+ if (!apiKey) throw new Error("NeuctraFinance: apiKey is required.");
49
+ if (typeof window !== "undefined" && apiKey.startsWith("nf_sk_")) {
50
+ throw new Error(
51
+ "NeuctraFinance: server keys (nf_sk_) must never ship to a browser. Use a public key (nf_pk_) here.",
52
+ );
53
+ }
54
+ this.serverUrl = serverUrl.replace(/\/+$/, "");
55
+ this.apiKey = apiKey;
56
+ this.timeoutMs = timeoutMs;
57
+ this.retries = retries;
58
+ this.fetch = fetchImpl || globalThis.fetch.bind(globalThis);
59
+
60
+ this.accounts = {
61
+ list: () => this.request("GET", "/v1/accounts").then((r) => r.data),
62
+ get: (accountId) => this.request("GET", `/v1/accounts/${enc(accountId)}`).then((r) => r.account),
63
+ /** True when the account is active and at least `amount` is available (not held). */
64
+ canSpend: async (accountId, amount) => {
65
+ const account = await this.accounts.get(accountId);
66
+ return account.status === "active" && account.available >= amount;
67
+ },
68
+ };
69
+
70
+ // Reserve money before you spend it, like a card payment (server keys only).
71
+ this.holds = {
72
+ /** Reserves `amount`. Refused when it is not available. */
73
+ authorize: (input) => this.write("/v1/holds", input),
74
+ get: (holdId) => this.request("GET", `/v1/holds/${enc(holdId)}`).then((r) => r.hold),
75
+ /** Spends the held amount, or less. Capturing twice returns the first result. */
76
+ capture: (holdId, input = {}) => this.write(`/v1/holds/${enc(holdId)}/capture`, input),
77
+ /** Gives the held money back. */
78
+ void: (holdId) => this.request("POST", `/v1/holds/${enc(holdId)}/void`).then((r) => r.hold),
79
+ };
80
+
81
+ // Ask for approval when an amount is above the account's approval line.
82
+ this.spendRequests = {
83
+ create: (input) => this.write("/v1/spend-requests", input).then((r) => r.request),
84
+ /** Once approved, `holdId` is set: capture that hold when you pay. */
85
+ get: (requestId) => this.request("GET", `/v1/spend-requests/${enc(requestId)}`).then((r) => r.request),
86
+ cancel: (requestId) => this.request("POST", `/v1/spend-requests/${enc(requestId)}/cancel`).then((r) => r.request),
87
+ };
88
+
89
+ this.expenses = {
90
+ /** Deducts money from an account. Refused with INSUFFICIENT_FUNDS when it would go below zero. */
91
+ record: (input) => this.write("/v1/expenses", input),
92
+ };
93
+
94
+ this.income = {
95
+ record: (input) => this.write("/v1/income", input),
96
+ };
97
+
98
+ this.transfers = {
99
+ create: (input) => this.write("/v1/transfers", input),
100
+ };
101
+
102
+ this.transactions = {
103
+ list: (query = {}) => this.request("GET", "/v1/transactions", { query }),
104
+ get: (transactionId) =>
105
+ this.request("GET", `/v1/transactions/${enc(transactionId)}`).then((r) => r.transaction),
106
+ /** Undoes a transaction with an opposite one. `reason` is required. */
107
+ reverse: (transactionId, { reason }) =>
108
+ this.write(`/v1/transactions/${enc(transactionId)}/reverse`, { reason }),
109
+ /** Walks every page: for await (const t of finance.transactions.iterate({ accountId })) */
110
+ iterate: async function* iterate(query = {}) {
111
+ let cursor;
112
+ do {
113
+ const page = await this.list({ ...query, cursor, limit: 100 });
114
+ yield* page.data;
115
+ cursor = page.nextCursor;
116
+ } while (cursor);
117
+ },
118
+ };
119
+
120
+ this.debts = {
121
+ list: (query = {}) => this.request("GET", "/v1/debts", { query }).then((r) => r.data),
122
+ get: (debtId) => this.request("GET", `/v1/debts/${enc(debtId)}`).then((r) => r.debt),
123
+ create: (input) => this.write("/v1/debts", input),
124
+ /** Pays a payable or collects a receivable, fully or in part. */
125
+ pay: (debtId, input) => this.write(`/v1/debts/${enc(debtId)}/payments`, input),
126
+ };
127
+ }
128
+
129
+ /** The business and permissions this key belongs to. */
130
+ me() {
131
+ return this.request("GET", "/v1/me");
132
+ }
133
+
134
+ /** Total balance, invested, spent, debts and accounts running low. */
135
+ summary() {
136
+ return this.request("GET", "/v1/summary");
137
+ }
138
+
139
+ // Every write carries an idempotency key, so a retry after a timeout can
140
+ // never record the same expense twice.
141
+ write(path, input = {}) {
142
+ const idempotencyKey = input.idempotencyKey || newIdempotencyKey();
143
+ return this.request("POST", path, { body: { ...input, idempotencyKey }, idempotencyKey });
144
+ }
145
+
146
+ async request(method, path, { body, query, idempotencyKey } = {}) {
147
+ const url = new URL(this.serverUrl + path);
148
+ for (const [name, value] of Object.entries(query || {})) {
149
+ if (value !== undefined && value !== null && value !== "") url.searchParams.set(name, String(value));
150
+ }
151
+
152
+ for (let attempt = 0; ; attempt++) {
153
+ let res;
154
+ try {
155
+ res = await this.fetch(url, {
156
+ method,
157
+ headers: {
158
+ Authorization: `Bearer ${this.apiKey}`,
159
+ Accept: "application/json",
160
+ ...(body ? { "Content-Type": "application/json" } : {}),
161
+ ...(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}),
162
+ },
163
+ body: body ? JSON.stringify(body) : undefined,
164
+ signal: AbortSignal.timeout(this.timeoutMs),
165
+ });
166
+ } catch (err) {
167
+ if (attempt < this.retries) {
168
+ await wait(300 * 2 ** attempt);
169
+ continue;
170
+ }
171
+ throw new NeuctraFinanceError({
172
+ message: `Could not reach Neuctra Finance at ${this.serverUrl}: ${err.message}`,
173
+ hint: "Check serverUrl and that the API is running.",
174
+ });
175
+ }
176
+
177
+ const payload = await res.json().catch(() => ({}));
178
+ if (res.ok) return payload;
179
+
180
+ const busy = payload?.error?.code === "BUSY";
181
+ if ((RETRYABLE.has(res.status) || busy) && attempt < this.retries) {
182
+ await wait(300 * 2 ** attempt);
183
+ continue;
184
+ }
185
+ throw new NeuctraFinanceError({
186
+ status: res.status,
187
+ code: payload?.error?.code || `HTTP_${res.status}`,
188
+ message: payload?.error?.message || `Request failed with status ${res.status}.`,
189
+ hint: payload?.error?.hint,
190
+ details: payload?.error?.details,
191
+ });
192
+ }
193
+ }
194
+ }
195
+
196
+ /**
197
+ * Checks a webhook from Neuctra Finance and returns its event.
198
+ * Pass the Neuctra-Signature header, the raw request body exactly as
199
+ * received (a string, before JSON parsing), and your nf_whsec_ secret.
200
+ * Throws NeuctraFinanceError (code INVALID_SIGNATURE) when it does not
201
+ * check out or is older than `toleranceSeconds`.
202
+ */
203
+ export async function verifyWebhook(signatureHeader, rawBody, secret, { toleranceSeconds = 300 } = {}) {
204
+ const fail = (message) => {
205
+ throw new NeuctraFinanceError({ code: "INVALID_SIGNATURE", message });
206
+ };
207
+ const parts = Object.fromEntries(
208
+ String(signatureHeader || "")
209
+ .split(",")
210
+ .map((part) => part.trim().split("=")),
211
+ );
212
+ const timestamp = Number(parts.t);
213
+ if (!timestamp || !parts.v1) fail("The Neuctra-Signature header is missing or malformed.");
214
+ if (Math.abs(Date.now() / 1000 - timestamp) > toleranceSeconds) fail("The webhook is too old. It may be a replay.");
215
+
216
+ const encoder = new TextEncoder();
217
+ const key = await globalThis.crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
218
+ const digest = await globalThis.crypto.subtle.sign("HMAC", key, encoder.encode(`${timestamp}.${rawBody}`));
219
+ const expected = Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
220
+
221
+ // Compare every character, so the time taken says nothing about the secret.
222
+ let difference = expected.length ^ parts.v1.length;
223
+ for (let i = 0; i < expected.length; i++) difference |= expected.charCodeAt(i) ^ (parts.v1.charCodeAt(i) || 0);
224
+ if (difference !== 0) fail("The webhook signature does not match.");
225
+ return JSON.parse(rawBody);
226
+ }
227
+
228
+ function enc(value) {
229
+ if (!value) throw new Error("NeuctraFinance: an id is required.");
230
+ return encodeURIComponent(value);
231
+ }
232
+
233
+ export default NeuctraFinance;