Files
accounted/.compliance/ropa.yaml
T
MattssonandClaude Fable 5 aab7e47c35 Bug/skv auth (#1010)
* fix(settings): open Skatteverket connect in a popup and fix the skahmst scope check

The full-page OAuth round-trip left Skatteverket's pages and the consumed
callback URL in browser history directly beneath /settings/tax, so closing
settings walked Back into a dead OAuth chain and re-prompted BankID auth.
The connect buttons now use the AGIPanel popup + postMessage pattern (the
callback already supports window.opener); the page never navigates and the
panel refetches status on success. Full-page navigation remains only as the
popup-blocked fallback.

Also fixes the reconnect-button condition: it checked for a scope literally
named 'skattekonto', but SKV grants 'skahmst', which kept "Anslut igen"
permanently visible on healthy connections.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor(skatteverket): extract per-declaration AGI kvittens reconciliation

Behavior-identical extraction of the kvittens cron's core (fetch kvittens,
promote declaration to submitted, stamp salary_runs, clear cached submission,
complete deadline, notify) into lib/agi-kvittens-reconcile.ts so the upcoming
post-connect refresh can reuse it. Auth-error mapping (needs_reconsent, grant
revocation, APIGW config gaps) and run-level logging stay in the cron, which
is why SkatteverketAuthError propagates out of the helper on purpose.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(skatteverket): auto-settle production-format AGI skattekonto draws

The settlement matcher only understood the SKV test environment's single
combined row ("Arbetsgivardeklaration YYYYMM"). Production books the draw as
two rows with Swedish month names: "Avdragen skatt maj 2026" (= total_tax)
and "Arbetsgivaravgift maj 2026" (= total_avgifter), so auto-settlement has
never fired against production data and the salary page kept showing paid
periods as unpaid.

parseAgiPeriod now also reads the month-name form (which additionally lets
match suggestions resolve the period on prod rows, including beslut rows).
Settlement classifies draws with start-anchored regexes so correction rows
like "Beslut 260703 arbetsgivaravgift mars 2026" can never qualify, and
settles a period on either the combined row matching the whole declared
amount or exactly one tax row + exactly one avgift row matching their
respective totals to the ore, dated to the later of the pair. Anything
non-exact (partial draws, duplicates) still falls back to the manual
mark-paid button.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(skatteverket): refresh skattekonto + kvittenser right after OAuth consent

Nothing fetched Skatteverket data after a (re)connect: tokens were stored and
the user redirected, with the next fetch left to the nightly cron. SKV's
per-flow tokens (and refresh tokens) live ~65 minutes, so the crons usually
find them dead; right after consent is the one reliable window for a
personal-token fetch, which is why reconnecting never made stale numbers
recover.

The callback now awaits runPostConnectRefresh after storing tokens: a
skattekonto sync (upsert + auto-settlement + balance snapshot) plus a
kvittens re-check for this company's pending_signature AGI declarations.
Awaited on purpose so popup-close means the data is already fresh and UI
refetch listeners never race a background job; every step is best-effort and
a refresh failure can never fail the connect that just succeeded.

The callback's non-popup fallback also switches to window.location.replace
so the consumed callback URL (one-shot code + state) drops out of history
instead of re-running into a guaranteed CSRF error on Back.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(salary): reload the salary dashboard after a Skatteverket reconnect

Listens for the BankID popup's skatteverket-oauth-success message and re-runs
load(). Because the OAuth callback awaits the skattekonto sync and AGI
auto-settlement before responding, the refetch already sees settled
tax-payment state: the "Skatt att betala" card flips to paid the moment the
popup closes, without leaving the page.

Also logs the three decisions behind this series in DECISIONS.md (awaited
post-connect refresh over after(), exact-pair settlement over per-period
summing, popup flow over in-place history repair).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(skatteverket): verify OAuth popup source identity before trusting postMessage

The three 'skatteverket-oauth-success' listeners accepted any same-origin
message, letting any same-origin script trigger a data reload or a fake
success toast (OWASP ASVS V3.2, SOC 2 CC6.1). The two components that open
the popup now keep its handle in a ref and require event.source to be that
exact window; a window reference cannot be forged by same-origin scripts,
which is strictly stronger than a nonce threaded through the OAuth flow.

