@substrat-run/connector-fortnox 0.11.1 → 0.12.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/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { addDecimal, CONNECTOR_ATTACHMENT_BUFFERED_MAX_BYTES, connectionActivity, connectionId as connectionIdSchema, entityRef, instant, money, mulDecimal, scopeId as scopeIdSchema, tenantId as tenantIdSchema, } from '@substrat-run/contracts';
3
- import { deadlineFetch, settleConnectionUse, ulid } from '@substrat-run/kernel';
3
+ import { deadlineFetch, ulid } from '@substrat-run/kernel';
4
4
  import { FortnoxApi, FortnoxApiError, fortnoxErrorCode, FORTNOX_API_BASE, FORTNOX_OAUTH_BASE, fortnoxSecret, } from './api.js';
5
5
  import { financialYearFor, summarizeLedger } from './aggregate.js';
6
6
  import { parseSie4 } from './sie4.js';
@@ -10,7 +10,8 @@ export { parseSie4, splitSieLine, sieAmount, sieDate, } from './sie4.js';
10
10
  export { COST_CENTRE_DIMENSION, financialYearFor, summarizeLedger, } from './aggregate.js';
11
11
  export { FortnoxMock } from './mock.js';
12
12
  export { completeFortnoxConsent } from './connect.js';
13
- export { FORTNOX_CONSENT_SCOPES, FORTNOX_INVOICE_FILE_SCOPES, FORTNOX_INVOICE_SCOPES, FORTNOX_LEDGER_SCOPES, FortnoxConsentShortfall, readFortnoxConsent, } from './consent.js';
13
+ export { FORTNOX_CONSENT_SCOPES, FORTNOX_INVOICE_FILE_SCOPES, FORTNOX_INVOICE_SCOPES, FORTNOX_LEDGER_SCOPES, FortnoxConsentShortfall, FORTNOX_PROBE_WRITES, fortnoxConsentWrite, readFortnoxConsent, } from './consent.js';
14
+ export { FORTNOX_PROBE_TIMEOUT_MS, FORTNOX_SWEEP_TIMEOUT_MS, fortnoxCallOptionsOf, runFortnoxCall, } from './call.js';
14
15
  /**
15
16
  * The Fortnox connector — the INBOUND half of accounting integration.
16
17
  *
@@ -22,9 +23,17 @@ export { FORTNOX_CONSENT_SCOPES, FORTNOX_INVOICE_FILE_SCOPES, FORTNOX_INVOICE_SC
22
23
  * vertical does not *ask* for last month's bookkeeping the way it asks for a signature;
23
24
  * the bookkeeping simply changes at Fortnox, and the platform finds out by looking.
24
25
  *
25
- * So there is no `registerFortnoxConnector`. `sweepFortnoxLedger` is a
26
- * {@link ConnectorSweeper}, the deployment binds it into the platform sweeper exactly
27
- * as it binds Scrive's, and that is the whole trigger surface.
26
+ * So there is no `registerFortnoxConnector`. `sweepFortnoxLedger` is what the platform's
27
+ * sweeper calls for each connection, handed that one connection's door (#3377), and that is
28
+ * the whole trigger surface.
29
+ *
30
+ * ## One connection per call, and nothing past it (#3377)
31
+ *
32
+ * Every function here is handed one connection's worth of the platform ({@link FortnoxOpened},
33
+ * {@link FortnoxConnectionDoor}, {@link FortnoxBindingDoor}, or its state), never a `ScopeHost`
34
+ * or a `HostAdmin`. The probes are calls of the one connector call contract
35
+ * ({@link runFortnoxCall}); the bindings, the sweep and a poll on request are no role of it and
36
+ * are handed the connection's door, which the platform builds.
28
37
  *
29
38
  * ## Where the data lands, and why the connector does not decide
30
39
  *
@@ -329,11 +338,26 @@ const lastModifiedFilter = (ms) => {
329
338
  * Record what this consent covers (#2422) — what a console reads back as "needs re-consent".
330
339
  * Costs no round trip: the mint it reads from is the one the pass needs anyway.
331
340
  */
