f31eeaa603
* feat(connect): peppol connector foundation: capability, ledger/budget service, quota Adds the storage + package shape for brokering Peppol through the connector with the same one-address + rate-budget model as bank/skatteverket: a peppol capability (connector-gated, free on hosted), peppol as a ledger + upstream service, a conservative rate budget, and a migration extending the ledger service CHECK and the per-key limits (peppol_connections_per_company). Proxy route + instance-side Qvalia reroute follow. Switch-on gated on the Qvalia brokering-terms check. (cherry picked from commit 3cc0da6a3, migration renumbered 20260902190000) Signed-off-by: Jakob Wennberg <jakob.wennberg@arcim.io> Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MMUUom4fUk6zi4xYZSSfat * feat(connect): Peppol through the connector: hosted proxy, instance transport, ownership ledger Completes the Peppol upstream for self-hosted instances on the connector (WS3): an instance with a connector key carrying the peppol scope and no Qvalia keys of its own sends and receives e-invoices through Arcim's contracted access point, the same way bank and Skatteverket already route. Hosted: app/api/connect/peppol/[...path] speaks the PeppolTransport operations (lookup, submit, status, evidence, recipient PUT/DELETE, inbound list/xml) rather than proxying Qvalia paths, because the Qvalia account is shared by every hosted company and every instance: reads must be scoped to what the caller owns, and the inbound read endpoint is destructive for the whole account. Ownership: a receiving registration is a ledger row (service peppol, participant id in account_uids, sha256 in handle_hash so one key holds a participant at a time); outbound submissions land in the new connector_peppol_submissions table and gate status/evidence; inbound documents are served from the hosted archive filtered by the participants the key holds. Per-company quota (peppol_connections_per_company), the shared PEPPOL_RECEIVING_MAX_REGISTRATIONS cap, and the global peppol rate budget apply. Provider failures cross as CONNECTOR_UPSTREAM_ERROR with the adapter's retryable flag (422 or 502). Instance: lib/invoices/transports/connector.ts implements PeppolTransport over that API and registers itself in connector mode (key present, no QVALIA_* keys); getPeppolTransportAvailability() defaults to it when no provider is selected, so an instance needs no PEPPOL_TRANSPORT_PROVIDER. Webhooks are not brokered; the existing outbound status poll covers it. Hosted is byte-identical: it has its own keys, so connector mode is never on. Docs: SELF-HOSTING.md, SOVEREIGN.md, .env.example. Switch-on for third-party instances stays gated on the Qvalia brokering-terms check; without the scope every operation answers 403. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MMUUom4fUk6zi4xYZSSfat Signed-off-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com> * fix(connect): authorize Peppol participants per key, harden the proxy after review Review follow-ups on #2177. Authorization: a key may only register (and send as) participant identifiers Arcim recorded on the key at issuance (connector_keys.peppol_participants, migration 20260902191000) or the licensee's own org number, and a document may only be submitted as a sender the key has registered; X-Connector-Company stays an opaque per-company ref. Cap: the shared access-point cap now counts fresh pending reservations and is re-checked after this request's own reservation, so concurrent registrations cannot both pass. Inbound: both halves of the participant id are filtered in the archive query (over-fetched, then exact-pair checked), so foreign rows sharing an identifier cannot consume the limit. Delete: deregistration is a required transport capability, checked before the ledger row is revoked, and registration refuses an access point that cannot deregister. Instance transport: the hosted URL must be https (loopback http only, same rule as getConnectorConfig), and the response body is read inside the timeout window with body-read failures mapped to retryable transport errors. issue-connector-key.ts gains --peppol-participants and --peppol-connections-per-company. Declined: NOT VALID on the ledger CHECK (the table is empty until keys are issued; the validated scan is instant). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MMUUom4fUk6zi4xYZSSfat Signed-off-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com> * fix(connect): bind Peppol ownership to the instance company, query exact participant pairs Second review round on #2177. Ownership is now (key, company_ref), not key alone: a sender must be registered under the same company header, status and evidence reads look the submission up under the header company, DELETE and re-registration refuse a participant the key holds for another company, so one company on a multi-company instance cannot act on another company's registration through the shared key. The instance transport resolves the owning company from its own peppol_deliveries / peppol_registrations rows before status, evidence and deregistration calls (deps.companyFor, deps.companyForParticipant, wired in transports/index.ts). Inbound listing stays key-wide (the instance routes documents to its own companies by its own registrations). The archive query now runs one exact-pair query per scheme (scheme fixed, that scheme's identifiers), so neither foreign nor cross-pair rows can consume the limit. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MMUUom4fUk6zi4xYZSSfat Signed-off-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com> --------- Signed-off-by: Jakob Wennberg <jakob.wennberg@arcim.io> Signed-off-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com> Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
204 lines
7.8 KiB
TypeScript
204 lines
7.8 KiB
TypeScript
import crypto from 'node:crypto'
|
|
import type { SupabaseClient } from '@supabase/supabase-js'
|
|
|
|
/**
|
|
* The connector connection ledger: proof, without secrets, that a connection
|
|
* belongs to a given connector key. Every bank/SKV connection is born through
|
|
* the proxy (the consent redirect is ours), so the proxy records it at
|
|
* creation and checks ownership on every later use. The upstream handle (EB
|
|
* session id, SKV access token) is hashed; the value never rests here.
|
|
*/
|
|
|
|
export type ConnectorService = 'bank' | 'skatteverket' | 'peppol'
|
|
|
|
export function hashHandle(handle: string): string {
|
|
return crypto.createHash('sha256').update(handle).digest('hex')
|
|
}
|
|
|
|
export interface LedgerRow {
|
|
id: string
|
|
connector_key_id: string
|
|
service: ConnectorService
|
|
company_ref: string
|
|
provider: string | null
|
|
account_uids: string[]
|
|
status: 'pending' | 'active' | 'revoked'
|
|
}
|
|
|
|
/**
|
|
* Pending rows count toward quota only while their consent window is open:
|
|
* the signed connector state expires after 15 minutes, so an abandoned
|
|
* consent stops reserving capacity once its state can no longer activate it.
|
|
*/
|
|
export const PENDING_QUOTA_WINDOW_MS = 15 * 60 * 1000
|
|
|
|
/**
|
|
* Rows currently holding or reserving quota for (key, service, company):
|
|
* active connections plus fresh pending reservations. Used by the /auth
|
|
* quota check both before insert (fast reject) and after insert (the
|
|
* reservation re-count that closes the concurrent-auth race).
|
|
*/
|
|
export async function countHeldConnections(
|
|
supabase: SupabaseClient,
|
|
keyId: string,
|
|
service: ConnectorService,
|
|
companyRef: string,
|
|
now: Date = new Date(),
|
|
): Promise<number> {
|
|
const freshPendingSince = new Date(now.getTime() - PENDING_QUOTA_WINDOW_MS).toISOString()
|
|
const { count, error } = await supabase
|
|
.from('connector_connections')
|
|
.select('id', { count: 'exact', head: true })
|
|
.eq('connector_key_id', keyId)
|
|
.eq('service', service)
|
|
.eq('company_ref', companyRef)
|
|
.or(`status.eq.active,and(status.eq.pending,created_at.gte.${freshPendingSince})`)
|
|
if (error) throw new Error(`ledger count failed: ${error.message}`)
|
|
return count ?? 0
|
|
}
|
|
|
|
/** Roll back a just-created pending reservation (lost the quota re-count). */
|
|
export async function deletePendingConnectionById(supabase: SupabaseClient, id: string): Promise<void> {
|
|
await supabase.from('connector_connections').delete().eq('id', id).eq('status', 'pending')
|
|
}
|
|
|
|
export async function createPendingConnection(
|
|
supabase: SupabaseClient,
|
|
params: { keyId: string; service: ConnectorService; companyRef: string; provider: string | null; pendingState: string },
|
|
): Promise<string> {
|
|
const { data, error } = await supabase
|
|
.from('connector_connections')
|
|
.insert({
|
|
connector_key_id: params.keyId,
|
|
service: params.service,
|
|
company_ref: params.companyRef,
|
|
provider: params.provider,
|
|
pending_state: params.pendingState,
|
|
status: 'pending',
|
|
})
|
|
.select('id')
|
|
.single()
|
|
if (error || !data) throw new Error(`ledger insert failed: ${error?.message}`)
|
|
return (data as { id: string }).id
|
|
}
|
|
|
|
/**
|
|
* The pending row a signed state belongs to, under the presenting key.
|
|
* Precondition for the code exchange at POST /sessions: exchanging a code
|
|
* against a state with no pending row would mint an upstream session the
|
|
* ledger never records (and cross-flow substitution could smuggle a code
|
|
* into a foreign state). The state's own TTL bounds freshness.
|
|
*/
|
|
export async function findPendingByState(
|
|
supabase: SupabaseClient,
|
|
params: { keyId: string; pendingState: string },
|
|
): Promise<LedgerRow | null> {
|
|
const { data, error } = await supabase
|
|
.from('connector_connections')
|
|
.select('id, connector_key_id, service, company_ref, provider, account_uids, status')
|
|
.eq('connector_key_id', params.keyId)
|
|
.eq('pending_state', params.pendingState)
|
|
.eq('status', 'pending')
|
|
.maybeSingle()
|
|
if (error) throw new Error(`ledger pending lookup failed: ${error.message}`)
|
|
return (data as LedgerRow | null) ?? null
|
|
}
|
|
|
|
/**
|
|
* The ACTIVE row whose refresh-token hash matches, under the presenting key.
|
|
* Ownership precondition for the SKV refresh exchange: without it the broker
|
|
* was an open refresh oracle for any leaked refresh token.
|
|
*/
|
|
export async function findByRefreshHash(
|
|
supabase: SupabaseClient,
|
|
params: { keyId: string; refreshHash: string },
|
|
): Promise<LedgerRow | null> {
|
|
const { data, error } = await supabase
|
|
.from('connector_connections')
|
|
.select('id, connector_key_id, service, company_ref, provider, account_uids, status')
|
|
.eq('connector_key_id', params.keyId)
|
|
.eq('service', 'skatteverket')
|
|
.eq('refresh_hash', params.refreshHash)
|
|
.eq('status', 'active')
|
|
.maybeSingle()
|
|
if (error) throw new Error(`ledger refresh lookup failed: ${error.message}`)
|
|
return (data as LedgerRow | null) ?? null
|
|
}
|
|
|
|
/** Activate a pending connection (found by its signed pending_state) with the live handle + accounts. */
|
|
export async function activateByPendingState(
|
|
supabase: SupabaseClient,
|
|
params: { keyId: string; pendingState: string; handle: string; accountUids?: string[] },
|
|
): Promise<LedgerRow | null> {
|
|
const { data, error } = await supabase
|
|
.from('connector_connections')
|
|
.update({
|
|
status: 'active',
|
|
handle_hash: hashHandle(params.handle),
|
|
account_uids: params.accountUids ?? [],
|
|
pending_state: null,
|
|
activated_at: new Date().toISOString(),
|
|
last_used_at: new Date().toISOString(),
|
|
})
|
|
.eq('connector_key_id', params.keyId)
|
|
.eq('pending_state', params.pendingState)
|
|
.eq('status', 'pending')
|
|
.select('id, connector_key_id, service, company_ref, provider, account_uids, status')
|
|
.maybeSingle()
|
|
if (error) throw new Error(`ledger activate failed: ${error.message}`)
|
|
return (data as LedgerRow | null) ?? null
|
|
}
|
|
|
|
/** The active ledger row that owns a given handle under a key. Ownership check for reads/writes. */
|
|
export async function findByHandle(
|
|
supabase: SupabaseClient,
|
|
params: { keyId: string; service: ConnectorService; handle: string },
|
|
): Promise<LedgerRow | null> {
|
|
const { data, error } = await supabase
|
|
.from('connector_connections')
|
|
.select('id, connector_key_id, service, company_ref, provider, account_uids, status')
|
|
.eq('connector_key_id', params.keyId)
|
|
.eq('service', params.service)
|
|
.eq('handle_hash', hashHandle(params.handle))
|
|
.eq('status', 'active')
|
|
.maybeSingle()
|
|
if (error) throw new Error(`ledger lookup failed: ${error.message}`)
|
|
return (data as LedgerRow | null) ?? null
|
|
}
|
|
|
|
/** The active ledger row that owns a bank account uid under a key. */
|
|
export async function findByAccountUid(
|
|
supabase: SupabaseClient,
|
|
params: { keyId: string; accountUid: string },
|
|
): Promise<LedgerRow | null> {
|
|
const { data, error } = await supabase
|
|
.from('connector_connections')
|
|
.select('id, connector_key_id, service, company_ref, provider, account_uids, status')
|
|
.eq('connector_key_id', params.keyId)
|
|
.eq('service', 'bank')
|
|
.eq('status', 'active')
|
|
.contains('account_uids', [params.accountUid])
|
|
.limit(1)
|
|
.maybeSingle()
|
|
if (error) throw new Error(`ledger account lookup failed: ${error.message}`)
|
|
return (data as LedgerRow | null) ?? null
|
|
}
|
|
|
|
export async function touchConnection(supabase: SupabaseClient, id: string): Promise<void> {
|
|
await supabase.from('connector_connections').update({ last_used_at: new Date().toISOString() }).eq('id', id)
|
|
}
|
|
|
|
/** Revoke by handle (DELETE /sessions). Idempotent. */
|
|
export async function revokeByHandle(
|
|
supabase: SupabaseClient,
|
|
params: { keyId: string; service: ConnectorService; handle: string },
|
|
): Promise<void> {
|
|
await supabase
|
|
.from('connector_connections')
|
|
.update({ status: 'revoked', revoked_at: new Date().toISOString() })
|
|
.eq('connector_key_id', params.keyId)
|
|
.eq('service', params.service)
|
|
.eq('handle_hash', hashHandle(params.handle))
|
|
.eq('status', 'active')
|
|
}
|