The salary dashboard never opens the popup, so its raw message listener is
replaced by a 'skatteverket-connection-updated' CustomEvent dispatched only
after a component has source-verified the popup (and after disconnect, so
connection-state consumers stay in sync).

Also extends the connect consent copy (sv + en) to disclose that connecting
immediately fetches skattekonto data and checks pending AGI receipts
(GDPR Art.5(1)(b) transparency).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(skatteverket): CSP nonce and no-store on OAuth callback, deadline on post-connect refresh

Both callback HTML responses now carry a per-response nonce CSP
(default-src 'none'; script-src 'nonce-...'; base-uri 'none';
form-action 'none') so injected markup could never execute, plus
Cache-Control: no-store because the callback URL carries a one-shot
authorization code. The jsLiteral/appUrl injection invariants are
documented at the definition site.

The awaited post-connect refresh is bounded by a 30-second Promise.race
deadline so a hung SKV call cannot hold the OAuth callback open; on
timeout the refresh continues best-effort and the user still gets the
success response. Refresh failures and timeouts now log through the
structured logger with companyId + userId so they are attributable in
log aggregation (ASVS V16, ISO 27001 A.8.15, SOC 2 CC8.1).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(skatteverket): tenant guard and redacting logs in kvittens reconcile, slim cron response

The agi_declarations update now also filters on company_id (ASVS V8.2.1),
matching the salary_runs pattern. The reconciler and the cron's error paths
log through the structured logger so third-party error strings pass
personnummer redaction; uuidKvittens is dropped from log context
(GDPR Art.5(1)(f) minimization, declarationId suffices).

response_data gains submittedAtEstimated so the signeradTid fallback can
never be mistaken for the legal filing time, and the submitted_by comment
now states explicitly that it records the technical submitter while
response_data.signeradAv is the authoritative legal signatory
(BFL 5 kap 6 par, BFNAR 2013:2 kap 8).

The cron HTTP response omits companyId per result row and sends
Cache-Control: no-store; the extension_data delete documents why the
period-scoped cache key needs no declaration-id guard. Cron tests observe
the logger via a mock without weakening any assertion.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(skatteverket): diagnosable settlement refusals and signeradAv ROPA documentation

Settlement refusals (candidates present but amounts mismatch) now emit a
structured info log with declared-vs-drawn ore amounts per kind, so a
rounding divergence between stored declaration totals and SKV's actual
draw is diagnosable instead of silently falling back to the manual button.
No transaction texts are logged (they can carry personal data).

parseAgiPeriod documents the beslut-row audit: correction rows parse to
their period on purpose for match-suggestion boosting; settlement never
uses parseAgiPeriod (anchored classifiers + parseNumericAgiPeriod only)
and the only callers require an exact amount+side 1630 match first.

.compliance/ropa.yaml documents signeradAv (signer personnummer in the
SKV kvittens stored in agi_declarations.response_data): lawful basis
Art.6(1)(c) via BFL 5 kap 6 par / BFNAR 2013:2 kap 8, 7-year retention
per BFL 7 kap 2 par, access via company-membership RLS. DECISIONS.md
records the accepted-with-documentation calls from the compliance review.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(skatteverket): add 'already_claimed' status to reconcile outcomes and enhance logging for pending lookups

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-13 01:40:03 +02:00

375 lines
15 KiB
YAML