332
- async function noteConsent(admin, connectionId, api, options) {
341
+ async function noteConsent(state, api, options) {
333
342
  const at = new Date(options.now?.() ?? Date.now()).toISOString();
334
343
  const consent = await fortnoxConsentOf(api, options.consentScopes ?? FORTNOX_CONSENT_SCOPES, at);
335
344
  if (consent)
336
- await recordFortnoxConsent(admin, connectionId, consent);
345
+ await recordFortnoxConsent(state, consent);
346
+ }
347
+ /**
348
+ * The connection as the client reads it: the credential and the egress. The client reads nothing
349
+ * else, so a probe's connection, which the call carries without the rest, is built the same way.
350
+ */
351
+ function apiConnection(conn) {
352
+ return {
353
+ id: conn.connection?.id ?? connectionIdSchema.parse('00000000000000000000000000'), // never read
354
+ tenantId: conn.connection?.tenantId ?? '',
355
+ vertical: conn.connection?.vertical ?? '',
356
+ provider: 'fortnox',
357
+ secret: conn.secret,
358
+ expiresAt: conn.connection?.expiresAt ?? null,
359
+ fetch: conn.fetch,
360
+ };
337
361
  }
338
362
  /** The client options a sync builds its `FortnoxApi` with. */
339
363
  const apiOptions = (options) => ({
@@ -354,9 +378,9 @@ const apiOptions = (options) => ({
354
378
  * nobody is watching, with a provider round trip already spent. Here it fails in the
355
379
  * operator's hands, naming the permission to grant.
356
380
  */
357
- export async function bindFortnoxScope(host, input) {
358
- const tenant = tenantIdSchema.parse(input.tenantId);
359
- const scope = scopeIdSchema.parse(input.scopeId);
381
+ export async function bindFortnoxScope(door, input) {
382
+ tenantIdSchema.parse(input.tenantId);
383
+ scopeIdSchema.parse(input.scopeId);
360
384
  if (input.ownerScopeId && input.ownerScopeId !== input.scopeId) {
361
385
  throw new Error(`connection ${input.connectionId} is scope ${input.ownerScopeId}'s own, and lands in that scope alone, not ${input.scopeId}`);
362
386
  }
@@ -372,15 +396,15 @@ export async function bindFortnoxScope(host, input) {
372
396
  if ((input.firstPass !== undefined || input.writeback !== undefined) && input.kind !== 'supplier-invoice') {
373
397
  throw new Error(`firstPass and writeback apply to a supplier-invoice binding, not to '${input.kind ?? 'ledger'}'`);
374
398
  }
375
- const current = (await listFortnoxBindings(host, input.connectionId)).find((b) => b.scopeId === input.scopeId);
399
+ const current = (await listFortnoxBindings(door.state)).find((b) => b.scopeId === input.scopeId);
376
400
  if (current && (current.kind ?? 'ledger') !== (input.kind ?? 'ledger')) {
377
401
  throw new Error(`one Fortnox landing kind per scope; use a separate scope for the other kind (${current.kind ?? 'ledger'} to ${input.kind ?? 'ledger'} on scope ${input.scopeId})`);
378
402
  }
379
- // On the host, not `admin`: this is the same projection the permission checker reads,
380
- // so a binding is verified against the tuples that will actually gate the invoke —
381
- // not against a directory row that may not have reached the scope yet.
382
- const granted = input.grantPreflighted ? [] : await host.connectionGrantsInScope(tenant, scope);
383
- const held = input.grantPreflighted || granted.some((g) => g.connectionId === input.connectionId && g.permission === input.permission);
403
+ // The door reads the same projection the permission checker reads, so a binding is verified
404
+ // against the tuples that will actually gate the invoke — not against a directory row that may
405
+ // not have reached the scope yet.
406
+ const held = input.grantPreflighted ||
407
+ (await door.holds({ tenantId: input.tenantId, scopeId: input.scopeId, permission: input.permission }));
384
408
  if (!held) {
385
409
  throw new Error(`connection ${input.connectionId} does not hold '${input.permission}' on scope ${input.scopeId} — ` +
386
410
  `a sweep would fetch the ledger and then fail to land it. Grant it first ` +
@@ -417,12 +441,12 @@ export async function bindFortnoxScope(host, input) {
417
441
  : {}),
418
442
  boundAt: new Date(input.now?.() ?? Date.now()).toISOString(),
419
443
  };
420
- await host.admin.putConnectorState(input.connectionId, bindingKey(input.scopeId), binding);
444
+ await door.state.put(bindingKey(input.scopeId), binding);
421
445
  return binding;
422
446
  }
423
447
  /** Every scope this connection syncs into. */
424
- export async function listFortnoxBindings(host, connectionId) {
425
- const rows = await host.admin.listConnectorState(connectionId, BINDING_PREFIX);
448
+ export async function listFortnoxBindings(state) {
449
+ const rows = await state.list(BINDING_PREFIX);
426
450
  // Tombstones filtered, exactly as the sweep and the activity projection do.
427
451
  // `unbindFortnoxScope` writes `null` under the same key, and casting that to
428
452
  // `FortnoxBinding` hands a caller a typed value that throws on the first property
@@ -437,8 +461,8 @@ export async function listFortnoxBindings(host, connectionId) {
437
461
  * unbound scope that a later sweep silently re-adopts would be worse than a visible
438
462
  * dead row.
439
463
  */
440
- export async function unbindFortnoxScope(host, connectionId, scopeId) {
441
- await host.admin.putConnectorState(connectionId, bindingKey(scopeId), null);
464
+ export async function unbindFortnoxScope(state, scopeId) {
465
+ await state.put(bindingKey(scopeId), null);
442
466
  }
443
467
  const sha256Hex = async (text) => {
444
468
  const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
@@ -452,15 +476,15 @@ const sha256Hex = async (text) => {
452
476
  * and an unchanged hash returns `changed: false` without a single `invoke` — which
453
477
  * matters because a sweep runs on a timer and most passes find books nobody has touched.
454
478
  */
455
- export async function syncFortnoxScope(host, connectionId, binding, options) {
479
+ export async function syncFortnoxScope(conn, binding, options) {
456
480
  if (binding.kind !== undefined && binding.kind !== 'ledger') {
457
481
  throw new Error(`ledger sync cannot use Fortnox binding kind '${String(binding.kind)}'`);
458
482
  }
459
- const admin = host.admin;
460
- const conn = await openFortnoxConnection(admin, options.fetch, binding.tenantId, binding.vertical, options.timeoutMs ?? 30_000, { externalAccountRef: binding.externalAccountRef ?? null, owner: ownerOf(connectionId, binding), expected: connectionId });
461
- const api = new FortnoxApi(conn, apiOptions(options));
483
+ const connectionId = conn.connection.id;
484
+ ownerOf(connectionId, binding);
485
+ const api = new FortnoxApi(apiConnection(conn), apiOptions(options));
462
486
  // #2422: a consent without `bookkeeping` answers every read 403; say so before reading.
463
- await noteConsent(admin, connectionId, api, options);
487
+ await noteConsent(conn.state, api, options);
464
488
  await requireFortnoxScopes(api, FORTNOX_LEDGER_SCOPES, 'a ledger binding');
465
489
  // The period defaults to the calendar year containing "now", which is the sane
466
490
  // default for a recurring sync; a caller back-filling names its own.
@@ -516,7 +540,7 @@ export async function syncFortnoxScope(host, connectionId, binding, options) {
516
540
  // The connection acting as itself (#97). Refuses a scope in another tenant or running
517
541
  // another vertical by construction, and the invoke below is gated on the connection's
518
542
  // own grant — the one `bindFortnoxScope` verified.
519
- const scope = await host.getConnectorScope(connectionId, scopeIdSchema.parse(binding.scopeId));
543
+ const scope = await conn.scope(scopeIdSchema.parse(binding.scopeId));
520
544
  const pageCount = Math.max(1, Math.ceil(summary.balances.length / PAGE_SIZE));
521
545
  for (let page = 0; page < pageCount; page += 1) {
522
546
  const slice = summary.balances.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE);
@@ -553,7 +577,7 @@ export async function syncFortnoxScope(host, connectionId, binding, options) {
553
577
  // Written only AFTER every page landed, so a failure mid-way leaves the cursor at the
554
578
  // previous hash and the next sweep retries the whole year rather than resuming into a
555
579
  // half-written ledger.
556
- await admin.putConnectorState(connectionId, bindingKey(binding.scopeId), synced);
580
+ await conn.state.put(bindingKey(binding.scopeId), synced);
557
581
  return {
558
582
  scopeId: binding.scopeId,
559
583
  changed: true,
@@ -576,10 +600,11 @@ export async function syncFortnoxScope(host, connectionId, binding, options) {
576
600
  * Each year is written to the binding right after it lands, so a failure on one costs only that one,
577
601
  * and the years that did land are answered beside the ones that failed.
578
602
  */
579
- export async function syncFortnoxSieFiles(host, connectionId, binding, options) {
580
- const conn = await openFortnoxConnection(host.admin, options.fetch, binding.tenantId, binding.vertical, options.timeoutMs ?? 30_000, { externalAccountRef: binding.externalAccountRef ?? null, owner: ownerOf(connectionId, binding), expected: connectionId });
581
- const api = new FortnoxApi(conn, apiOptions(options));
582
- await noteConsent(host.admin, connectionId, api, options);
603
+ export async function syncFortnoxSieFiles(conn, binding, options) {
604
+ const connectionId = conn.connection.id;
605
+ ownerOf(connectionId, binding);
606
+ const api = new FortnoxApi(apiConnection(conn), apiOptions(options));
607
+ await noteConsent(conn.state, api, options);
583
608
  await requireFortnoxScopes(api, FORTNOX_LEDGER_SCOPES, 'a ledger binding');
584
609
  const nowMs = options.now?.() ?? Date.now();
585
610
  const year = new Date(nowMs).toISOString().slice(0, 4);
@@ -618,7 +643,7 @@ export async function syncFortnoxSieFiles(host, connectionId, binding, options)
618
643
  // The file names its company (#FNAMN, #ORGNR), as the summary form reads it.
619
644
  const ledger = parseSie4(sie);
620
645
  // The connection acting as itself (#97), gated on the grant the binding was seated with.
621
- const scope = await host.getConnectorScope(connectionId, scopeIdSchema.parse(binding.scopeId));
646
+ const scope = await conn.scope(scopeIdSchema.parse(binding.scopeId));
622
647
  await scope.invoke(binding.operation, fortnoxSieFile.parse({
623
648
  syncId: contentHash,
624
649
  connectionId,
@@ -630,12 +655,12 @@ export async function syncFortnoxSieFiles(host, connectionId, binding, options)
630
655
  // A year is a long download, so the binding read at the start of the pass may be stale by now:
631
656
  // the cursor goes onto the binding as it stands, and one unbound or re-bound meanwhile is left
632
657
  // as the person left it rather than brought back from this pass's copy.
633
- const now = (await host.admin.getConnectorState(connectionId, key));
658
+ const now = (await conn.state.get(key));
634
659
  if (!now || typeof now !== 'object' || now.boundAt !== binding.boundAt)
635
660
  break;
636
661
  const syncedAt = new Date(nowMs).toISOString();
637
662
  const { [String(financialYear.Id)]: _landed, ...stillFailed } = now.yearFailedAt ?? {};
638
- await host.admin.putConnectorState(connectionId, key, {
663
+ await conn.state.put(key, {
639
664
  ...now,
640
665
  yearSync: { ...now.yearSync, [String(financialYear.Id)]: { syncedAt, contentHash } },
641
666
  yearFailedAt: Object.keys(stillFailed).length > 0 ? stillFailed : undefined,
@@ -655,7 +680,7 @@ export async function syncFortnoxSieFiles(host, connectionId, binding, options)
655
680
  failed.push({ financialYearId: financialYear.Id, error });
656
681
  // The current year is tried every pass anyway; an older one is put back in the queue.
657
682
  if (financialYear !== current)
658
- await markYearFailed(host, connectionId, key, binding, financialYear.Id, nowMs);
683
+ await markYearFailed(conn.state, key, binding, financialYear.Id, nowMs);
659
684
  }
660
685
  }
661
686
  return { synced, failed };
@@ -665,12 +690,12 @@ export async function syncFortnoxSieFiles(host, connectionId, binding, options)
665
690
  * year's error is already answered, so a failure to record it only means the year is tried again
666
691
  * next pass, as it was before this was recorded.
667
692
  */
668
- async function markYearFailed(host, connectionId, key, binding, financialYearId, nowMs) {
693
+ async function markYearFailed(state, key, binding, financialYearId, nowMs) {
669
694
  try {
670
- const now = (await host.admin.getConnectorState(connectionId, key));
695
+ const now = (await state.get(key));
671
696
  if (!now || typeof now !== 'object' || now.boundAt !== binding.boundAt)
672
697
  return;
673
- await host.admin.putConnectorState(connectionId, key, {
698
+ await state.put(key, {
674
699
  ...now,
675
700
  yearFailedAt: { ...now.yearFailedAt, [String(financialYearId)]: new Date(nowMs).toISOString() },
676
701
  });
@@ -693,15 +718,15 @@ async function markYearFailed(host, connectionId, key, binding, financialYearId,
693
718
  * Files come after the cursor, because a file that cannot be read says nothing about the invoice:
694
719
  * the invoices keep landing, and the file stays queued and fails the scope's row by its number.
695
720
  */
696
- export async function syncFortnoxSupplierInvoices(host, connectionId, binding, options) {
721
+ export async function syncFortnoxSupplierInvoices(conn, binding, options) {
697
722
  if (binding.kind !== 'supplier-invoice') {
698
723
  throw new Error(`supplier-invoice sync cannot use Fortnox binding kind '${String(binding.kind ?? 'ledger')}'`);
699
724
  }
700
- const conn = await openFortnoxConnection(host.admin, options.fetch, binding.tenantId, binding.vertical, options.timeoutMs ?? 30_000, { externalAccountRef: binding.externalAccountRef ?? null, owner: ownerOf(connectionId, binding), expected: connectionId });
701
- const api = new FortnoxApi(conn, apiOptions(options));
725
+ ownerOf(conn.connection.id, binding);
726
+ const api = new FortnoxApi(apiConnection(conn), apiOptions(options));
702
727
  // #2422: without these nothing lands, so the binding fails saying so rather than on a 403. The
703
728
  // files' scopes are checked by the file half, because the invoices land without them.
704
- await noteConsent(host.admin, connectionId, api, options);
729
+ await noteConsent(conn.state, api, options);
705
730
  await requireFortnoxScopes(api, FORTNOX_INVOICE_SCOPES, 'a supplier-invoice binding');
706
731
  const nowMs = options.now?.() ?? Date.now();
707
732
  const expired = () => (options.now?.() ?? Date.now()) - nowMs >= INVOICE_PASS_DEADLINE_MS;
@@ -710,7 +735,7 @@ export async function syncFortnoxSupplierInvoices(host, connectionId, binding, o
710
735
  const scopeRef = scopeIdSchema.parse(binding.scopeId);
711
736
  let companyRead;
712
737
  const company = () => (companyRead ??= api.companyInformation());
713
- const files = new InvoiceFiles(host, connectionId, binding.scopeId, scopeRef, api, budget, expired, binding.files);
738
+ const files = new InvoiceFiles(conn, binding.scopeId, scopeRef, api, budget, expired, binding.files);
714
739
  const withFiles = (base) => {
715
740
  const { files: _held, ...rest } = base;
716
741
  return { ...rest, ...files.held() };
@@ -718,7 +743,7 @@ export async function syncFortnoxSupplierInvoices(host, connectionId, binding, o
718
743
  const saveFiles = async (base) => {
719
744
  if (!files.moved)
720
745
  return;
721
- await host.admin.putConnectorState(connectionId, bindingKey(binding.scopeId), withFiles(base));
746
+ await conn.state.put(bindingKey(binding.scopeId), withFiles(base));
722
747
  files.moved = false;
723
748
  };
724
749
  // The queue goes first, so it never outgrows one pass's budget, and it is saved at once, so a
@@ -727,10 +752,10 @@ export async function syncFortnoxSupplierInvoices(host, connectionId, binding, o
727
752
  await saveFiles(binding);
728
753
  // A pass's parts are independent: a landing that throws says nothing about a decision waiting to be
729
754
  // written, and an idle pass is when most decisions are. The first failure is thrown at the end.
730
- const landing = await landChangedInvoices(host, connectionId, binding, { api, company, files, budget, expired, nowMs, withFiles, saveFiles })
755
+ const landing = await landChangedInvoices(conn, binding, { api, company, files, budget, expired, nowMs, withFiles, saveFiles })
731
756
  .catch((err) => ({ landed: 0, more: true, failure: asError(err) }));
732
757
  const writes = binding.writeback
733
- ? await writeBackInvoices(host, connectionId, binding, binding.writeback, { api, company, budget, expired, nowMs })
758
+ ? await writeBackInvoices(conn, binding, binding.writeback, { api, company, budget, expired, nowMs })
734
759
  .catch((err) => ({ held: 0, written: 0, more: true, failure: asError(err) }))
735
760
  : { held: 0, written: 0, more: false, failure: null };
736
761
  const failure = landing.failure ?? files.failed ?? writes.failure;
@@ -789,8 +814,9 @@ function writeFailure(what, how, err) {
789
814
  return new FortnoxSaidFailure(`${what} ${how}: ${asError(err).message}`, `${what} ${how}${answered === null ? '' : `: ${answered}`}`);
790
815
  }
791
816
  /** Land what changed since the cursor, then read the files the landing asked for. */
792
- async function landChangedInvoices(host, connectionId, binding, pass) {
817
+ async function landChangedInvoices(conn, binding, pass) {
793
818
  const { api, company: companyOf, files, budget, expired, nowMs, withFiles, saveFiles } = pass;
819
+ const connectionId = conn.connection.id;
794
820
  if (budget.details <= 0 || expired())
795
821
  return { landed: 0, more: true, failure: null };
796
822
  const cursor = binding.invoiceSync;
@@ -842,7 +868,7 @@ async function landChangedInvoices(host, connectionId, binding, pass) {
842
868
  invoices,
843
869
  });
844
870
  // The connection acting as itself (#97), gated on the grant the binding was seated with.
845
- const scope = await host.getConnectorScope(connectionId, scopeIdSchema.parse(binding.scopeId));
871
+ const scope = await conn.scope(scopeIdSchema.parse(binding.scopeId));
846
872
  files.ask(await scope.invoke(binding.operation, payload));
847
873
  }
848
874
  const more = changed.length > handled;
@@ -856,7 +882,7 @@ async function landChangedInvoices(host, connectionId, binding, pass) {
856
882
  ...(more ? { pending: { startedAt, through: batch[handled - 1] } } : {}),
857
883
  },
858
884
  });
859
- await host.admin.putConnectorState(connectionId, bindingKey(binding.scopeId), synced);
885
+ await conn.state.put(bindingKey(binding.scopeId), synced);
860
886
  files.moved = false;
861
887
  await files.drain();
862
888
  await saveFiles(synced);
@@ -880,12 +906,14 @@ const statedRefusal = (err) => err instanceof FortnoxApiError && err.status >= 4
880
906
  * pass would get the same answer and a person has to act: a decision's goes to the vertical at once,
881
907
  * and a hold's is remembered on the invoice's note and fails one pass, not every pass (#3452).
882
908
  */
883
- async function writeBackInvoices(host, connectionId, binding, operations, pass) {
909
+ async function writeBackInvoices(conn, binding, operations, pass) {
884
910
  const { api, budget, expired, nowMs } = pass;
911
+ const connectionId = conn.connection.id;
912
+ const state = conn.state;
885
913
  // A pass with no budget left for one write asks nothing of Fortnox, not even who the company is.
886
914
  if (budget.details < INVOICE_HOLD_CALLS || expired())
887
915
  return { held: 0, written: 0, more: true, failure: null };
888
- const scope = await host.getConnectorScope(connectionId, scopeIdSchema.parse(binding.scopeId));
916
+ const scope = await conn.scope(scopeIdSchema.parse(binding.scopeId));
889
917
  const company = await pass.company();
890
918
  const waiting = fortnoxInvoiceWriteback.parse(await scope.invoke(operations.read, {
891
919
  connectionId,
@@ -896,7 +924,7 @@ async function writeBackInvoices(host, connectionId, binding, operations, pass)
896
924
  for (const { givenNumber } of waiting.hold) {
897
925
  const key = invoiceHoldKey(givenNumber);
898
926
  // A released hold does not count: an invoice can come back to the queue, and then it is held again.
899
- const known = (await host.admin.getConnectorState(connectionId, key));
927
+ const known = (await state.get(key));
900
928
  const live = known && !known.cleared ? known : null;
901
929
  // Only a block this connector saw set is left alone. Someone else's is looked at again, because
902
930
  // lifting it would leave the undecided invoice payable, and so is one Fortnox never confirmed.
@@ -912,16 +940,16 @@ async function writeBackInvoices(host, connectionId, binding, operations, pass)
912
940
  if ((await api.supplierInvoice(givenNumber)).DisablePaymentFile) {
913
941
  // Blocked already: ours when our unconfirmed write went through, someone else's otherwise.
914
942
  if (!live || live.unconfirmed) {
915
- await host.admin.putConnectorState(connectionId, key, { ours: !!live?.ours, at: live?.at ?? at });
943
+ await state.put(key, { ours: !!live?.ours, at: live?.at ?? at });
916
944
  }
917
945
  continue;
918
946
  }
919
947
  // Remembered before the write: a pass that dies between them must not leave a block nobody
920
948
  // knows is ours, which no approval would ever clear and which keeps a good invoice unpaid.
921
- await host.admin.putConnectorState(connectionId, key, { ours: true, at, unconfirmed: true });
949
+ await state.put(key, { ours: true, at, unconfirmed: true });
922
950
  asked = true;
923
951
  await api.setSupplierInvoicePaymentBlock(givenNumber, true);
924
- await host.admin.putConnectorState(connectionId, key, { ours: true, at });
952
+ await state.put(key, { ours: true, at });
925
953
  out.held += 1;
926
954
  }
927
955
  catch (err) {
@@ -929,7 +957,7 @@ async function writeBackInvoices(host, connectionId, binding, operations, pass)
929
957
  // note stays unconfirmed and the next pass reads the invoice to find out.
930
958
  if (fortnoxErrorCode(err) === APPROVED_LOCKED) {
931
959
  // Approved before it could be held: asking again gets the same answer every pass.
932
- await host.admin.putConnectorState(connectionId, key, { ours: false, at, approved: true });
960
+ await state.put(key, { ours: false, at, approved: true });
933
961
  out.failure ??= new FortnoxSaidFailure(`hold of supplier invoice ${givenNumber}: it was approved in Fortnox before it could be held, ` +
934
962
  `so it cannot be blocked over the API. Block it in Fortnox if it must wait for the decision. ${asError(err).message}`, `supplier invoice ${givenNumber} was approved in Fortnox before it could be held: ${fortnoxAnswered(err)}`);
935
963
  continue;
@@ -938,7 +966,7 @@ async function writeBackInvoices(host, connectionId, binding, operations, pass)
938
966
  // Refused in Fortnox's words, so the block was not set and asking again gets the same answer:
939
967
  // remembered, and failed for once (#3452), rather than asked and failed on every pass.
940
968
  const refused = { status: err.status, code: fortnoxErrorCode(err), at };
941
- await host.admin.putConnectorState(connectionId, key, { ours: false, at, refused });
969
+ await state.put(key, { ours: false, at, refused });
942
970
  out.failure ??= writeFailure(`hold of supplier invoice ${givenNumber}`, 'was refused, and is not asked again until the invoice is decided', err);
943
971
  continue;
944
972
  }
@@ -954,24 +982,24 @@ async function writeBackInvoices(host, connectionId, binding, operations, pass)
954
982
  const tries = invoiceWriteKey(decision.key);
955
983
  const progress = { step: 'the read' };
956
984
  try {
957
- await settleInvoiceDecision(host, connectionId, api, decision, at, progress);
985
+ await settleInvoiceDecision(state, api, decision, at, progress);
958
986
  progress.step = 'the receipt';
959
987
  await scope.invoke(operations.record, fortnoxInvoiceWritebackReceipt.parse({ key: decision.key, status: 'done', error: null }));
960
- await host.admin.putConnectorState(connectionId, tries, null);
961
- await forgetRefusedHold(host, connectionId, decision.givenNumber, at);
988
+ await state.put(tries, null);
989
+ await forgetRefusedHold(state, decision.givenNumber, at);
962
990
  out.written += 1;
963
991
  }
964
992
  catch (err) {
965
993
  const error = asError(err);
966
- const attempts = ((await host.admin.getConnectorState(connectionId, tries))?.attempts ?? 0) + 1;
994
+ const attempts = ((await state.get(tries))?.attempts ?? 0) + 1;
967
995
  // The step says how far the decision got (#3452): a refused second booking reads apart from a
968
996
  // first booking that was refused for another reason.
969
997
  out.failure ??= writeFailure(`write-back of supplier invoice ${decision.givenNumber}`, `failed at ${progress.step}`, err);
970
998
  if (statedRefusal(err) || attempts >= INVOICE_WRITE_ATTEMPTS) {
971
999
  try {
972
1000
  await scope.invoke(operations.record, fortnoxInvoiceWritebackReceipt.parse({ key: decision.key, status: 'failed', error: error.message }));
973
- await host.admin.putConnectorState(connectionId, tries, null);
974
- await forgetRefusedHold(host, connectionId, decision.givenNumber, at);
1001
+ await state.put(tries, null);
1002
+ await forgetRefusedHold(state, decision.givenNumber, at);
975
1003
  continue;
976
1004
  }
977
1005
  catch {
@@ -979,7 +1007,7 @@ async function writeBackInvoices(host, connectionId, binding, operations, pass)
979
1007
  // again, and this pass goes on to the rest. The first failure is already the one reported.
980
1008
  }
981
1009
  }
982
- await host.admin.putConnectorState(connectionId, tries, { attempts, lastError: error.message });
1010
+ await state.put(tries, { attempts, lastError: error.message });
983
1011
  }
984
1012
  }
985
1013
  return out;
@@ -988,21 +1016,21 @@ async function writeBackInvoices(host, connectionId, binding, operations, pass)
988
1016
  * A settled decision ends what a refused hold remembered, so an invoice that comes back to the queue
989
1017
  * is asked about again. A note for any other hold stays: whether to lift that block is the release's.
990
1018
  */
991
- async function forgetRefusedHold(host, connectionId, givenNumber, at) {
1019
+ async function forgetRefusedHold(state, givenNumber, at) {
992
1020
  const key = invoiceHoldKey(givenNumber);
993
- const hold = (await host.admin.getConnectorState(connectionId, key));
1021
+ const hold = (await state.get(key));
994
1022
  if (hold?.refused && !hold.cleared)
995
- await host.admin.putConnectorState(connectionId, key, { ...hold, cleared: at });
1023
+ await state.put(key, { ...hold, cleared: at });
996
1024
  }
997
1025
  /** Bring Fortnox to what one decision says. Safe to repeat: every step looks before it writes. */
998
- async function settleInvoiceDecision(host, connectionId, api, decision, at, progress) {
1026
+ async function settleInvoiceDecision(state, api, decision, at, progress) {
999
1027
  const { givenNumber, book, release, comment } = decision;
1000
1028
  progress.step = 'the read';
1001
1029
  const invoice = await api.supplierInvoice(givenNumber);
1002
1030
  const key = invoiceHoldKey(givenNumber);
1003
1031
  /** Lift the block this binding set, once. */
1004
1032
  const releaseHold = async () => {
1005
- const hold = (await host.admin.getConnectorState(connectionId, key));
1033
+ const hold = (await state.get(key));
1006
1034
  if (!hold?.ours || hold.cleared)
1007
1035
  return;
1008
1036
  progress.step = 'the release';
@@ -1017,7 +1045,7 @@ async function settleInvoiceDecision(host, connectionId, api, decision, at, prog
1017
1045
  `so its payment block can be lifted only in Fortnox: ${err.message}`, err.status, err.body);
1018
1046
  }
1019
1047
  }
1020
- await host.admin.putConnectorState(connectionId, key, { ...hold, cleared: at });
1048
+ await state.put(key, { ...hold, cleared: at });
1021
1049
  };
1022
1050
  let released = false;
1023
1051
  if (book && !invoice.Booked) {
@@ -1056,8 +1084,7 @@ const triedKey = (entry) => JSON.stringify([entry.givenNumber, entry.entity.enti
1056
1084
  * them all: it is the company's consent, and every other file would answer the same.
1057
1085
  */
1058
1086
  class InvoiceFiles {
1059
- host;
1060
- connectionId;
1087
+ conn;
1061
1088
  scopeId;
1062
1089
  scopeRef;
1063
1090
  api;
@@ -1078,9 +1105,8 @@ class InvoiceFiles {
1078
1105
  skipped = [];
1079
1106
  /** True once the queue differs from what the binding holds. */
1080
1107
  moved = false;
1081
- constructor(host, connectionId, scopeId, scopeRef, api, budget, expired, held = []) {
1082
- this.host = host;
1083
- this.connectionId = connectionId;
1108
+ constructor(conn, scopeId, scopeRef, api, budget, expired, held = []) {
1109
+ this.conn = conn;
1084
1110
  this.scopeId = scopeId;
1085
1111
  this.scopeRef = scopeRef;
1086
1112
  this.api = api;
@@ -1164,7 +1190,7 @@ class InvoiceFiles {
1164
1190
  this.budget.details -= 1;
1165
1191
  const connected = await this.api.supplierInvoiceFiles(entry.givenNumber);
1166
1192
  const key = filesLandedKey(this.scopeId, entry.givenNumber);
1167
- const held = (await this.host.admin.getConnectorState(this.connectionId, key));
1193
+ const held = (await this.conn.state.get(key));
1168
1194
  const sameEntity = held?.entity.entityType === entry.entity.entityType && held.entity.entityId === entry.entity.entityId;
1169
1195
  let landed = sameEntity ? held.fileIds : [];
1170
1196
  for (const file of connected) {
@@ -1175,7 +1201,7 @@ class InvoiceFiles {
1175
1201
  this.budget.details -= 1;
1176
1202
  await this.land(entry, file);
1177
1203
  landed = [...landed, file.FileId];
1178
- await this.host.admin.putConnectorState(this.connectionId, key, { entity: entry.entity, fileIds: landed });
1204
+ await this.conn.state.put(key, { entity: entry.entity, fileIds: landed });
1179
1205
  }
1180
1206
  return true;
1181
1207
  }
@@ -1195,7 +1221,7 @@ class InvoiceFiles {
1195
1221
  this.skipped.push({ givenNumber: entry.givenNumber, reason: `${name} is ${read.tooLarge} bytes, over ${INVOICE_FILE_MAX_BYTES}` });
1196
1222
  return;
1197
1223
  }
1198
- this.attachments ??= await this.host.getConnectorAttachments(this.connectionId, this.scopeRef);
1224
+ this.attachments ??= await this.conn.attachments(this.scopeRef);
1199
1225
  await this.attachments.upload({
1200
1226
  entity: entry.entity,
1201
1227
  filename: name,
@@ -1254,14 +1280,14 @@ const leaseKey = (scope) => `fortnox:lease:${scope}`;
1254
1280
  * compare-and-set, so the take is a write and a read back of its token, and two takers that
1255
1281
  * interleave within those few milliseconds can both hold it.
1256
1282
  */
1257
- async function takePollLease(host, connectionId, scopeId, nowMs) {
1283
+ async function takePollLease(state, scopeId, nowMs) {
1258
1284
  const key = leaseKey(scopeId);
1259
- const held = (await host.admin.getConnectorState(connectionId, key));
1285
+ const held = (await state.get(key));
1260
1286
  if (held && Date.parse(held.until) > nowMs)
1261
1287
  return null;
1262
1288
  const token = ulid();
1263
- await host.admin.putConnectorState(connectionId, key, { token, until: new Date(nowMs + POLL_LEASE_MS).toISOString() });
1264
- const after = (await host.admin.getConnectorState(connectionId, key));
1289
+ await state.put(key, { token, until: new Date(nowMs + POLL_LEASE_MS).toISOString() });
1290
+ const after = (await state.get(key));
1265
1291
  return after?.token === token ? token : null;
1266
1292
  }
1267
1293
  /**
@@ -1270,12 +1296,12 @@ async function takePollLease(host, connectionId, scopeId, nowMs) {
1270
1296
  * left alone. A body read is not a boundary: one that streams longer than the lease can outlive it.
1271
1297
  * Best effort, as the release: a renewal that fails leaves the lease to expire, never the request.
1272
1298
  */
1273
- function leaseRenewing(host, connectionId, scopeId, token, fetch, now) {
1299
+ function leaseRenewing(state, scopeId, token, fetch, now) {
1274
1300
  let renewedAt = now();
1275
1301
  const renew = async (at) => {
1276
- const held = (await host.admin.getConnectorState(connectionId, leaseKey(scopeId)));
1302
+ const held = (await state.get(leaseKey(scopeId)));
1277
1303
  if (held?.token === token)
1278
- await host.admin.putConnectorState(connectionId, leaseKey(scopeId), { token, until: new Date(at + POLL_LEASE_MS).toISOString() });
1304
+ await state.put(leaseKey(scopeId), { token, until: new Date(at + POLL_LEASE_MS).toISOString() });
1279
1305
  };
1280
1306
  return async (input, init) => {
1281
1307
  if (now() - renewedAt >= POLL_LEASE_MS / 3) {
@@ -1286,15 +1312,15 @@ function leaseRenewing(host, connectionId, scopeId, token, fetch, now) {
1286
1312
  };
1287
1313
  }
1288
1314
  /** Give the lease back, unless it expired and another poll took it over. */
1289
- async function releasePollLease(host, connectionId, scopeId, token) {
1315
+ async function releasePollLease(state, scopeId, token) {
1290
1316
  const key = leaseKey(scopeId);
1291
- const held = (await host.admin.getConnectorState(connectionId, key));
1317
+ const held = (await state.get(key));
1292
1318
  if (held?.token === token)
1293
- await host.admin.putConnectorState(connectionId, key, null);
1319
+ await state.put(key, null);
1294
1320
  }
1295
1321
  /**
1296
- * Poll Fortnox for every scope this connection is bound to — the {@link ConnectorSweeper}
1297
- * a deployment schedules. A ledger binding syncs its year of books
1322
+ * Poll Fortnox for every scope this connection is bound to — what the platform's sweeper runs
1323
+ * for each connection, handed its door (#3377). A ledger binding syncs its year of books
1298
1324
  * ({@link syncFortnoxScope}); an invoice binding lands the supplier invoices changed since its
1299
1325
  * cursor ({@link syncFortnoxSupplierInvoices}). The name predates invoices and is kept.
1300
1326
  *
@@ -1306,8 +1332,10 @@ async function releasePollLease(host, connectionId, scopeId, token) {
1306
1332
  * anything, and a failure on one scope is recorded and stepped over rather than sinking
1307
1333
  * the pass — one vertical's missing grant must not stop another tenant's books syncing.
1308
1334
  */
1309
- export async function sweepFortnoxLedger(host, connectionId, options) {
1310
- const rows = await host.admin.listConnectorState(connectionId, options.scopeId === undefined ? BINDING_PREFIX : bindingKey(options.scopeId));
1335
+ export async function sweepFortnoxLedger(door, options) {
1336
+ const connectionId = door.connectionId;
1337
+ const state = door.state;
1338
+ const rows = await state.list(options.scopeId === undefined ? BINDING_PREFIX : bindingKey(options.scopeId));
1311
1339
  const result = { found: 0, synced: [], invoices: [], unchanged: 0, failed: [], busy: [] };
1312
1340
  // One budget and one rate window per pass: every binding on this connection reads the same company.
1313
1341
  const budget = { details: INVOICE_DETAILS_PER_PASS };
@@ -1330,14 +1358,22 @@ export async function sweepFortnoxLedger(host, connectionId, options) {
1330
1358
  }
1331
1359
  let lease = null;
1332
1360
  try {
1333
- lease = await takePollLease(host, connectionId, binding.scopeId, clock());
1361
+ lease = await takePollLease(state, binding.scopeId, clock());
1334
1362
  if (lease === null) {
1335
1363
  result.busy.push(binding.scopeId);
1336
1364
  continue;
1337
1365
  }
1338
- const leased = { ...pass, fetch: leaseRenewing(host, connectionId, binding.scopeId, lease, pass.fetch, clock) };
1366
+ // The company the binding records (#2316) and its owner (#3410); the door opens only this
1367
+ // connection there, so the credential that reads and the identity that lands are one.
1368
+ const opened = await door.open({
1369
+ tenantId: binding.tenantId,
1370
+ vertical: binding.vertical,
1371
+ externalAccountRef: binding.externalAccountRef ?? null,
1372
+ ownerScopeId: ownerOf(connectionId, binding),
1373
+ });
1374
+ const leased = { ...opened, fetch: leaseRenewing(state, binding.scopeId, lease, opened.fetch, clock) };
1339
1375
  if (binding.kind === 'supplier-invoice') {
1340
- const r = await syncFortnoxSupplierInvoices(host, connectionId, binding, { ...leased, budget });
1376
+ const r = await syncFortnoxSupplierInvoices(leased, binding, { ...pass, budget });
1341
1377
  if (r.landed > 0 || r.files > 0 || r.held > 0 || r.written > 0 || r.skipped || r.pending)
1342
1378
  result.invoices.push(r);
1343
1379
  else
@@ -1345,7 +1381,7 @@ export async function sweepFortnoxLedger(host, connectionId, options) {
1345
1381
  continue;
1346
1382
  }
1347
1383
  if (binding.form === 'sie') {
1348
- const { synced, failed } = await syncFortnoxSieFiles(host, connectionId, binding, leased);
1384
+ const { synced, failed } = await syncFortnoxSieFiles(leased, binding, pass);
1349
1385
  const landed = synced.filter((r) => r.changed);
1350
1386
  result.synced.push(...landed);
1351
1387
  for (const f of failed) {
@@ -1358,7 +1394,7 @@ export async function sweepFortnoxLedger(host, connectionId, options) {
1358
1394
  result.unchanged += 1;
1359
1395
  continue;
1360
1396
  }
1361
- const r = await syncFortnoxScope(host, connectionId, binding, leased);
1397
+ const r = await syncFortnoxScope(leased, binding, pass);
1362
1398
  if (r.changed)
1363
1399
  result.synced.push(r);
1364
1400
  else
@@ -1374,7 +1410,7 @@ export async function sweepFortnoxLedger(host, connectionId, options) {
1374
1410
  finally {
1375
1411
  // A release that fails leaves the lease to expire.
1376
1412
  if (lease !== null)
1377
- await releasePollLease(host, connectionId, binding.scopeId, lease).catch(() => undefined);
1413
+ await releasePollLease(state, binding.scopeId, lease).catch(() => undefined);
1378
1414
  }
1379
1415
  }
1380
1416
  return result;
@@ -1383,8 +1419,8 @@ export async function sweepFortnoxLedger(host, connectionId, options) {
1383
1419
  * Poll ONE scope's bindings now — {@link sweepFortnoxLedger} narrowed to the scope, so the same
1384
1420
  * budget, deadline and rate window bound it as bound a pass.
1385
1421
  */
1386
- export async function pollFortnoxScope(host, connectionId, scopeId, options) {
1387
- const r = await sweepFortnoxLedger(host, connectionId, { ...options, scopeId });
1422
+ export async function pollFortnoxScope(door, scopeId, options) {
1423
+ const r = await sweepFortnoxLedger(door, { ...options, scopeId });
1388
1424
  const pending = r.invoices.some((i) => i.pending);
1389
1425
  if (r.failed.length > 0) {
1390
1426
  const said = r.failed.flatMap((f) => (f.said ? [f.said] : []));
@@ -1426,25 +1462,24 @@ export async function probeFortnoxSecret(secret, options) {
1426
1462
  };
1427
1463
  }
1428
1464
  const timeoutMs = options.timeoutMs ?? 15_000;
1429
- const conn = {
1430
- id: connectionIdSchema.parse('00000000000000000000000000'), // no row yet; never read
1431
- tenantId: '',
1432
- vertical: '',
1433
- provider: 'fortnox',
1434
- secret: parsed.data,
1435
- // Probe stub, not where expiry is set. Fortnox mints 1h access tokens via client_credentials and has NO refresh token (api.ts); recording the access token expiry here would warn on every row. See connections.md §3.6.
1436
- expiresAt: null,
1437
- fetch: deadlineFetch(options.fetch, timeoutMs),
1438
- };
1439
- return probeWith(conn, options);
1465
+ // No row yet, so no connection is named; a candidate's failure is not a fact about a live one.
1466
+ // Not where expiry is set either: Fortnox mints 1h access tokens via client_credentials and has
1467
+ // NO refresh token (api.ts); recording the access token expiry would warn on every row. See
1468
+ // connections.md §3.6.
1469
+ return probeWith(apiConnection({ secret: parsed.data, fetch: deadlineFetch(options.fetch, timeoutMs) }), options);
1440
1470
  }
1441
- /** Probe the credential a live connection already holds. Verifying is itself a use. */
1442
- export async function probeFortnoxConnection(host, connection, options) {
1443
- const conn = await openFortnoxConnection(host.admin, options.fetch, connection.tenantId, connection.vertical, options.timeoutMs ?? 15_000, { externalAccountRef: connection.externalAccountRef ?? null, owner: connection.ownerScopeId ?? null });
1444
- // A probe a person asked for is a fresh check, so it always rewrites what the console reads.
1445
- return probeWith(conn, options, (consent) => recordFortnoxConsent(host.admin, conn.id, consent, true));
1471
+ /**
1472
+ * Probe the credential a live connection already holds. Verifying is itself a use: `conn.fetch` is
1473
+ * the platform's, bounded and recorded against the connection.
1474
+ *
1475
+ * The answer names what the consent covers (`consent`). A probe a person asked for is a fresh check,
1476
+ * so the platform records it whenever there is one, rewriting what the console reads: over the call
1477
+ * contract the probe answers it as a write of the connection's state ({@link runFortnoxCall}).
1478
+ */
1479
+ export async function probeFortnoxConnection(conn, options) {
1480
+ return probeWith(apiConnection(conn), options);
1446
1481
  }
1447
- async function probeWith(conn, options, record) {
1482
+ async function probeWith(conn, options) {
1448
1483
  const api = new FortnoxApi(conn, {
1449
1484
  apiBase: options.apiBase,
1450
1485
  oauthBase: options.oauthBase,
@@ -1455,8 +1490,6 @@ async function probeWith(conn, options, record) {
1455
1490
  // The mint first: it proves the client pair and the consent, and names what the consent
1456
1491
  // covers (#2422). A read outside that set would answer 403, which is not a refused key.
1457
1492
  consent = await fortnoxConsentOf(api, options.consentScopes ?? FORTNOX_CONSENT_SCOPES, new Date(options.now?.() ?? Date.now()).toISOString());
1458
- if (consent && record)
1459
- await record(consent);
1460
1493
  const consentFact = consent
1461
1494
  ? {
1462
1495
  label: 'Consent',
@@ -1527,8 +1560,8 @@ async function probeWith(conn, options, record) {
1527
1560
  * synced", which is the question an operator asks when a figure looks stale, and it
1528
1561
  * answers it without spending a provider round trip.
1529
1562
  */
1530
- export async function fortnoxConnectionActivity(host, connectionId) {
1531
- const rows = await host.admin.listConnectorState(connectionId, BINDING_PREFIX);
1563
+ export async function fortnoxConnectionActivity(state) {
1564
+ const rows = await state.list(BINDING_PREFIX);
1532
1565
  const entries = rows
1533
1566
  .filter(({ value }) => value !== null && typeof value === 'object')
1534
1567
  .map(({ key, value }) => {
@@ -1558,7 +1591,7 @@ export async function fortnoxConnectionActivity(host, connectionId) {
1558
1591
  ],
1559
1592
  };
1560
1593
  });
1561
- const consent = await readFortnoxConsent(host.admin, connectionId);
1594
+ const consent = await readFortnoxConsent(state);
1562
1595
  return connectionActivity.parse({
1563
1596
  source: 'ledger',
1564
1597
  entries,
@@ -1578,14 +1611,10 @@ export async function fortnoxConnectionActivity(host, connectionId) {
1578
1611
  * identifier, not a secret — and it is the field an operator most needs to read when a
1579
1612
  * connection syncs the wrong company's books.
1580
1613
  */
1581
- export async function fortnoxCredentialSummary(host, connection) {
1582
- // #2316: this company's connection, not whichever one (tenant, vertical) would pick; and a
1583
- // scope's own (#3410) only when the row says so.
1584
- const open = await host.admin.openConnection(tenantIdSchema.parse(connection.tenantId), connection.vertical, 'fortnox', connection.externalAccountRef ?? undefined, connection.ownerScopeId ? scopeIdSchema.parse(connection.ownerScopeId) : undefined);
1585
- if (!open) {
1586
- throw new Error(`no live 'fortnox' connection for tenant ${connection.tenantId} / vertical '${connection.vertical}'`);
1587
- }
1588
- const secret = fortnoxSecret.parse(open.secret);
1614
+ export function fortnoxCredentialSummary(storedSecret) {
1615
+ // #2316: the platform opens this company's connection, not whichever one (tenant, vertical) would
1616
+ // pick; and a scope's own (#3410) only when the row says so. The connector reads the credential.
1617
+ const secret = fortnoxSecret.parse(storedSecret);
1589
1618
  return {
1590
1619
  fields: [
1591
1620
  { key: 'clientId', label: 'Client ID', value: secret.clientId, masked: false },
@@ -1606,45 +1635,4 @@ function ownerOf(connectionId, binding) {
1606
1635
  }
1607
1636
  return binding.ownerScopeId ?? null;
1608
1637
  }
1609
- /**
1610
- * Open the live Fortnox connection for a (tenant, vertical) — and, with several companies
1611
- * connected, the one `account.externalAccountRef` names (#2316) — with health recorded.
1612
- *
1613
- * `account.expected` is the connection a binding names. The credential that reads and the
1614
- * identity that writes must be the same connection, so a mismatch is refused loudly rather than
1615
- * landing one company's books as another's connection — Planima's backstop, which here guards a
1616
- * reachable case: a binding written before it recorded the account, once a second company exists.
1617
- */
1618
- async function openFortnoxConnection(admin, fetchImpl, tenant, vertical, timeoutMs, account = {}) {
1619
- const parsedTenant = tenantIdSchema.parse(tenant);
1620
- // `owner` opens a scope's OWN connection (#3410); without it only the tenant's is ever opened.
1621
- const owner = account.owner ? scopeIdSchema.parse(account.owner) : undefined;
1622
- const open = await admin.openConnection(parsedTenant, vertical, 'fortnox', account.externalAccountRef ?? undefined, owner);
1623
- if (!open) {
1624
- throw new Error(`no live 'fortnox' connection for tenant ${tenant} / vertical '${vertical}'` +
1625
- (account.externalAccountRef ? ` and company ${account.externalAccountRef}` : ''));
1626
- }
1627
- if (account.expected !== undefined && open.id !== account.expected) {
1628
- throw new Error(`binding names connection ${account.expected}, but the live 'fortnox' connection opened for tenant ` +
1629
- `${tenant} / vertical '${vertical}' is ${open.id} — the credential that reads and the identity ` +
1630
- `that writes must be the same connection. Re-bind the scope against ${account.expected}.`);
1631
- }
1632
- const bounded = deadlineFetch(fetchImpl, timeoutMs);
1633
- return {
1634
- ...open,
1635
- fetch: async (input, init) => {
1636
- // #1691: timed, so the host's per-call data point carries a duration.
1637
- const started = Date.now();
1638
- try {
1639
- const res = await bounded(input, init);
1640
- await admin.recordConnectionUse(open.id, settleConnectionUse('fortnox', Date.now() - started, { response: res }));
1641
- return res;
1642
- }
1643
- catch (err) {
1644
- await admin.recordConnectionUse(open.id, settleConnectionUse('fortnox', Date.now() - started, { error: err }));
1645
- throw err;
1646
- }
1647
- },
1648
- };
1649
- }
1650
1638
  //# sourceMappingURL=index.js.map