# Record of Processing Activities (GDPR Art. 30)
#
# Each entry documents one processing activity. Field shape follows EDPB
# Guidelines 9/2022 §3 (controller-side RoPA): purposes, lawful basis,
# data subject + data category, recipients, transfer mechanism, retention,
# security measures. Add an entry whenever a new flow ships that touches
# personal data: onboarding, integrations, support, or regulator filings.
processing_activities:
- id: agi.submit
name: AGI inlämning till Skatteverket
purpose: >-
Lämna in lagstadgad arbetsgivardeklaration på individnivå (AGI) till
Skatteverket varje månad (Skatteförfarandelagen 26 kap.). Innefattar
huvuduppgift (HU) och individuppgifter (IU) per anställd. Skatteverkets
kvittens sparas i response_data inklusive signeradAv: personnummer för
den som BankID-signerade inlämningen. Ändamålet är bevis för vem som
juridiskt undertecknade deklarationen samt behandlingshistorik; BFL
5 kap. 6 § och BFNAR 2013:2 kap. 8 kräver att räkenskapsinformationen
bevarar den faktiska ingivaren, medan själva inlämningen styrs av SFL.
lawful_basis: art_6_1_c # legal obligation
special_category_basis: null
controller: gnubok-tenant
processor: anthropic-na # software supplier; Skatteverket is recipient, not processor
data_subjects:
- employee
- company_signatory # firmatecknare/deklarationsombud (BankID-signerare av kvittensen)
data_categories:
- user.government_id # personnummer (anställda i IU; signerarens i response_data.signeradAv)
- user.name
- user.financial.employment # gross salary, tax withheld, benefits
- user.financial.tax # avgifter, sjuklönekostnad
recipients:
- name: Skatteverket
country: SE
role: legal_recipient
international_transfers:
applicable: false
mechanism: null
note: >-
Sweden-to-Sweden processor-to-public-authority flow. Adequacy decision
not applicable; no third-country transfer.
retention:
duration: 7y
basis: bfl_7_kap # BFL 7 kap. 2 §: räkenskapsinformation
stored_in:
- agi_declarations.xml_content
- agi_declarations.individuppgifter
- agi_declarations.response_data # SKV kvittens incl. signeradAv (signerarens pnr); access via company-membership RLS
- skatteverket_api_audit_log
security_measures:
- encryption_at_rest_supabase
- rls_company_scoped
- tls_1_3_to_skatteverket
- bankid_signing_required_for_filing
- immutable_audit_log
- personnummer_at_rest_encryption
- id: agi.kontrollera.preflight
name: AGI pre-flight kontrollera (HU/IU)
purpose: >-
Skicka enskild HU eller IU som JSON till Skatteverkets kontrollera-
ändpunkt (v1.7 §7/§8) för dry-run-validering av felmeddelanden och
STOPP-/AVVISANDE-status innan ett fullständigt underlag laddas upp.
Skatteverket lagrar inget från denna kontroll; svaret driver vår UI
som låter användaren rätta felaktigheter i lönekörningen lokalt.
lawful_basis: art_6_1_c # legal obligation (ancillary to AGI filing)
special_category_basis: null
controller: gnubok-tenant
processor: anthropic-na
data_subjects:
- employee
data_categories:
- user.government_id # personnummer (BetalningsmottagarId)
- user.financial.employment # gross salary, tax withheld, benefits
recipients:
- name: Skatteverket
country: SE
role: legal_recipient
international_transfers:
applicable: false
mechanism: null
note: Sweden-to-Sweden flow; no third-country transfer.
retention:
# Skatteverket retains nothing for kontrollera calls. Our outbound
# audit row in skatteverket_api_audit_log records who-called-what-when
# but NOT the payload body, minimising at-rest footprint.
duration: 7y
basis: bfl_7_kap
stored_in:
- skatteverket_api_audit_log
security_measures:
- strict_zod_allow_list_input_validation
- request_size_cap_64kb
- rbac_company_member_role_check
- rls_company_scoped
- tls_1_3_to_skatteverket
- immutable_audit_log
- no_payload_body_persisted
- id: moms.declaration
name: Momsdeklaration till Skatteverket
purpose: >-
Lämna in lagstadgad momsdeklaration (utkast, lås och signering) till
Skatteverkets momsdeklaration-API (Mervärdesskattelagen 17 kap. 24 §).
lawful_basis: art_6_1_c
special_category_basis: null
controller: gnubok-tenant
processor: anthropic-na
data_subjects:
- business_owner
data_categories:
- user.government_id # orgnummer (juridiska personer) eller pnr
- user.financial.tax # rutor 05-62
recipients:
- name: Skatteverket
country: SE
role: legal_recipient
international_transfers:
applicable: false
mechanism: null
note: Sweden-to-Sweden flow; no third-country transfer.
retention:
duration: 7y
basis: bfl_7_kap
stored_in:
- extension_data (utkast metadata)
- skatteverket_api_audit_log
security_measures:
- rls_company_scoped
- tls_1_3_to_skatteverket
- bankid_signing_required_for_filing
- immutable_audit_log
- id: psd2.cash_account_mirror
name: PSD2-konton speglas till cash_accounts
purpose: >-
När en bank-anslutning via Enable Banking returnerar kontolista efter
lyckad PSD2-consent kopieras kontometadata (IBAN, valuta, kontonamn,
external_uid) till cash_accounts så att avstämning, motkontoresolver
och __PRIMARY_SEK__-sentinel kan rutta verifikat utan att läsa JSONB
från bank_connections.accounts_data vid varje fråga.
lawful_basis: art_6_1_b # contract (PSD2 consent + bookkeeping service)
special_category_basis: null
controller: gnubok-tenant
processor: anthropic-na
data_subjects:
- business_owner
data_categories:
- user.financial.bank_account # IBAN
- user.contact # account name (kontotitel)
recipients:
- name: Supabase
country: EU
role: processor
international_transfers:
applicable: false
mechanism: null
note: EU-only processor; no third-country transfer.
retention:
duration: consent_lifetime
basis: psd2_consent
stored_in:
- cash_accounts
- bank_connections.accounts_data
security_measures:
- rls_company_scoped
- data_minimization_no_balance_on_callback
- failure_emitted_to_event_log
- id: transactions.counterparty_iban
name: Motpartens IBAN på transaktioner
purpose: >-
Spara motpartens IBAN på transaktionsraden så att own-account-detector
kan identifiera överföringar mellan företagets egna konton (1930 → 1932
etc.) och bokföra båda benen automatiskt istället för att felbokföra
utflödet som extern kostnad. Krävs även för payment-matchning mot
leverantörsfakturor.
lawful_basis: art_6_1_b # contract (bookkeeping service)
special_category_basis: null
controller: gnubok-tenant
processor: anthropic-na
data_subjects:
- business_owner
- counterparty
data_categories:
- user.financial.bank_account # counterparty IBAN
recipients:
- name: Supabase
country: EU
role: processor
international_transfers:
applicable: false
mechanism: null
note: EU-only processor.
retention:
duration: 7y
basis: bfl_7_kap
stored_in:
- transactions.counterparty_iban
security_measures:
- rls_company_scoped
- immutable_after_post
- id: skattekonto.drift_alert
name: Skattekonto-drift via e-post
purpose: >-
Underrätta företagets kontaktadress när det cachade Skatteverket-saldot
avviker från GL 1630 utöver konfigurerad tolerans (> 1 SEK), så
bokföraren kan granska skattekonto-raderna. E-postmeddelandet
innehåller ingen finansiell siffra utan en länk till autentiserad
dashboard; mottagaren valideras mot company_members innan utskick.
lawful_basis: art_6_1_f # legitimate interest (bookkeeping accuracy)
special_category_basis: null
controller: gnubok-tenant
processor: resend
data_subjects:
- business_owner
- company_member
data_categories:
- user.contact.email
recipients:
- name: Resend
country: US
role: processor
international_transfers:
applicable: true
mechanism: scc_2021_c2p
note: >-
Resend (US): SCC Module 2 (controller-to-processor). Outbound
payload limited to ett notifieringsmail utan finansiella belopp;
TIA dokumenterad i .compliance/tia/resend.md.
retention:
duration: 30d
basis: event_log_ttl
stored_in:
- event_log
security_measures:
- recipient_membership_check_before_send
- no_financial_figures_in_body
- tls_to_resend
- rls_company_scoped
- id: ai.inference
name: AI-inferens (kategorisering + dokumenttolkning) via Amazon Bedrock
purpose: >-
Föreslå bokföringskategori för banktransaktioner och tolka/extrahera
uppladdade underlag (kvitton, leverantörsfakturor) med Anthropic
Claude-modeller körda i Amazon Bedrock. Endast aktiv när tenanten
uttryckligen aktiverat AI-funktioner: kärntjänsten (bokföring, fakturor,
moms, rapporter) fungerar fullt ut utan AI.
lawful_basis: art_6_1_a # consent: opt-in, AI features off by default
special_category_basis: null
controller: gnubok-tenant
processor: aws-bedrock
data_subjects:
- business_owner
- counterparty # namn/belopp på uppladdade underlag
data_categories:
- user.financial # transaktionsdata skickad för kategorisering
- user.document # uppladdade kvitton/fakturor för OCR/extraktion
recipients:
- name: Amazon Web Services (Amazon Bedrock)
country: EU
role: processor
international_transfers:
applicable: false
mechanism: null
note: >-
Inferens körs i AWS-regionen eu-north-1 (Stockholm): ingen överföring
till tredje land. AWS DPA + SCC + DPF-certifiering finns som
skyddsmekanism. Prompter lagras ej hos Bedrock efter anropet och används
ej till modellträning.
retention:
duration: none_at_processor
basis: no_retention_bedrock # prompt not persisted by Bedrock post-inference
stored_in:
- ai_usage_tracking # usage metadata only (tokens/cost), no payload body
security_measures:
- opt_in_consent_required
- eu_region_inference_eu_north_1
- prompts_not_retained_after_inference
- not_used_for_model_training
- rls_company_scoped
- tls_to_bedrock
- id: mcp.telemetry
name: MCP/agent-telemetri i event_log
purpose: >-
Varje MCP-verktygsanrop loggar metadata (verktygsnamn, felkod,
felmeddelande max 500 tecken, latens, aktör, session, frivillig
distributionskanal-markör, t.ex. 'openclaw' via X-Gnubok-Client-header
eller ?client=-parameter, sanerad mot allow-list och aldrig använd för
auktorisation) och varje skill-laddning loggar slug/tier till event_log.
Syftet är tillförlitlighetsanalys av agentgränssnittet: felfrekvens per
verktyg, adoption per distributionskanal, korrelation mellan laddade
skills och efterföljande fel, samt agenters egenrapporterade feedback
(agent.feedback). Inga verktygsargument eller verktygsresultat
persisteras.
lawful_basis: art_6_1_f # legitimate interest (service reliability/improvement)
special_category_basis: null
controller: gnubok-tenant
processor: supabase
data_subjects:
- business_owner
data_categories:
- user.unique_id # userId, actorId (API-nyckel-id), sessionId
- user.contact # actorLabel (användarvald API-nyckeletikett)
recipients:
- name: Supabase
country: EU
role: processor
international_transfers:
applicable: false
mechanism: null
note: EU-only processor; no third-country transfer.
retention:
# Differentiated TTL via /api/events/cleanup/cron: mcp.*/agent.*-rader
# behålls 180 dagar (felfrekvens-trender kräver mer än leveransfönstret);
# övriga event_log-rader (leveranshändelser) 30 dagar.
duration: 180d
basis: legitimate_interest_reliability
stored_in:
- event_log
security_measures:
- rls_user_scoped_select # event_log SELECT: auth.uid() = user_id
- service_role_only_writes
- error_message_truncated_500_chars
- no_tool_args_or_results_persisted
- id: arsredovisning.bolagsverket.submit
name: Digital inlämning av årsredovisning till Bolagsverket
purpose: >-
Lämna in årsredovisningen (iXBRL) digitalt till Bolagsverkets eget
utrymme (ÅRL 8 kap.). Avsändarens och undertecknarens personnummer
krävs av Bolagsverkets API (skapa-inlamningtoken, lamna-in) och
används transient i anropen; i databasen sparas endast
företagssaltade SHA-256-hashar. Fastställelseintyget signeras med
e-legitimation hos Bolagsverket, aldrig i appen.
lawful_basis: art_6_1_c # legal obligation (ÅRL filing duty)
special_category_basis: null
controller: gnubok-tenant
processor: anthropic-na # software supplier; Bolagsverket is recipient, not processor
data_subjects:
- business_owner # avsändare/undertecknare (styrelseledamot, VD)
data_categories:
- user.government_id # personnummer (transient; at rest only salted SHA-256 hash)
- user.name # undertecknarens namn
- user.contact # undertecknarens/kvittens e-post
- user.financial # årsredovisningens finansiella innehåll
recipients:
- name: Bolagsverket
country: SE
role: legal_recipient
international_transfers:
applicable: false
mechanism: null
note: Sweden-to-Sweden flow to a public authority; no third-country transfer.
retention:
duration: 7y
basis: bfl_7_kap # filed .xhtml archived as räkenskapsinformation
stored_in:
- arsredovisning_submissions # status, idnummer, checksums, PNR hashes only
- document_attachments # the exact filed iXBRL bytes (WORM)
security_measures:
- mtls_client_certificate_to_bolagsverket
- mtls_key_env_only_injected_from_secret_manager # never in settings/DB; see .env.example custody note
- pinned_endpoint_allowlist_per_environment # HOSTS map in client.ts; not env-configurable
- personnummer_never_persisted_plaintext_salted_sha256_only
- personnummer_never_logged
- webhook_secret_constant_time_validation
- rls_company_scoped
- immutable_status_machine_trigger