Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Add FinanceKit device publisher (#3633)

Juan José Mata355648ce5d67
diff --git a/app/controllers/api/v1/financekit/base_controller.rb b/app/controllers/api/v1/financekit/base_controller.rb
new file mode 100644
index 0000000000..5e68e54cee
--- /dev/null
+++ b/app/controllers/api/v1/financekit/base_controller.rb
@@ -0,0 +1,42 @@
+class Api::V1::Financekit::BaseController < Api::V1::BaseController
+ wrap_parameters false
+
+ before_action :require_financekit_access
+ rescue_from Financekit::Error, with: :protocol_error
+ rescue_from ActiveRecord::RecordInvalid, with: :invalid_record
+ rescue_from ActiveRecord::RecordNotUnique, with: :duplicate_record
+ rescue_from KeyError, with: :invalid_record
+
+ private
+
+ def require_financekit_access
+ return unless authorize_scope!(request.get? || request.head? ? :read : :write)
+ unless current_resource_owner.admin? && current_resource_owner.preview_features_enabled?
+ raise Financekit::Error.new("publisher_forbidden", 403)
+ end
+ unless action_name == "capabilities" || Financekit.enabled?(current_resource_owner.family) || action_name == "destroy"
+ raise Financekit::Error.new("unavailable", 503)
+ end
+ end
+
+ def connection
+ @connection ||= current_resource_owner.family.financekit_items.where(user: current_resource_owner).find(params[:connection_id] || params[:id])
+ end
+
+ def input
+ request.request_parameters
+ end
+
+ def protocol_error(error)
+ response.headers["Retry-After"] = "60" if [ 429, 503 ].include?(error.status)
+ render_json({ error: error.code }, status: error.status)
+ end
+
+ def invalid_record(_error)
+ protocol_error(Financekit::Error.new("validation_failed"))
+ end
+
+ def duplicate_record(_error)
+ protocol_error(Financekit::Error.new("resource_conflict", 409))
+ end
+end
diff --git a/app/controllers/api/v1/financekit/batches_controller.rb b/app/controllers/api/v1/financekit/batches_controller.rb
new file mode 100644
index 0000000000..ae0c4f73d0
--- /dev/null
+++ b/app/controllers/api/v1/financekit/batches_controller.rb
@@ -0,0 +1,47 @@
+class Api::V1::Financekit::BatchesController < ActionController::API
+ rescue_from Financekit::Error, with: :protocol_error
+ rescue_from ActiveRecord::RecordNotFound do
+ render json: { error: "not_found" }, status: :not_found
+ end
+
+ def show
+ item = authenticated_item!
+ batch = item.financekit_batches.find_by!(generation: item.generation, batch_id: params[:batch_id])
+ render json: batch.receipt
+ end
+
+ def create
+ raise Financekit::Error.new("invalid_content_type", 400) unless request.media_type == "application/json"
+ raise Financekit::Error.new("payload_too_large", 413) if request.content_length.to_i > Financekit::MAX_BYTES
+
+ item = authenticated_item!
+
+ batch = FinancekitBatch.accept!(item, limited_body,
+ claimed_digest: request.headers["X-Sure-Payload-SHA256"],
+ idempotency_key: request.headers["Idempotency-Key"])
+ render json: batch.receipt, status: :accepted
+ end
+
+ private
+ def authenticated_item!
+ item = FinancekitItem.find_by(publisher_id: params[:publisher_id])
+ token = request.authorization&.match(/\ABearer ([A-Za-z0-9_-]+)\z/)&.captures&.first # pipelock:ignore Credential in URL
+ raise Financekit::Error.new("publisher_unauthorized", 401) unless item&.authenticate_credential?(token)
+ item
+ end
+
+ def limited_body
+ body = request.body
+ result = +""
+ while (chunk = body.read(16.kilobytes))
+ result << chunk
+ raise Financekit::Error.new("payload_too_large", 413) if result.bytesize > Financekit::MAX_BYTES
+ end
+ result
+ end
+
+ def protocol_error(error)
+ response.headers["Retry-After"] = "60" if [ 429, 503 ].include?(error.status)
+ render json: { error: error.code }, status: error.status
+ end
+end
diff --git a/app/controllers/api/v1/financekit/conflicts_controller.rb b/app/controllers/api/v1/financekit/conflicts_controller.rb
new file mode 100644
index 0000000000..e7abb7e66d
--- /dev/null
+++ b/app/controllers/api/v1/financekit/conflicts_controller.rb
@@ -0,0 +1,20 @@
+class Api::V1::Financekit::ConflictsController < Api::V1::Financekit::BaseController
+ def index
+ conflicts = connection.financekit_conflicts.open.order(created_at: :desc)
+ .offset((safe_page_param - 1) * safe_per_page_param).limit(safe_per_page_param)
+ render_json({ conflicts: conflicts.map { |conflict| conflict_data(conflict) } })
+ end
+
+ def update
+ conflict = connection.financekit_conflicts.find(params[:id])
+ conflict.resolve!(user: current_resource_owner, resolution: input.fetch("resolution"))
+ render_json(conflict_data(conflict))
+ end
+
+ private
+
+ def conflict_data(conflict)
+ conflict.as_json(only: %i[id kind status details resolution resolved_at created_at],
+ methods: %i[financekit_account_lineage_id financekit_transaction_id])
+ end
+end
diff --git a/app/controllers/api/v1/financekit/connections_controller.rb b/app/controllers/api/v1/financekit/connections_controller.rb
new file mode 100644
index 0000000000..9770cf5f08
--- /dev/null
+++ b/app/controllers/api/v1/financekit/connections_controller.rb
@@ -0,0 +1,81 @@
+class Api::V1::Financekit::ConnectionsController < Api::V1::Financekit::BaseController
+ def capabilities
+ available = Financekit.enabled?(current_resource_owner.family)
+ render_json({ available: available, protocol_versions: [ Financekit::VERSION ],
+ delivery: "background_publisher", max_payload_bytes: Financekit::MAX_BYTES,
+ max_records: Financekit::MAX_RECORDS, max_accounts: Financekit::MAX_ACCOUNTS,
+ max_queued_batches: Financekit::MAX_QUEUED, transaction_statuses: Financekit::Payload::STATUSES,
+ amount_precision: 19, amount_scale: 4 })
+ end
+
+ def create
+ result = Financekit::Enrollment.create!(current_resource_owner, input)
+ render_json(connection_data(result.item), status: result.created ? :created : :ok)
+ end
+
+ def show
+ mappings = connection.financekit_accounts.order(:id)
+ total = mappings.count
+ render_json(connection_data(connection).merge(
+ accounts: mappings.includes(financekit_account_lineage: :account)
+ .offset((safe_page_param - 1) * safe_per_page_param).limit(safe_per_page_param).map { |mapping| mapping_data(mapping) },
+ pagination: { page: safe_page_param, per_page: safe_per_page_param, total_count: total,
+ total_pages: (total.to_f / safe_per_page_param).ceil }))
+ end
+
+ def mapping
+ mapping = FinancekitAccount.map!(connection, params[:source_id], input)
+ render_json(mapping_data(mapping))
+ end
+
+ def activate
+ credential = connection.activate!
+ render_json(publisher_configuration(connection, credential))
+ end
+
+ def credential
+ credential = connection.renew_credential!
+ render_json(publisher_configuration(connection, credential))
+ end
+
+ def repair
+ credential = connection.repair!
+ render_json(publisher_configuration(connection, credential))
+ end
+
+ def destroy
+ connection.disconnect!
+ head :no_content
+ end
+
+ private
+
+ def connection_data(item)
+ { id: item.id, connection_id: item.id, publisher_id: item.publisher_id, status: item.status,
+ generation: item.generation, stream_id: item.stream_id, next_sequence: item.next_sequence,
+ repair_reason: item.repair_reason, last_device_contact_at: item.last_device_contact_at,
+ last_accepted_at: item.last_accepted_at, last_imported_at: item.last_imported_at,
+ last_downstream_at: item.last_downstream_at, last_captured_at: item.last_captured_at,
+ open_conflicts: item.financekit_conflicts.open.count }
+ end
+
+ def mapping_data(mapping)
+ mapping.as_json(only: %i[source_id mapping_version name institution_name currency accountable_type subtype ledger_timezone])
+ .merge("lineage_id" => mapping.financekit_account_lineage_id, "account_id" => mapping.account&.id)
+ end
+
+ def publisher_configuration(item, credential)
+ connection_data(item).merge(
+ protocol_version: Financekit::VERSION,
+ server_url: request.base_url,
+ upload_url: api_v1_financekit_publisher_batches_upload_url(publisher_id: item.publisher_id),
+ consent: item.consent.except("recorded_at"),
+ account_bindings: item.selected_accounts.order(:source_id).map do |mapping|
+ { source_account_id: mapping.source_id, lineage_id: mapping.financekit_account_lineage_id,
+ mapping_version: mapping.mapping_version }
+ end,
+ max_records_per_batch: Financekit::MAX_RECORDS,
+ max_bytes_per_batch: Financekit::MAX_BYTES,
+ publisher_credential: credential)
+ end
+end
diff --git a/app/jobs/financekit_inbox_job.rb b/app/jobs/financekit_inbox_job.rb
new file mode 100644
index 0000000000..ca6fd6f859
--- /dev/null
+++ b/app/jobs/financekit_inbox_job.rb
@@ -0,0 +1,21 @@
+class FinancekitInboxJob < ApplicationJob
+ queue_as :high_priority
+
+ def perform(item_id = nil)
+ items = item_id ? FinancekitItem.where(id: item_id) : FinancekitItem.where(status: "active")
+ items.find_each do |item|
+ next unless Financekit.enabled?(item.family)
+
+ Financekit::MAX_QUEUED.times do
+ break unless Financekit::Processor.new(item).apply_next!
+ end
+ end
+ FinancekitBatch.where(status: "applied", downstream_completed_at: nil).find_each do |batch|
+ next unless Financekit.enabled?(batch.financekit_item.family)
+
+ Financekit::Downstream.new(batch).perform!
+ end
+ FinancekitBatch.where(status: %w[applied failed revoked]).where("updated_at < ?", 7.days.ago)
+ .where.not(payload: nil).update_all(payload: nil, updated_at: Time.current)
+ end
+end
diff --git a/app/models/account/provider_import_adapter.rb b/app/models/account/provider_import_adapter.rb
index 28388e1018..9548f87839 100644
--- a/app/models/account/provider_import_adapter.rb
+++ b/app/models/account/provider_import_adapter.rb
@@ -35,8 +35,9 @@ class Account::ProviderImportAdapter
# @param pending_transaction_id [String, nil] Plaid's linking ID for pending→posted reconciliation
# @param extra [Hash, nil] Optional provider-specific metadata to merge into transaction.extra
# @param investment_activity_label [String, nil] Optional activity type label (e.g., "Buy", "Dividend")
+ # @param allow_heuristic_matching [Boolean] Claim likely duplicates using amount/date matching
# @return [Entry] The created or updated entry
- def import_transaction(external_id:, amount:, currency:, date:, name:, source:, category_id: nil, kind: nil, merchant: nil, notes: nil, pending_transaction_id: nil, extra: nil, investment_activity_label: nil)
+ def import_transaction(external_id:, amount:, currency:, date:, name:, source:, category_id: nil, kind: nil, merchant: nil, notes: nil, pending_transaction_id: nil, extra: nil, investment_activity_label: nil, allow_heuristic_matching: true)
raise ArgumentError, "external_id is required" if external_id.blank?
raise ArgumentError, "source is required" if source.blank?
@@ -93,7 +94,7 @@ class Account::ProviderImportAdapter
# This handles the case where a user manually created or CSV imported a transaction
# before linking their account to a provider
# Note: We don't pass name here to allow matching even when provider formats names differently
- if entry.new_record?
+ if entry.new_record? && allow_heuristic_matching
duplicate = find_duplicate_transaction(date: date, amount: amount, currency: currency)
if duplicate
# Check if duplicate is protected - if so, link but don't modify
@@ -124,7 +125,7 @@ class Account::ProviderImportAdapter
# PRIORITY 2: Fallback to EXACT amount match (for SimpleFIN and providers without linking IDs)
# Only searches backward in time - pending date must be <= posted date
- if pending_match.nil?
+ if pending_match.nil? && allow_heuristic_matching
pending_match = find_pending_transaction(date: date, amount: amount, currency: currency, source: source)
if pending_match
Rails.logger.info("Reconciling pending→posted via exact amount match: claiming entry #{pending_match.id} (#{pending_match.name}) with new external_id #{external_id}")
@@ -270,7 +271,7 @@ class Account::ProviderImportAdapter
# AFTER save: For NEW posted transactions, check for fuzzy matches to SUGGEST (not auto-claim)
# This handles tip adjustments where auto-matching is too risky
- if is_new_posted
+ if is_new_posted && allow_heuristic_matching
# PRIORITY 1: Try medium-confidence fuzzy match (≤30% amount difference)
fuzzy_suggestion = find_pending_transaction_fuzzy(
date: date,
diff --git a/app/models/account_provider.rb b/app/models/account_provider.rb
index 5d39eb26b9..61f983a2f3 100644
--- a/app/models/account_provider.rb
+++ b/app/models/account_provider.rb
@@ -7,6 +7,8 @@ class AccountProvider < ApplicationRecord
validates :account_id, uniqueness: { scope: :provider_type }
validates :provider_id, uniqueness: { scope: :provider_type }
+ validate :financekit_has_exclusive_writer, if: -> { new_record? || will_save_change_to_account_id? || will_save_change_to_provider_id? || will_save_change_to_provider_type? }
+
# When unlinking a CoinStats account, also destroy the CoinstatsAccount record
# so it doesn't remain orphaned and count as "needs setup".
# Other providers may legitimately enter a "needs setup" state.
@@ -33,6 +35,21 @@ class AccountProvider < ApplicationRecord
private
+ def financekit_has_exclusive_writer
+ # belongs_to :account already reports a missing account; bail out rather
+ # than dereference it below.
+ return if account.nil?
+ # Every provider link takes the same canonical-account lock. This closes
+ # the race between FinanceKit mapping and another provider's setup flow.
+ Account.where(id: account_id).lock.pick(:id)
+ others = self.class.where(account_id: account_id).where.not(id: id)
+ conflict = provider_type == "FinancekitAccountLineage" ? others.exists? : others.where(provider_type: "FinancekitAccountLineage").exists?
+ errors.add(:account, "already has an exclusive FinanceKit publisher") if conflict
+ if provider_type == "FinancekitAccountLineage" && provider&.family_id != account.family_id
+ errors.add(:account, "must belong to the FinanceKit enrollment family")
+ end
+ end
+
def coinstats_provider?
provider_type == "CoinstatsAccount"
end
diff --git a/app/models/family.rb b/app/models/family.rb
index 807110c390..7d25ca9e45 100644
--- a/app/models/family.rb
+++ b/app/models/family.rb
@@ -1,4 +1,8 @@
class Family < ApplicationRecord
+ has_many :financekit_items, dependent: :destroy
+ has_many :financekit_account_lineages, dependent: :destroy
+ has_many :financekit_conflicts, dependent: :destroy
+
include FioConnectable
include Syncable, AutoTransferMatchable, Subscribeable, VectorSearchable
include PlaidConnectable, SimplefinConnectable, LunchflowConnectable, AkahuConnectable, EnableBankingConnectable
diff --git a/app/models/family/financial_data_reset.rb b/app/models/family/financial_data_reset.rb
index f04f67bb29..da2b13b23d 100644
--- a/app/models/family/financial_data_reset.rb
+++ b/app/models/family/financial_data_reset.rb
@@ -40,6 +40,7 @@ class Family::FinancialDataReset
].freeze
STATUS_COUNT_KEYS = (COUNT_KEYS - %i[syncs]) + %i[plaid_items]
PROVIDER_ITEM_ASSOCIATIONS = %i[
+ financekit_items
binance_items
brex_items
coinbase_items
@@ -160,6 +161,7 @@ class Family::FinancialDataReset
scope(:tags).destroy_all
scope(:merchants).destroy_all
delete_provider_items!
+ family.financekit_account_lineages.destroy_all
scope(:accounts).destroy_all
end
diff --git a/app/models/financekit.rb b/app/models/financekit.rb
new file mode 100644
index 0000000000..5ee69c9b8a
--- /dev/null
+++ b/app/models/financekit.rb
@@ -0,0 +1,36 @@
+module Financekit
+ VERSION = 2
+ MAX_BYTES = 1_048_576
+ MAX_RECORDS = 500
+ MAX_ACCOUNTS = 20
+ MAX_QUEUED = 100
+ MAX_ATTEMPTS = 5
+ TOKEN_BYTES = 32
+
+ class Error < StandardError
+ attr_reader :code, :status
+
+ def initialize(code, status = 422)
+ @code = code
+ @status = status
+ super(code)
+ end
+ end
+
+ def self.require!(condition, code = "invalid_payload", status = 422)
+ raise Error.new(code, status) unless condition
+ end
+
+ def self.enabled?(family)
+ ENV["FINANCEKIT_ENABLED"] == "true" &&
+ ENV.fetch("FINANCEKIT_FAMILY_IDS", "").split(",").map(&:strip).include?(family.id)
+ end
+
+ def self.issue_credential
+ SecureRandom.urlsafe_base64(TOKEN_BYTES, false)
+ end
+
+ def self.credential_digest(credential)
+ Digest::SHA256.hexdigest(credential.to_s)
+ end
+end
diff --git a/app/models/financekit/account_mapping.rb b/app/models/financekit/account_mapping.rb
new file mode 100644
index 0000000000..a05be2f451
--- /dev/null
+++ b/app/models/financekit/account_mapping.rb
@@ -0,0 +1,109 @@
+class Financekit::AccountMapping
+ TYPES = { "Depository" => Depository, "CreditCard" => CreditCard }.freeze
+
+ def initialize(item, source_id, input)
+ @item = item
+ @source_id = source_id
+ @input = input
+ end
+
+ def apply!
+ validate!
+ @item.family.with_lock do
+ @item.lock!
+ Financekit.require!(%w[pending_mapping repair_required].include?(@item.status), "mapping_closed", 409)
+ Financekit.require!(@item.consented_source_ids.any? { |id| id.casecmp?(@source_id) },
+ "account_not_consented", 403)
+ existing = @item.financekit_accounts.find_by(source_id: @source_id)
+ return replay!(existing) if existing
+
+ Financekit.require!(@input["expected_version"] == 0, "mapping_conflict", 409)
+ account, lineage = resolve_account_and_lineage!
+ validate_canonical!(account)
+ # One enrollment may not publish two Wallet accounts into the same
+ # canonical account. Without this the unique index raises RecordNotUnique,
+ # which no handler in the FinanceKit stack translates.
+ Financekit.require!([email protected]_accounts.exists?(financekit_account_lineage_id: lineage.id),
+ "lineage_account_conflict", 409)
+ version = lineage.financekit_accounts.maximum(:mapping_version).to_i + 1
+ @item.financekit_accounts.create!(financekit_account_lineage: lineage, source_id: @source_id,
+ mapping_version: version, mapping_digest: mapping_digest,
+ name: @input["name"], institution_name: @input["institution_name"], currency: @input["currency"],
+ accountable_type: @input["accountable_type"], subtype: @input["subtype"],
+ ledger_timezone: @input["ledger_timezone"])
+ end
+ rescue ActiveRecord::RecordNotUnique
+ raise Financekit::Error.new("mapping_conflict", 409)
+ rescue Money::Currency::UnknownCurrencyError
+ raise Financekit::Error.new("invalid_currency")
+ end
+
+ private
+
+ def validate!
+ Financekit::Payload.uuid!(@source_id)
+ Financekit::Payload.shape!(@input,
+ %w[expected_version action name institution_name currency accountable_type subtype ledger_timezone],
+ %w[account_id lineage_id booked_balance observed_at])
+ Financekit::Payload.text!(@input["name"])
+ Financekit::Payload.text!(@input["institution_name"])
+ Financekit.require!(%w[create link].include?(@input["action"]))
+ type = TYPES[@input["accountable_type"]]
+ Financekit.require!(type && type::SUBTYPES.key?(@input["subtype"]), "confirmed_subtype_required")
+ Financekit.require!(Money::Currency.new(@input["currency"]).iso_code == @input["currency"])
+ Financekit.require!(TZInfo::Timezone.all_identifiers.include?(@input["ledger_timezone"]), "invalid_timezone")
+ Financekit.require!(@input["expected_version"].is_a?(Integer))
+ end
+
+ def replay!(existing)
+ Financekit.require!(existing.mapping_digest == mapping_digest &&
+ [ 0, existing.mapping_version, existing.mapping_version - 1 ].include?(@input["expected_version"]),
+ "mapping_conflict", 409)
+ existing
+ end
+
+ def resolve_account_and_lineage!
+ return link_account_and_lineage! if @input["action"] == "link"
+
+ Financekit.require!([email protected]?("account_id"))
+ prior = FinancekitAccount.joins(:financekit_item)
+ .where(source_id: @source_id, financekit_items: { family_id: @item.family_id, user_id: @item.user_id })
+ .includes(financekit_account_lineage: :account).order(created_at: :desc).first
+ return [ prior.account, prior.financekit_account_lineage ] if prior&.account
+
+ Financekit::Payload.money!(@input.fetch("booked_balance"))
+ Financekit.require!(@input["booked_balance"]["currency"] == @input["currency"], "currency_mismatch")
+ Financekit.require!(Financekit::Payload.timestamp!(@input.fetch("observed_at")) <= Time.current + 5.minutes)
+ type = TYPES.fetch(@input["accountable_type"])
+ account = @item.family.accounts.create!(owner: @item.user, name: @input["name"], currency: @input["currency"],
+ balance: Financekit::Mapping.balance(@input["booked_balance"], @input["accountable_type"]),
+ accountable: type.new(subtype: @input["subtype"]), status: "active")
+ [ account, @item.family.financekit_account_lineages.create!(account: account) ]
+ end
+
+ def link_account_and_lineage!
+ Financekit.require!([email protected]?("booked_balance") && [email protected]?("observed_at"))
+ account = @item.family.accounts.writable_by(@item.user).find(@input.fetch("account_id"))
+ lineage = if @input["lineage_id"]
+ @item.family.financekit_account_lineages.find(@input["lineage_id"])
+ else
+ @item.family.financekit_account_lineages.find_by(account: account)
+ end
+ Financekit.require!(!lineage || lineage.account_id == account.id, "lineage_account_conflict", 409)
+ lineage ||= @item.family.financekit_account_lineages.create!(account: account)
+ [ account, lineage ]
+ end
+
+ def validate_canonical!(account)
+ Financekit.require!(account.currency == @input["currency"] && account.accountable_type == @input["accountable_type"] &&
+ account.accountable.subtype == @input["subtype"], "account_type_conflict", 409)
+ provider = account.account_providers.first
+ current_lineage = @item.family.financekit_account_lineages.find_by(account: account)
+ Financekit.require!(!provider || provider.provider == current_lineage, "account_already_supplied", 409)
+ end
+
+ def mapping_digest
+ @mapping_digest ||= Digest::SHA256.hexdigest(
+ Financekit::Enrollment.canonical(@input.except("expected_version")))
+ end
+end
diff --git a/app/models/financekit/downstream.rb b/app/models/financekit/downstream.rb
new file mode 100644
index 0000000000..9619d9778b
--- /dev/null
+++ b/app/models/financekit/downstream.rb
@@ -0,0 +1,24 @@
+class Financekit::Downstream
+ def initialize(batch)
+ @batch = batch
+ end
+
+ def perform!
+ return if @batch.downstream_completed_at?
+
+ item = @batch.financekit_item
+ item.selected_accounts.includes(financekit_account_lineage: :account).find_each do |mapping|
+ mapping.account&.sync_later
+ end
+ item.family.auto_match_transfers!
+ item.family.rules.where(active: true).find_each(&:apply_later)
+ completed_at = Time.current
+ @batch.update!(downstream_completed_at: completed_at)
+ item.update!(last_downstream_at: completed_at)
+ rescue StandardError
+ DebugLogEntry.capture(category: "provider_sync", level: "error",
+ message: "FinanceKit downstream scheduling failed", source: self.class.name,
+ provider_key: "financekit", family: @batch.financekit_item.family,
+ metadata: { batch_id: @batch.batch_id })
+ end
+end
diff --git a/app/models/financekit/enrollment.rb b/app/models/financekit/enrollment.rb
new file mode 100644
index 0000000000..7ccf2a4459
--- /dev/null
+++ b/app/models/financekit/enrollment.rb
@@ -0,0 +1,58 @@
+class Financekit::Enrollment
+ Result = Data.define(:item, :created)
+
+ def self.validate_consent!(consent)
+ Financekit::Payload.shape!(consent,
+ %w[version granted_at selected_source_account_ids upload_authorized family_visibility_acknowledged remote_processing_acknowledged])
+ Financekit.require!(consent["version"] == 1 && consent["upload_authorized"] == true &&
+ consent["family_visibility_acknowledged"] == true && consent["remote_processing_acknowledged"] == true,
+ "consent_required")
+ Financekit::Payload.timestamp!(consent["granted_at"])
+ ids = consent["selected_source_account_ids"]
+ Financekit.require!(ids.is_a?(Array) && ids.size.between?(1, Financekit::MAX_ACCOUNTS) &&
+ ids.map { |id| id.to_s.downcase }.uniq.size == ids.size)
+ ids.each { |id| Financekit::Payload.uuid!(id) }
+ end
+
+ def self.create!(user, input)
+ Financekit::Payload.shape!(input, %w[enrollment_id consent protocol_version], %w[replaces_connection_id])
+ Financekit.require!(input["protocol_version"] == Financekit::VERSION, "unsupported_protocol", 400)
+ Financekit::Payload.uuid!(input["enrollment_id"])
+ validate_consent!(input["consent"])
+ digest = Digest::SHA256.hexdigest(canonical(input))
+
+ result = nil
+ user.family.with_lock do
+ existing = user.family.financekit_items.find_by(enrollment_id: input["enrollment_id"])
+ if existing
+ Financekit.require!(existing.enrollment_digest == digest && existing.user_id == user.id,
+ "enrollment_conflict", 409)
+ result = Result.new(item: existing, created: false)
+ next
+ end
+
+ Financekit.require!(user.family.financekit_items.where(status: %w[pending_mapping active repair_required]).count < 20,
+ "connection_limit", 429)
+ replacement = if input["replaces_connection_id"]
+ user.family.financekit_items.where(user: user).find(input["replaces_connection_id"])
+ end
+ generation = replacement ? replacement.generation + 1 : 1
+ item = user.family.financekit_items.create!(user: user, enrollment_id: input["enrollment_id"],
+ publisher_id: SecureRandom.uuid, generation: generation, enrollment_digest: digest,
+ replaces_financekit_item: replacement, consent: input["consent"].merge("recorded_at" => Time.current.iso8601))
+ result = Result.new(item: item, created: true)
+ end
+ result
+ end
+
+ def self.canonical(value)
+ JSON.generate(case value
+ when Hash
+ value.keys.sort.to_h { |key| [ key, JSON.parse(canonical(value[key])) ] }
+ when Array
+ value.map { |entry| JSON.parse(canonical(entry)) }
+ else
+ value
+ end)
+ end
+end
diff --git a/app/models/financekit/mapping.rb b/app/models/financekit/mapping.rb
new file mode 100644
index 0000000000..7a16943dbe
--- /dev/null
+++ b/app/models/financekit/mapping.rb
@@ -0,0 +1,18 @@
+class Financekit::Mapping
+ def self.transaction_amount(record)
+ amount = Financekit::Payload.money!(record.fetch("amount"))
+ record.fetch("amount").fetch("direction") == "credit" ? -amount : amount
+ end
+
+ def self.balance(record, accountable_type)
+ money = record.key?("money") ? record.fetch("money") : record
+ amount = Financekit::Payload.money!(money)
+ positive = accountable_type == "CreditCard" ? "debit" : "credit"
+ money.fetch("direction") == positive ? amount : -amount
+ end
+
+ def self.ledger_date(record, timezone)
+ timestamp = Financekit::Payload.timestamp!(record["posted_at"] || record.fetch("transacted_at"))
+ timestamp.in_time_zone(timezone).to_date
+ end
+end
diff --git a/app/models/financekit/payload.rb b/app/models/financekit/payload.rb
new file mode 100644
index 0000000000..f9af5c2afb
--- /dev/null
+++ b/app/models/financekit/payload.rb
@@ -0,0 +1,182 @@
+class Financekit::Payload
+ STATUSES = %w[authorized pending booked rejected memo unknown].freeze
+ EVENT_KINDS = %w[account_upsert account_unavailable balance_upsert transaction_upsert transaction_tombstone].freeze
+ UUID = /\A[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\z/i
+ DIGEST = /\A[0-9a-f]{64}\z/
+ DECIMAL = /\A(?:0|[1-9][0-9]{0,14})(?:\.[0-9]{1,4})?\z/
+ EXCHANGE_RATE = /\A(?:0|[1-9][0-9]{0,17})(?:\.[0-9]{1,18})?\z/
+
+ class << self
+ def uuid!(value)
+ Financekit.require!(value.is_a?(String) && UUID.match?(value))
+ value
+ end
+
+ def timestamp!(value)
+ Financekit.require!(value.is_a?(String) && /(?:Z|[+-]\d{2}:\d{2})\z/.match?(value))
+ Time.iso8601(value)
+ rescue ArgumentError
+ raise Financekit::Error.new("invalid_timestamp")
+ end
+
+ def money!(record)
+ shape!(record, %w[amount currency direction])
+ Financekit.require!(record["amount"].is_a?(String) && DECIMAL.match?(record["amount"]))
+ Financekit.require!(record["currency"].is_a?(String) && Money::Currency.new(record["currency"]).iso_code == record["currency"])
+ Financekit.require!(%w[credit debit].include?(record["direction"]))
+ BigDecimal(record["amount"])
+ rescue Money::Currency::UnknownCurrencyError
+ raise Financekit::Error.new("invalid_currency")
+ end
+
+ def shape!(record, required, optional = [])
+ Financekit.require!(record.is_a?(Hash) && (required - record.keys).empty? &&
+ (record.keys - required - optional).empty?)
+ end
+
+ def text!(value, limit = 255, allow_empty: false)
+ Financekit.require!(value.is_a?(String) && (allow_empty || value.present?) && value.length <= limit)
+ end
+
+ def validate_batch!(data, item)
+ shape!(data, %w[protocol_version connection_id publisher_id generation stream_id batch_id sequence capture_id
+ chunk_index chunk_count capture_mode snapshot_complete captured_at selected_source_account_ids events],
+ %w[predecessor_digest])
+ validate_stream!(data, item)
+ capture = timestamp!(data["captured_at"])
+ Financekit.require!(capture <= Time.current + 5.minutes, "future_capture")
+ Financekit.require!(%w[snapshot delta].include?(data["capture_mode"]))
+ Financekit.require!([ true, false ].include?(data["snapshot_complete"]))
+ Financekit.require!(data["snapshot_complete"] == false || data["capture_mode"] == "snapshot")
+ Financekit.require!(data["chunk_index"].is_a?(Integer) && data["chunk_count"].is_a?(Integer) &&
+ data["chunk_index"].between?(0, data["chunk_count"] - 1))
+ Financekit.require!(data["chunk_count"] <= Financekit::MAX_QUEUED, "capture_limit", 413)
+ ids = data["selected_source_account_ids"]
+ normalized_ids = ids.is_a?(Array) ? ids.map { |id| id.to_s.downcase } : []
+ Financekit.require!(ids.is_a?(Array) && normalized_ids.uniq.size == ids.size &&
+ normalized_ids.sort == item.consented_source_ids.map(&:downcase).sort, "scope_conflict", 409)
+ ids.each { |id| uuid!(id) }
+ Financekit.require!(data["events"].is_a?(Array) && data["events"].size <= Financekit::MAX_RECORDS,
+ "record_limit", 413)
+
+ mappings = item.selected_accounts.includes(:financekit_account_lineage).index_by { |mapping| mapping.source_id.downcase }
+ seen = Set.new
+ data["events"].each { |event| validate_event!(event, mappings, seen, capture) }
+ data
+ end
+
+ private
+
+ def validate_stream!(data, item)
+ Financekit.require!(data["protocol_version"] == Financekit::VERSION, "unsupported_protocol", 400)
+ %w[connection_id publisher_id stream_id batch_id capture_id].each { |key| uuid!(data[key]) }
+ Financekit.require!(data["connection_id"].casecmp?(item.id) && data["publisher_id"].casecmp?(item.publisher_id) &&
+ data["stream_id"].casecmp?(item.stream_id), "publisher_conflict", 409)
+ Financekit.require!(data["generation"] == item.generation, "generation_conflict", 409)
+ Financekit.require!(data["sequence"].is_a?(Integer) && data["sequence"].between?(1, 9_007_199_254_740_991))
+ predecessor = data["predecessor_digest"]
+ Financekit.require!(predecessor.nil? || (predecessor.is_a?(String) && DIGEST.match?(predecessor)))
+ Financekit.require!((data["sequence"] == 1) == predecessor.nil?, "invalid_predecessor")
+ end
+
+ def validate_event!(event, mappings, seen, capture)
+ Financekit.require!(event.is_a?(Hash) && EVENT_KINDS.include?(event["kind"]))
+ case event["kind"]
+ when "account_upsert"
+ shape!(event, %w[kind account])
+ validate_account!(event.fetch("account"), mappings, seen)
+ when "account_unavailable"
+ shape!(event, %w[kind source_account_id lineage_id mapping_version])
+ validate_unavailable!(event, mappings, seen)
+ when "balance_upsert"
+ shape!(event, %w[kind balance])
+ validate_balance!(event.fetch("balance"), mappings, seen, capture)
+ when "transaction_upsert"
+ shape!(event, %w[kind transaction])
+ validate_transaction!(event.fetch("transaction"), mappings, seen, capture)
+ when "transaction_tombstone"
+ shape!(event, %w[kind tombstone])
+ validate_tombstone!(event.fetch("tombstone"), mappings, seen)
+ end
+ end
+
+ def validate_account!(record, mappings, seen)
+ shape!(record, %w[source_id lineage_id mapping_version display_name institution_name currency kind],
+ %w[account_description opening_date])
+ mapping = mapping!(record, mappings, "source_id")
+ Financekit.require!(record["currency"] == mapping.currency, "currency_mismatch")
+ expected_kind = mapping.accountable_type == "CreditCard" ? "liability" : "asset"
+ Financekit.require!(record["kind"] == expected_kind, "account_type_conflict", 409)
+ text!(record["display_name"])
+ text!(record["institution_name"])
+ text!(record["account_description"], 1000, allow_empty: true) if record.key?("account_description")
+ timestamp!(record["opening_date"]) if record.key?("opening_date")
+ unique!(seen, [ "account", mapping.id ])
+ end
+
+ def validate_unavailable!(event, mappings, seen)
+ mapping = mapping!(event, mappings, "source_account_id")
+ unique!(seen, [ "account_unavailable", mapping.id ])
+ end
+
+ def validate_balance!(record, mappings, seen, capture)
+ shape!(record, %w[source_id source_account_id lineage_id mapping_version kind observed_at money])
+ uuid!(record["source_id"])
+ mapping = mapping!(record, mappings, "source_account_id")
+ Financekit.require!(%w[available booked].include?(record["kind"]))
+ Financekit.require!(timestamp!(record["observed_at"]) <= capture)
+ money!(record["money"])
+ Financekit.require!(record["money"]["currency"] == mapping.currency, "currency_mismatch")
+ unique!(seen, [ "balance", mapping.financekit_account_lineage_id, record["source_id"].downcase,
+ record["kind"], record["observed_at"] ])
+ end
+
+ def validate_transaction!(record, mappings, seen, capture)
+ shape!(record, %w[source_id source_account_id lineage_id mapping_version amount transaction_description
+ original_transaction_description transaction_type status transacted_at],
+ %w[foreign_amount foreign_exchange_rate merchant_name merchant_category_code posted_at])
+ uuid!(record["source_id"])
+ mapping = mapping!(record, mappings, "source_account_id")
+ money!(record["amount"])
+ Financekit.require!(record["amount"]["currency"] == mapping.currency, "currency_mismatch")
+ money!(record["foreign_amount"]) if record.key?("foreign_amount")
+ if record.key?("foreign_exchange_rate")
+ Financekit.require!(record["foreign_exchange_rate"].is_a?(String) && EXCHANGE_RATE.match?(record["foreign_exchange_rate"]))
+ end
+ Financekit.require!(STATUSES.include?(record["status"]))
+ text!(record["transaction_type"], 100)
+ text!(record["transaction_description"], 1000, allow_empty: true)
+ text!(record["original_transaction_description"], 1000, allow_empty: true)
+ text!(record["merchant_name"]) if record.key?("merchant_name")
+ if record.key?("merchant_category_code")
+ Financekit.require!(record["merchant_category_code"].is_a?(Integer) && record["merchant_category_code"].between?(-32_768, 32_767))
+ end
+ Financekit.require!(timestamp!(record["transacted_at"]) <= capture)
+ Financekit.require!(record.key?("posted_at")) if record["status"] == "booked"
+ Financekit.require!(timestamp!(record["posted_at"]) <= capture) if record.key?("posted_at")
+ unique!(seen, [ "transaction", mapping.financekit_account_lineage_id, record["source_id"].downcase ])
+ end
+
+ def validate_tombstone!(record, mappings, seen)
+ shape!(record, %w[source_id source_account_id lineage_id mapping_version])
+ uuid!(record["source_id"])
+ mapping = mapping!(record, mappings, "source_account_id")
+ unique!(seen, [ "transaction", mapping.financekit_account_lineage_id, record["source_id"].downcase ])
+ end
+
+ def mapping!(record, mappings, key)
+ uuid!(record[key])
+ uuid!(record["lineage_id"])
+ mapping = mappings[record[key].downcase]
+ Financekit.require!(mapping && record["mapping_version"].is_a?(Integer) &&
+ mapping.mapping_version == record["mapping_version"] &&
+ mapping.financekit_account_lineage_id.casecmp?(record["lineage_id"]), "mapping_conflict", 409)
+ mapping
+ end
+
+ def unique!(seen, identity)
+ Financekit.require!(!seen.include?(identity), "duplicate_record")
+ seen << identity
+ end
+ end
+end
diff --git a/app/models/financekit/processor.rb b/app/models/financekit/processor.rb
new file mode 100644
index 0000000000..913a1643e7
--- /dev/null
+++ b/app/models/financekit/processor.rb
@@ -0,0 +1,326 @@
+class Financekit::Processor
+ def initialize(item)
+ @item = item
+ end
+
+ def apply_next!
+ batch = nil
+ @item.with_lock do
+ @item.require_publisher!
+ batch = @item.financekit_batches.find_by(generation: @item.generation,
+ stream_id: @item.stream_id, sequence: @item.next_sequence)
+ return false unless batch && batch.status == "accepted" && (!batch.retry_at || batch.retry_at <= Time.current)
+ capture = @item.financekit_batches.where(generation: @item.generation, capture_id: batch.capture_id).order(:chunk_index).to_a
+ return false unless capture.size == batch.chunk_count && capture.map(&:chunk_index) == (0...batch.chunk_count).to_a &&
+ capture.all? { |part| part.status == "accepted" && (!part.retry_at || part.retry_at <= Time.current) }
+
+ Financekit.require!([email protected]_captured_at || batch.captured_at >= @item.last_captured_at,
+ "stale_capture", 409)
+ counts = { "upserted" => 0, "retracted" => 0, "review_required" => 0,
+ "source_only" => 0, "settled" => 0, "balances" => 0, "accounts" => 0 }
+ mappings = @item.selected_accounts.includes(financekit_account_lineage: :account)
+ .index_by { |mapping| mapping.source_id.downcase }
+ predecessor_digest = @item.predecessor_digest
+ capture.each do |part|
+ batch = part
+ Financekit.require!(part.predecessor_digest == predecessor_digest, "predecessor_conflict", 409)
+ data = JSON.parse(part.payload)
+ Financekit::Payload.validate_batch!(data, @item)
+ part.update!(status: "processing")
+ data["events"].each { |event| apply_event!(event, mappings, part, counts) }
+ predecessor_digest = part.payload_digest
+ end
+ applied_at = Time.current
+ sync = @item.syncs.create!(status: "completed", completed_at: applied_at,
+ sync_stats: { "financekit" => counts, "total_accounts" => mappings.size, "linked_accounts" => mappings.size })
+ capture.each { |part| part.update!(status: "applied", applied_at: applied_at, counts: counts, sync: sync,
+ error_code: nil, retry_at: nil) }
+ last = capture.last
+ @item.update!(next_sequence: last.sequence + 1, predecessor_digest: last.payload_digest,
+ last_imported_at: applied_at, last_captured_at: last.captured_at)
+ batch = last
+ end
+ Financekit::Downstream.new(batch).perform!
+ true
+ rescue ActiveRecord::RecordInvalid => error
+ # Retryable. RecordInvalid covers ordinary races — a concurrent balance
+ # observation or conflict insert, an entry validation a later attempt
+ # clears — as well as genuinely poisoned input. Fencing on the first
+ # occurrence sends the publisher to repair_required and clears the upload
+ # credential, which only a foreground, OAuth-authenticated repair can
+ # reissue: no background wake can recover from it. Let the bounded
+ # MAX_ATTEMPTS backoff decide instead. A transient race clears itself; a
+ # persistent one still ends in the same fenced state, just not on a single
+ # unlucky save.
+ Rails.error.report(error, handled: true,
+ context: { financekit_item_id: @item.id, batch_id: batch&.batch_id })
+ fail_batch!(batch, "import_validation", permanent: false)
+ false
+ rescue Financekit::Error, JSON::ParserError => error
+ # Not retryable. The stored payload is immutable, so a protocol violation
+ # or bytes that no longer parse give every later attempt the same input.
+ fail_batch!(batch, error.is_a?(Financekit::Error) ? error.code : "import_validation", permanent: true)
+ false
+ rescue StandardError => error
+ Rails.error.report(error, handled: true, context: { financekit_item_id: @item.id, batch_id: batch&.batch_id })
+ fail_batch!(batch, "processing_error", permanent: false)
+ false
+ end
+
+ private
+
+ def apply_event!(event, mappings, batch, counts)
+ case event.fetch("kind")
+ when "account_upsert"
+ import_account!(mappings.fetch(event.fetch("account").fetch("source_id").downcase), event.fetch("account"), counts)
+ when "account_unavailable"
+ mappings.fetch(event.fetch("source_account_id").downcase).update!(unavailable_at: Time.current)
+ counts["accounts"] += 1
+ when "balance_upsert"
+ record = event.fetch("balance")
+ import_balance!(mappings.fetch(record.fetch("source_account_id").downcase), record, counts)
+ when "transaction_upsert"
+ record = event.fetch("transaction")
+ import_transaction!(mappings.fetch(record.fetch("source_account_id").downcase), record, batch, counts)
+ when "transaction_tombstone"
+ record = event.fetch("tombstone")
+ retract!(mappings.fetch(record.fetch("source_account_id").downcase), record, batch, counts)
+ end
+ end
+
+ def import_account!(mapping, record, counts)
+ mapping.update!(name: record["display_name"], institution_name: record["institution_name"], unavailable_at: nil)
+ counts["accounts"] += 1
+ end
+
+ def import_balance!(mapping, record, counts)
+ observed_at = Financekit::Payload.timestamp!(record["observed_at"])
+ money = record.fetch("money")
+ observation = mapping.financekit_balance_observations.find_or_create_by!(source_id: record["source_id"],
+ kind: record["kind"], observed_at: observed_at) do |balance|
+ balance.financekit_account = mapping
+ balance.amount = Financekit::Payload.money!(money)
+ balance.currency = money["currency"]
+ balance.direction = money["direction"]
+ end
+ Financekit.require!(observation.amount == Financekit::Payload.money!(money) &&
+ observation.currency == money["currency"] && observation.direction == money["direction"],
+ "balance_observation_conflict", 409)
+ counts["balances"] += 1 if observation.previously_new_record?
+ return unless record["kind"] == "booked"
+
+ latest = mapping.financekit_balance_observations.where(kind: "booked").maximum(:observed_at)
+ return unless latest == observed_at
+
+ account = mapping.account
+ account.with_lock do
+ Account::ProviderImportAdapter.new(account).update_balance(
+ balance: Financekit::Mapping.balance(record, mapping.accountable_type), source: "financekit")
+ account.update!(status: "active") if account.draft?
+ end
+ end
+
+ def import_transaction!(mapping, record, batch, counts)
+ identity = transaction_identity_for(mapping, record["source_id"])
+ existed = identity.persisted?
+ identity.assign_attributes(financekit_account: mapping, generation: batch.generation,
+ sequence: batch.sequence, status: record["status"], raw_payload: record)
+
+ # "Keep Sure" is a durable decision about this source identity, not a
+ # one-off dismissal. The publisher re-sends the same record on every
+ # capture that covers it, so without this the resolved conflict reopens
+ # on the next batch and the family is asked the same question forever.
+ if settled_by_family?(identity)
+ identity.review_required = false
+ identity.save!
+ counts["settled"] += 1
+ return
+ end
+
+ # An unanswered review keeps the record out of the ledger. Importing it
+ # on the next capture would decide the question the family was asked.
+ if existed && identity.review_required?
+ settle_edited_pending_entry!(identity.entry, record)
+ identity.save!
+ counts["review_required"] += 1
+ return
+ end
+
+ if !existed && @item.replaces_financekit_item_id.present? &&
+ mapping.financekit_account_lineage.financekit_transactions.exists?
+ identity.review_required = true
+ identity.save!
+ create_conflict!(mapping, identity, "replacement_identity")
+ counts["review_required"] += 1
+ return
+ end
+ if identity.tombstoned_at || (existed && identity.entry_id.nil? && identity.ledger_imported)
+ identity.update!(review_required: true)
+ create_conflict!(mapping, identity, "source_reappeared")
+ counts["review_required"] += 1
+ return
+ end
+ if %w[rejected memo unknown].include?(record["status"])
+ remove_source_only_entry!(mapping, identity, counts) if identity.entry
+ identity.ledger_imported = false unless identity.review_required?
+ identity.save!
+ counts["source_only"] += 1
+ return
+ end
+
+ account = mapping.account
+ account.with_lock do
+ entry = identity.entry
+ entry&.lock!
+ if entry && protected_entry?(entry)
+ settle_edited_pending_entry!(entry, record)
+ identity.update!(review_required: true)
+ create_conflict!(mapping, identity, "protected_entry")
+ counts["review_required"] += 1
+ return
+ end
+
+ adapter = Account::ProviderImportAdapter.new(account)
+ entry = adapter.import_transaction(external_id: transaction_external_id(mapping, record.fetch("source_id")),
+ amount: Financekit::Mapping.transaction_amount(record), currency: record.dig("amount", "currency"),
+ date: Financekit::Mapping.ledger_date(record, mapping.ledger_timezone),
+ name: record["merchant_name"].presence || record["transaction_description"].presence || "Wallet transaction",
+ source: "financekit", allow_heuristic_matching: false,
+ extra: { "financekit" => record.merge("pending" => %w[authorized pending].include?(record["status"])) })
+ identity.update!(entry: entry, ledger_imported: true, review_required: adapter.skipped_entries.any?)
+ create_conflict!(mapping, identity, "protected_entry") if identity.review_required?
+ counts[identity.review_required? ? "review_required" : "upserted"] += 1
+ end
+ end
+
+ def retract!(mapping, record, batch, counts)
+ identity = transaction_identity_for(mapping, record["source_id"])
+ identity.assign_attributes(financekit_account: mapping, generation: batch.generation, sequence: batch.sequence,
+ status: "deleted", tombstoned_at: Time.current, raw_payload: nil)
+ entry = identity.entry
+ if entry && settled_by_family?(identity)
+ # The family already chose to keep Sure's entry for this identity. The
+ # tombstone is still recorded so the source cannot resurrect it, but the
+ # protected entry stays and the answered conflict is not reopened.
+ identity.review_required = false
+ counts["settled"] += 1
+ elsif entry
+ Entry.transaction do
+ entry.lock!
+ if protected_entry?(entry) || entry.source != "financekit" || entry.account_id != mapping.account.id
+ identity.review_required = true
+ create_conflict!(mapping, identity, "protected_tombstone")
+ counts["review_required"] += 1
+ else
+ entry.destroy!
+ identity.entry = nil
+ counts["retracted"] += 1
+ end
+ end
+ end
+ identity.save!
+ DebugLogEntry.capture(category: "provider_sync", level: "info", message: "FinanceKit tombstone processed",
+ source: self.class.name, provider_key: "financekit", family: @item.family,
+ metadata: { batch_id: batch.batch_id, source_identity_id: identity.id,
+ review_required: identity.review_required })
+ end
+
+ # A conflict the family resolved with "keep_sure" settles that source
+ # identity for good: Sure's version wins and the publisher's copy of the
+ # record is recorded without touching the ledger or raising again.
+ def settled_by_family?(identity)
+ identity.persisted? && settled_identity_ids.include?(identity.id)
+ end
+
+ # Read once per apply rather than per record: a capture carries up to
+ # Financekit::MAX_RECORDS events and this runs inside the item row lock.
+ # Scoped to the family, not the connection, so a decision survives device
+ # replacement the same way the source identity behind it does. Conflicts
+ # opened during this apply are "open", so the set cannot change under us.
+ def settled_identity_ids
+ @settled_identity_ids ||= FinancekitConflict
+ .where(family_id: @item.family_id, resolution: "keep_sure")
+ .where.not(financekit_transaction_id: nil)
+ .distinct.pluck(:financekit_transaction_id).to_set
+ end
+
+ def transaction_identity_for(mapping, source_id)
+ mapping.financekit_transactions.find_or_initialize_by(source_id: source_id).tap do |identity|
+ identity.financekit_account = mapping
+ end
+ end
+
+ def transaction_external_id(mapping, source_id)
+ "financekit:#{mapping.financekit_account_lineage_id}:#{source_id.downcase}"
+ end
+
+ def remove_source_only_entry!(mapping, identity, counts)
+ entry = identity.entry
+ return unless entry
+
+ Entry.transaction do
+ entry.lock!
+ if protected_entry?(entry) || entry.source != "financekit" || entry.account_id != mapping.account.id
+ identity.review_required = true
+ create_conflict!(mapping, identity, "protected_source_update")
+ counts["review_required"] += 1
+ else
+ entry.destroy!
+ identity.entry = nil
+ end
+ end
+ end
+
+ def protected_entry?(entry)
+ entry.protected_from_sync? || entry.transaction.transfer.present? || entry.transaction.transfer_id.present? || entry.reconciled_at.present? ||
+ entry.split_parent? || entry.split_child? || entry.locked_attributes.present? ||
+ entry.transaction.locked_attributes.present?
+ end
+
+ # Preserve the shared importer's pending-to-booked exception for user edits,
+ # without changing the edited ledger fields or bypassing an import lock.
+ def settle_edited_pending_entry!(entry, record)
+ return unless entry && record["status"] == "booked"
+
+ Entry.transaction do
+ entry.lock!
+ return unless entry.user_modified? && !entry.excluded? && !entry.import_locked?
+
+ transaction = entry.transaction
+ if transaction.extra.dig("financekit", "pending")
+ transaction.update!(extra: transaction.extra.deep_merge("financekit" => { "pending" => false }))
+ end
+ end
+ end
+
+ def create_conflict!(mapping, identity, kind)
+ @item.financekit_conflicts.find_or_create_by!(financekit_transaction: identity, kind: kind, status: "open") do |conflict|
+ conflict.family = @item.family
+ conflict.financekit_account_lineage = mapping.financekit_account_lineage
+ conflict.details = { "source_id" => identity.source_id }
+ end
+ end
+
+ def fail_batch!(batch, code, permanent:)
+ return unless batch
+
+ @item.with_lock do
+ batch.reload
+ return unless batch.status.in?(%w[accepted processing]) && batch.generation == @item.generation
+
+ attempts = batch.attempts + 1
+ if permanent || attempts >= Financekit::MAX_ATTEMPTS
+ batch.update!(attempts: attempts, status: "failed", error_code: code, retry_at: nil)
+ @item.update!(status: "repair_required", repair_reason: code, credential_digest: nil)
+ @item.financekit_batches.where(status: "accepted").where.not(id: batch.id)
+ .update_all(status: "revoked", error_code: "stream_failed", payload: nil, updated_at: Time.current)
+ else
+ batch.update!(attempts: attempts, status: "accepted", error_code: code,
+ retry_at: Time.current + (2**attempts).minutes)
+ end
+ end
+ DebugLogEntry.capture(category: "provider_sync", level: "error", message: "FinanceKit import requires attention",
+ source: self.class.name, provider_key: "financekit", family: @item.family,
+ metadata: { batch_id: batch.batch_id, error_code: code })
+ end
+end
diff --git a/app/models/financekit_account.rb b/app/models/financekit_account.rb
new file mode 100644
index 0000000000..0118697a07
--- /dev/null
+++ b/app/models/financekit_account.rb
@@ -0,0 +1,15 @@
+class FinancekitAccount < ApplicationRecord
+ belongs_to :financekit_item
+ belongs_to :financekit_account_lineage
+ has_one :account, through: :financekit_account_lineage
+
+ delegate :financekit_transactions, :financekit_balance_observations, to: :financekit_account_lineage
+
+ def self.map!(item, source_id, input)
+ Financekit::AccountMapping.new(item, source_id, input).apply!
+ end
+
+ def raw_payload
+ nil
+ end
+end
diff --git a/app/models/financekit_account_lineage.rb b/app/models/financekit_account_lineage.rb
new file mode 100644
index 0000000000..f9518a6f60
--- /dev/null
+++ b/app/models/financekit_account_lineage.rb
@@ -0,0 +1,8 @@
+class FinancekitAccountLineage < ApplicationRecord
+ belongs_to :family
+ belongs_to :account, optional: true
+ has_many :financekit_accounts, dependent: :restrict_with_error
+ has_many :financekit_transactions, dependent: :destroy
+ has_many :financekit_balance_observations, dependent: :destroy
+ has_one :account_provider, as: :provider, dependent: :destroy
+end
diff --git a/app/models/financekit_balance_observation.rb b/app/models/financekit_balance_observation.rb
new file mode 100644
index 0000000000..f30a2ed05a
--- /dev/null
+++ b/app/models/financekit_balance_observation.rb
@@ -0,0 +1,4 @@
+class FinancekitBalanceObservation < ApplicationRecord
+ belongs_to :financekit_account_lineage
+ belongs_to :financekit_account, optional: true
+end
diff --git a/app/models/financekit_batch.rb b/app/models/financekit_batch.rb
new file mode 100644
index 0000000000..47a5b76345
--- /dev/null
+++ b/app/models/financekit_batch.rb
@@ -0,0 +1,80 @@
+class FinancekitBatch < ApplicationRecord
+ belongs_to :financekit_item
+ belongs_to :sync, optional: true
+
+ def self.accept!(item, raw_payload, claimed_digest: nil, idempotency_key: nil)
+ Financekit.require!(raw_payload.is_a?(String) && raw_payload.bytesize <= Financekit::MAX_BYTES,
+ "payload_too_large", 413)
+ digest = Digest::SHA256.hexdigest(raw_payload)
+ Financekit.require!(claimed_digest.blank? || claimed_digest == digest, "payload_digest_mismatch", 409)
+ data = JSON.parse(raw_payload)
+ # validate_batch! proves the shape, but it runs behind the item lock and the
+ # idempotency comparison below already indexes the body by key.
+ Financekit.require!(data.is_a?(Hash))
+ Financekit.require!(idempotency_key.blank? || idempotency_key.casecmp?(data["batch_id"].to_s),
+ "idempotency_key_mismatch", 409)
+
+ batch = nil
+ item.with_lock do
+ item.require_publisher!
+ Financekit::Payload.validate_batch!(data, item)
+ existing = item.financekit_batches.find_by(generation: item.generation, batch_id: data["batch_id"])
+ if existing
+ Financekit.require!(existing.payload_digest == digest && existing.sequence == data["sequence"] &&
+ existing.predecessor_digest == data["predecessor_digest"] && existing.stream_id.casecmp?(data["stream_id"]),
+ "batch_conflict", 409)
+ item.update!(last_device_contact_at: Time.current)
+ batch = existing
+ next
+ end
+
+ Financekit.require!(data["sequence"] >= item.next_sequence &&
+ !item.financekit_batches.exists?(generation: item.generation, stream_id: item.stream_id, sequence: data["sequence"]),
+ "sequence_conflict", 409)
+ capture = item.financekit_batches.where(generation: item.generation, capture_id: data["capture_id"]).order(:chunk_index)
+ if capture.exists?
+ first = capture.first
+ Financekit.require!(first.chunk_count == data["chunk_count"] && first.capture_mode == data["capture_mode"] &&
+ first.captured_at == Financekit::Payload.timestamp!(data["captured_at"]) &&
+ data["chunk_index"] == capture.maximum(:chunk_index) + 1 &&
+ data["sequence"] == capture.maximum(:sequence) + 1, "capture_conflict", 409)
+ else
+ Financekit.require!(data["chunk_index"] == 0, "capture_conflict", 409)
+ incomplete = item.financekit_batches.where(generation: item.generation).where.not(status: %w[applied failed revoked])
+ .group(:capture_id, :chunk_count).having("COUNT(*) < chunk_count").exists?
+ Financekit.require!(!incomplete, "capture_incomplete", 409)
+ end
+ Financekit.require!(data["sequence"] < item.next_sequence + Financekit::MAX_QUEUED &&
+ item.financekit_batches.where(status: %w[accepted processing]).count < Financekit::MAX_QUEUED,
+ "inbox_full", 429)
+ accepted_at = Time.current
+ batch = item.financekit_batches.create!(batch_id: data["batch_id"], stream_id: data["stream_id"],
+ capture_id: data["capture_id"], generation: data["generation"], sequence: data["sequence"],
+ predecessor_digest: data["predecessor_digest"], payload_digest: digest,
+ chunk_index: data["chunk_index"], chunk_count: data["chunk_count"], capture_mode: data["capture_mode"],
+ snapshot_complete: data["snapshot_complete"], captured_at: Financekit::Payload.timestamp!(data["captured_at"]),
+ accepted_at: accepted_at, payload: raw_payload)
+ item.update!(last_device_contact_at: accepted_at, last_accepted_at: accepted_at)
+ end
+ FinancekitInboxJob.perform_later(item.id) if batch.previously_new_record?
+ batch
+ rescue JSON::ParserError
+ raise Financekit::Error.new("invalid_json", 400)
+ end
+
+ def receipt
+ {
+ connection_id: financekit_item_id,
+ publisher_id: financekit_item.publisher_id,
+ generation: generation,
+ stream_id: stream_id,
+ batch_id: batch_id,
+ sequence: sequence,
+ payload_digest: payload_digest,
+ status: status,
+ accepted_at: accepted_at,
+ applied_at: applied_at,
+ error_code: error_code
+ }
+ end
+end
diff --git a/app/models/financekit_conflict.rb b/app/models/financekit_conflict.rb
new file mode 100644
index 0000000000..d50f879fdb
--- /dev/null
+++ b/app/models/financekit_conflict.rb
@@ -0,0 +1,27 @@
+class FinancekitConflict < ApplicationRecord
+ belongs_to :family
+ belongs_to :financekit_item
+ belongs_to :financekit_account_lineage, optional: true
+ belongs_to :financekit_transaction, optional: true
+ belongs_to :resolved_by, class_name: "User", optional: true
+
+ scope :open, -> { where(status: "open") }
+
+ def resolve!(user:, resolution:)
+ Financekit.require!(%w[keep_sure retry_after_repair].include?(resolution), "invalid_resolution")
+ financekit_item.with_lock do
+ lock!
+ Financekit.require!(status == "open", "conflict_already_resolved", 409)
+ update!(status: "resolved", resolution: resolution, resolved_by: user, resolved_at: Time.current)
+ case resolution
+ when "keep_sure"
+ financekit_transaction&.update!(review_required: false)
+ when "retry_after_repair"
+ financekit_item.mark_repair!("conflict_retry_requested")
+ if financekit_transaction
+ financekit_transaction.update!(review_required: financekit_transaction.financekit_conflicts.open.exists?)
+ end
+ end
+ end
+ end
+end
diff --git a/app/models/financekit_item.rb b/app/models/financekit_item.rb
new file mode 100644
index 0000000000..b681a0a7a6
--- /dev/null
+++ b/app/models/financekit_item.rb
@@ -0,0 +1,163 @@
+class FinancekitItem < ApplicationRecord
+ include Syncable
+
+ before_destroy :release_orphaned_lineage_links
+
+ belongs_to :family
+ belongs_to :user
+ belongs_to :replaces_financekit_item, class_name: "FinancekitItem", optional: true
+ has_many :replacement_financekit_items, class_name: "FinancekitItem",
+ foreign_key: :replaces_financekit_item_id, dependent: :nullify, inverse_of: :replaces_financekit_item
+ has_many :financekit_accounts, dependent: :destroy
+ has_many :financekit_account_lineages, through: :financekit_accounts
+ has_many :financekit_batches, dependent: :destroy
+ has_many :financekit_conflicts, dependent: :destroy
+ has_many :accounts, through: :financekit_account_lineages
+
+ scope :ordered, -> { order(created_at: :desc, id: :desc) }
+ scope :syncable, -> { none }
+
+ def name
+ "Apple Wallet (FinanceKit)"
+ end
+
+ def credentials_configured?
+ status == "active" && credential_digest.present? && stream_id.present?
+ end
+
+ def pending_account_setup?
+ mapped_source_ids = financekit_accounts.pluck(:source_id).map(&:downcase)
+ (consented_source_ids.map(&:downcase) - mapped_source_ids).any?
+ end
+
+ def selected_accounts
+ financekit_accounts.where(source_id: consented_source_ids)
+ end
+
+ def authenticate_credential?(credential)
+ return false if credential_digest.blank? || credential.blank?
+
+ candidate = Financekit.credential_digest(credential)
+ ActiveSupport::SecurityUtils.secure_compare(credential_digest, candidate)
+ end
+
+ def require_publisher!
+ error = status == "repair_required" ? "repair_required" : "connection_revoked"
+ Financekit.require!(status == "active", error, 403)
+ Financekit.require!(Financekit.enabled?(family), "unavailable", 503)
+ user.reload
+ Financekit.require!(user.active? && user.family_id == family_id && user.admin? && user.preview_features_enabled?,
+ "publisher_forbidden", 403)
+ Financekit.require!(!pending_account_setup?, "account_setup_required", 409)
+ permitted_ids = family.accounts.writable_by(user).pluck(:id)
+ Financekit.require!(selected_accounts.includes(financekit_account_lineage: :account).all? do |mapping|
+ mapping.account && permitted_ids.include?(mapping.account.id)
+ end, "account_forbidden", 403)
+ end
+
+ def activate!
+ token = nil
+ family.with_lock do
+ lock!
+ Financekit.require!(%w[pending_mapping repair_required].include?(status), "activation_conflict", 409)
+ Financekit.require!(!pending_account_setup?, "account_setup_required", 409)
+ mappings = selected_accounts.includes(financekit_account_lineage: :account).to_a
+ Financekit.require!(mappings.all?(&:account), "account_setup_required", 409)
+
+ Financekit.require!(!competing_active_writer?(mappings, excluding: [ id, replaces_financekit_item_id ]),
+ "lineage_writer_conflict", 409)
+
+ replaces_financekit_item&.revoke!(release_lineages_except: mappings.map(&:financekit_account_lineage_id))
+ mappings.each do |mapping|
+ lineage = mapping.financekit_account_lineage
+ lineage.create_account_provider!(account: lineage.account) unless lineage.account_provider
+ end
+
+ token = rotate_credential! # pipelock:ignore Credential in URL
+ update!(status: "active", repair_reason: nil, stream_id: SecureRandom.uuid,
+ next_sequence: 1, predecessor_digest: nil)
+ end
+ token
+ end
+
+ def repair!
+ token = nil
+ family.with_lock do
+ lock!
+ Financekit.require!(%w[active repair_required].include?(status), "connection_revoked", 403)
+ Financekit.require!(!pending_account_setup?, "account_setup_required", 409)
+ mappings = selected_accounts.includes(financekit_account_lineage: :account).to_a
+ Financekit.require!(mappings.all?(&:account), "account_setup_required", 409)
+ Financekit.require!(!competing_active_writer?(mappings, excluding: [ id ]),
+ "lineage_writer_conflict", 409)
+ revoke_pending_batches!("generation_replaced")
+ token = rotate_credential! # pipelock:ignore Credential in URL
+ update!(generation: generation + 1, stream_id: SecureRandom.uuid, next_sequence: 1,
+ predecessor_digest: nil, status: "active", repair_reason: nil)
+ end
+ token
+ end
+
+ def renew_credential!
+ with_lock do
+ Financekit.require!(status == "active", "connection_revoked", 403)
+ rotate_credential!
+ end
+ end
+
+ def mark_repair!(reason)
+ with_lock do
+ revoke_pending_batches!(reason)
+ update!(status: "repair_required", repair_reason: reason, credential_digest: nil)
+ end
+ end
+
+ def disconnect!
+ family.with_lock { revoke!(release_lineages_except: []) }
+ end
+
+ def revoke!(release_lineages_except: [])
+ lock!
+ revoke_pending_batches!("connection_revoked")
+ update!(status: "revoked", credential_digest: nil)
+ financekit_account_lineages.distinct.where.not(id: release_lineages_except).find_each do |lineage|
+ release_lineage_link!(lineage)
+ end
+ end
+
+ def rotate_credential!
+ credential = Financekit.issue_credential
+ self.credential_digest = Financekit.credential_digest(credential)
+ save! if persisted? && changed?
+ credential
+ end
+
+ def consented_source_ids
+ consent.fetch("selected_source_account_ids")
+ end
+
+ private
+
+ def competing_active_writer?(mappings, excluding:)
+ FinancekitAccount.joins(:financekit_item)
+ .where(financekit_account_lineage_id: mappings.map(&:financekit_account_lineage_id),
+ financekit_items: { status: "active" })
+ .where.not(financekit_item_id: excluding.compact).exists?
+ end
+
+ def revoke_pending_batches!(code)
+ financekit_batches.where(status: %w[accepted processing failed])
+ .update_all(status: "revoked", error_code: code, payload: nil, updated_at: Time.current)
+ end
+
+ def release_orphaned_lineage_links
+ financekit_account_lineages.distinct.find_each { |lineage| release_lineage_link!(lineage) }
+ end
+
+ def release_lineage_link!(lineage)
+ other_active_writer = FinancekitAccount.joins(:financekit_item)
+ .where(financekit_account_lineage_id: lineage.id, financekit_items: { status: "active" })
+ .where.not(financekit_item_id: id).exists?
+ lineage.account_provider&.destroy! unless other_active_writer
+ end
+end
diff --git a/app/models/financekit_transaction.rb b/app/models/financekit_transaction.rb
new file mode 100644
index 0000000000..34871d51c9
--- /dev/null
+++ b/app/models/financekit_transaction.rb
@@ -0,0 +1,6 @@
+class FinancekitTransaction < ApplicationRecord
+ belongs_to :financekit_account_lineage
+ belongs_to :financekit_account, optional: true
+ belongs_to :entry, optional: true
+ has_many :financekit_conflicts, dependent: :nullify
+end
diff --git a/app/models/provider/financekit_adapter.rb b/app/models/provider/financekit_adapter.rb
new file mode 100644
index 0000000000..331d4233de
--- /dev/null
+++ b/app/models/provider/financekit_adapter.rb
@@ -0,0 +1,26 @@
+class Provider::FinancekitAdapter < Provider::Base
+ include Provider::InstitutionMetadata
+ Provider::Factory.register("FinancekitAccountLineage", self)
+
+ def self.supported_account_types
+ %w[Depository CreditCard]
+ end
+
+ def provider_name
+ "financekit"
+ end
+
+ def item
+ provider_account.financekit_accounts.joins(:financekit_item)
+ .where(financekit_items: { status: %w[active repair_required] })
+ .order(created_at: :desc).first&.financekit_item
+ end
+
+ def metadata
+ return super.merge(delivery: "background_publisher") unless item
+
+ super.merge(delivery: "background_publisher", last_device_contact_at: item.last_device_contact_at,
+ last_accepted_at: item.last_accepted_at, last_imported_at: item.last_imported_at,
+ last_downstream_at: item.last_downstream_at, repair_required: item.status == "repair_required")
+ end
+end
diff --git a/app/models/provider_connection_status.rb b/app/models/provider_connection_status.rb
index c562d46386..06b05333dd 100644
--- a/app/models/provider_connection_status.rb
+++ b/app/models/provider_connection_status.rb
@@ -2,6 +2,7 @@
class ProviderConnectionStatus
PROVIDERS = [
+ { key: "financekit", type: "FinancekitItem", association: :financekit_items, accounts: :financekit_account_lineages },
{ key: "akahu", type: "AkahuItem", association: :akahu_items, accounts: :akahu_accounts },
{ key: "up", type: "UpItem", association: :up_items, accounts: :up_accounts },
{ key: "monobank", type: "MonobankItem", association: :monobank_items, accounts: :monobank_accounts },
@@ -197,6 +198,10 @@ class ProviderConnectionStatus
end
def sync_status_summary
+ if provider[:key] == "financekit"
+ return item.last_imported_at ? "Wallet publisher imported" : "Waiting for Wallet publisher"
+ end
+
stats = latest_completed_sync_stats
counts = accounts_payload
total = stats.fetch("total_accounts", counts[:total_count]).to_i
diff --git a/app/models/transaction.rb b/app/models/transaction.rb
index 532121a541..ccbbcdfd4b 100644
--- a/app/models/transaction.rb
+++ b/app/models/transaction.rb
@@ -112,7 +112,7 @@ class Transaction < ApplicationRecord
INTERNAL_MOVEMENT_LABELS = [ "Transfer", "Sweep In", "Sweep Out", "Exchange" ].freeze
# Providers that support pending transaction flags
- PENDING_PROVIDERS = %w[simplefin plaid lunchflow enable_banking akahu up monobank mercury redbark].freeze
+ PENDING_PROVIDERS = %w[simplefin plaid lunchflow enable_banking akahu up monobank mercury redbark financekit].freeze
# Pre-computed SQL fragment for subqueries that check if a transaction (aliased as "t") is pending.
# Stored as a constant so static analysis can verify it contains no user input.
diff --git a/app/models/user.rb b/app/models/user.rb
index 1fc5741278..9232048b79 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -1,4 +1,6 @@
class User < ApplicationRecord
+ has_many :financekit_items, dependent: :destroy
+
include Encryptable
# Allow nil password for SSO-only users (JIT provisioning).
@@ -368,10 +370,13 @@ class User < ApplicationRecord
transaction do
lock!
- accounts_to_move = owned_accounts.to_a
+ accounts_to_move = owned_accounts.order(:id).to_a
provider_items_to_move = provider_items_for_transfer(accounts_to_move)
moving_default_account = accounts_to_move.any? { |account| account.id == default_account_id }
+ provider_items_to_move.sort_by(&:id).each(&:lock!)
+ accounts_to_move.each(&:lock!)
+
account_shares.delete_all
update!(family: new_family, role: role, default_account: moving_default_account ? default_account : nil)
@@ -383,6 +388,11 @@ class User < ApplicationRecord
AccountStatement.where(account: accounts_to_move).update_all(family_id: new_family.id, updated_at: Time.current) if accounts_to_move.any?
provider_items_to_move.each do |provider_item|
+ if provider_item.is_a?(FinancekitItem)
+ lineage_ids = provider_item.financekit_account_lineages.select(:id)
+ FinancekitAccountLineage.where(id: lineage_ids).update_all(family_id: new_family.id, updated_at: Time.current)
+ provider_item.financekit_conflicts.update_all(family_id: new_family.id, updated_at: Time.current)
+ end
attrs = { family: new_family }
# provider_items_for_transfer only returns items whose accounts all
@@ -403,11 +413,18 @@ class User < ApplicationRecord
account_ids_to_move = accounts_to_move.map(&:id)
provider_items = accounts_to_move.flat_map do |account|
account.account_providers.includes(:provider).filter_map do |account_provider|
- provider_item_for(account_provider.provider)
+ provider_items_for(account_provider.provider)
end
- end.uniq
+ end.flatten.uniq
+ provider_items.concat(financekit_items)
+ provider_items.uniq!
provider_items.each do |provider_item|
+ if provider_item.is_a?(FinancekitItem) && provider_item.user_id != id
+ errors.add(:base, :provider_item_has_other_accounts)
+ raise ActiveRecord::RecordInvalid, self
+ end
+
linked_account_ids = provider_item.accounts.map(&:id)
next if linked_account_ids.all? { |account_id| account_ids_to_move.include?(account_id) }
@@ -418,12 +435,16 @@ class User < ApplicationRecord
provider_items
end
- def provider_item_for(provider)
+ def provider_items_for(provider)
+ if provider.is_a?(FinancekitAccountLineage)
+ return provider.financekit_accounts.includes(:financekit_item).map(&:financekit_item).uniq
+ end
+
item_association = provider.class.reflect_on_all_associations(:belongs_to).find do |association|
association.name.to_s.end_with?("_item") && provider.respond_to?(association.name)
end
- provider.public_send(item_association.name) if item_association
+ Array(provider.public_send(item_association.name)) if item_association
end
# Revokes mobile/third-party API access alongside the web-session
diff --git a/config/initializers/filter_parameter_logging.rb b/config/initializers/filter_parameter_logging.rb
index 7ec2bc90c1..29abe5efb1 100644
--- a/config/initializers/filter_parameter_logging.rb
+++ b/config/initializers/filter_parameter_logging.rb
@@ -11,5 +11,6 @@ Rails.application.config.filter_parameters += [
# A device code redeems into tokens on its own, so it is a bearer credential in
# transit; verification_uri_complete embeds the user code, hence all three.
:device_code, :user_code, :verification_uri_complete,
- :bank_username, :bank_password, :security_answers, :captcha_input
+ :bank_username, :bank_password, :security_answers, :captcha_input, :credential,
+ :events, :consent, :booked_balance
]
diff --git a/config/initializers/rack_attack.rb b/config/initializers/rack_attack.rb
index 7aa151f67e..2b08d4a18a 100644
--- a/config/initializers/rack_attack.rb
+++ b/config/initializers/rack_attack.rb
@@ -143,6 +143,30 @@ class Rack::Attack
credential_guess_email.call(request) if request.post? && credential_guess_path.call(request, "/api/v1/auth/sso_link")
end
+ # FinanceKit publisher endpoints belong to this section: both the upload and
+ # the receipt read authenticate a bearer token against a stored SHA-256
+ # digest (FinancekitItem#authenticate_credential?), the same
+ # credential-against-stored-value shape as the throttles above. They sit
+ # outside Api::V1::BaseController, so its per-key rate limiting never runs.
+ # Guessing the token itself is infeasible — 256 bits of SecureRandom — but
+ # an accepted upload takes the item row lock and validates up to
+ # Financekit::MAX_RECORDS events, so the limit is really about bounding that
+ # work per publisher. Discriminate by publisher_id as well as IP, matching
+ # the section's throttle-by-both rule.
+ financekit_publisher_id = ->(request) do
+ request.path.match(
+ %r{\A/api/v1/financekit/publishers/([^/]+)/batches(?:/[^/]+)?(?:\.[^./?]+)?\z}
+ )&.captures&.first
+ end
+
+ throttle("financekit_publisher/ip", limit: 60, period: 1.minute) do |request|
+ request.ip if financekit_publisher_id.call(request)
+ end
+
+ throttle("financekit_publisher/publisher", limit: 60, period: 1.minute) do |request|
+ financekit_publisher_id.call(request)
+ end
+
# The background jobs console lives under /settings (so its polling GET
# isn't throttled), but its mutation is destructive and super-admin only —
# rate limit it independently.
diff --git a/config/routes.rb b/config/routes.rb
index 390bcae496..d87c360813 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -718,6 +718,18 @@ Rails.application.routes.draw do
# API routes
namespace :api do
namespace :v1 do
+ namespace :financekit do
+ get "capabilities", to: "connections#capabilities"
+ resources :connections, only: [ :create, :show, :destroy ] do
+ put "account_mappings/:source_id", to: "connections#mapping"
+ post :activate, to: "connections#activate"
+ post :credential, to: "connections#credential"
+ post :repair, to: "connections#repair"
+ resources :conflicts, only: [ :index, :update ]
+ end
+ post "publishers/:publisher_id/batches", to: "batches#create", as: :publisher_batches_upload
+ get "publishers/:publisher_id/batches/:batch_id", to: "batches#show", as: :publisher_batch_status
+ end
# Authentication endpoints
post "auth/signup", to: "auth#signup"
post "auth/login", to: "auth#login"
diff --git a/config/schedule.yml b/config/schedule.yml
index 1683540a3d..126681d8cd 100644
--- a/config/schedule.yml
+++ b/config/schedule.yml
@@ -13,6 +13,12 @@ clean_syncs:
queue: "scheduled"
description: "Cleans up stale syncs and reaps imports, exports, and provider fetch flags stuck by lost jobs"
+process_financekit_inbox:
+ cron: "*/5 * * * *"
+ class: "FinancekitInboxJob"
+ queue: "high_priority"
+ description: "Applies durable FinanceKit publisher batches and retries downstream work"
+
run_security_health_checks:
cron: "0 2 * * 1-5" # 2:00 AM EST / 3:00 AM EDT (NY time) Monday through Friday
class: "SecurityHealthCheckJob"
diff --git a/db/migrate/20260922230000_create_financekit_device_publisher.rb b/db/migrate/20260922230000_create_financekit_device_publisher.rb
new file mode 100644
index 0000000000..4ed0bcd289
--- /dev/null
+++ b/db/migrate/20260922230000_create_financekit_device_publisher.rb
@@ -0,0 +1,143 @@
+class CreateFinancekitDevicePublisher < ActiveRecord::Migration[8.1]
+ def change
+ create_table :financekit_items, id: :uuid do |t|
+ t.references :family, type: :uuid, null: false, foreign_key: true
+ t.references :user, type: :uuid, null: false, foreign_key: true
+ t.references :replaces_financekit_item, type: :uuid, foreign_key: { to_table: :financekit_items, on_delete: :nullify }
+ t.uuid :enrollment_id, null: false
+ t.uuid :publisher_id, null: false
+ t.uuid :stream_id
+ t.bigint :generation, null: false, default: 1
+ t.bigint :next_sequence, null: false, default: 1
+ t.string :predecessor_digest
+ t.string :credential_digest
+ t.string :enrollment_digest, null: false
+ t.jsonb :consent, null: false
+ t.string :status, null: false, default: "pending_mapping"
+ t.string :repair_reason
+ t.datetime :last_device_contact_at
+ t.datetime :last_accepted_at
+ t.datetime :last_captured_at
+ t.datetime :last_imported_at
+ t.datetime :last_downstream_at
+ t.timestamps
+ end
+ add_index :financekit_items, [ :family_id, :enrollment_id ], unique: true
+ add_index :financekit_items, :publisher_id, unique: true
+ add_check_constraint :financekit_items, "generation > 0 AND next_sequence > 0", name: "financekit_items_positive_stream"
+
+ create_table :financekit_account_lineages, id: :uuid do |t|
+ t.references :family, type: :uuid, null: false, foreign_key: true
+ t.references :account, type: :uuid, foreign_key: { on_delete: :nullify }
+ t.string :status, null: false, default: "active"
+ t.timestamps
+ end
+ add_index :financekit_account_lineages, [ :family_id, :account_id ], unique: true,
+ where: "account_id IS NOT NULL", name: "financekit_lineage_canonical_account"
+
+ create_table :financekit_accounts, id: :uuid do |t|
+ t.references :financekit_item, type: :uuid, null: false, foreign_key: true
+ t.references :financekit_account_lineage, type: :uuid, null: false, foreign_key: true, index: { name: "index_financekit_accounts_on_lineage_id" }
+ t.uuid :source_id, null: false
+ t.integer :mapping_version, null: false, default: 1
+ t.string :mapping_digest, null: false
+ t.string :name, null: false
+ t.string :institution_name
+ t.string :currency, null: false
+ t.string :accountable_type, null: false
+ t.string :subtype, null: false
+ t.string :ledger_timezone, null: false
+ t.datetime :unavailable_at
+ t.timestamps
+ end
+ add_index :financekit_accounts, [ :financekit_item_id, :source_id ], unique: true
+ add_index :financekit_accounts, [ :financekit_item_id, :financekit_account_lineage_id ], unique: true,
+ name: "financekit_item_lineage_identity"
+
+ create_table :financekit_batches, id: :uuid do |t|
+ t.references :financekit_item, type: :uuid, null: false, foreign_key: true
+ t.references :sync, type: :uuid, foreign_key: { on_delete: :nullify }
+ t.uuid :batch_id, null: false
+ t.uuid :stream_id, null: false
+ t.uuid :capture_id, null: false
+ t.bigint :generation, null: false
+ t.bigint :sequence, null: false
+ t.string :predecessor_digest
+ t.string :payload_digest, null: false
+ t.integer :chunk_index, null: false
+ t.integer :chunk_count, null: false
+ t.string :capture_mode, null: false
+ t.boolean :snapshot_complete, null: false, default: false
+ t.binary :payload
+ t.string :status, null: false, default: "accepted"
+ t.string :error_code
+ t.jsonb :counts, null: false, default: {}
+ t.integer :attempts, null: false, default: 0
+ t.datetime :retry_at
+ t.datetime :captured_at, null: false
+ t.datetime :accepted_at, null: false
+ t.datetime :applied_at
+ t.datetime :downstream_completed_at
+ t.timestamps
+ end
+ add_index :financekit_batches, [ :financekit_item_id, :generation, :batch_id ], unique: true,
+ name: "financekit_batch_identity"
+ add_index :financekit_batches, [ :financekit_item_id, :generation, :stream_id, :sequence ], unique: true,
+ name: "financekit_stream_sequence"
+ add_index :financekit_batches, [ :status, :retry_at ]
+ add_check_constraint :financekit_batches,
+ "sequence > 0 AND generation > 0 AND chunk_index >= 0 AND chunk_count > 0 AND chunk_index < chunk_count",
+ name: "financekit_batch_stream_values"
+
+ create_table :financekit_balance_observations, id: :uuid do |t|
+ t.references :financekit_account_lineage, type: :uuid, null: false, foreign_key: true,
+ index: { name: "index_financekit_balances_on_lineage_id" }
+ t.references :financekit_account, type: :uuid, foreign_key: { on_delete: :nullify }
+ t.uuid :source_id, null: false
+ t.string :kind, null: false
+ t.datetime :observed_at, null: false
+ t.decimal :amount, precision: 19, scale: 4, null: false
+ t.string :currency, null: false
+ t.string :direction, null: false
+ t.timestamps
+ end
+ add_index :financekit_balance_observations,
+ [ :financekit_account_lineage_id, :source_id, :kind, :observed_at ], unique: true,
+ name: "financekit_balance_observation_identity"
+
+ create_table :financekit_transactions, id: :uuid do |t|
+ t.references :financekit_account_lineage, type: :uuid, null: false, foreign_key: true,
+ index: { name: "index_financekit_transactions_on_lineage_id" }
+ t.references :financekit_account, type: :uuid, foreign_key: { on_delete: :nullify }
+ t.references :entry, type: :uuid, foreign_key: { on_delete: :nullify }
+ t.uuid :source_id, null: false
+ t.bigint :generation, null: false
+ t.bigint :sequence, null: false
+ t.string :status, null: false
+ t.jsonb :raw_payload
+ t.boolean :ledger_imported, null: false, default: false
+ t.datetime :tombstoned_at
+ t.boolean :review_required, null: false, default: false
+ t.timestamps
+ end
+ add_index :financekit_transactions, [ :financekit_account_lineage_id, :source_id ], unique: true,
+ name: "financekit_transaction_lineage_identity"
+
+ create_table :financekit_conflicts, id: :uuid do |t|
+ t.references :family, type: :uuid, null: false, foreign_key: true
+ t.references :financekit_item, type: :uuid, null: false, foreign_key: true
+ t.references :financekit_account_lineage, type: :uuid, foreign_key: { on_delete: :nullify },
+ index: { name: "index_financekit_conflicts_on_lineage_id" }
+ t.references :financekit_transaction, type: :uuid, foreign_key: { on_delete: :nullify }
+ t.references :resolved_by, type: :uuid, foreign_key: { to_table: :users, on_delete: :nullify }
+ t.string :kind, null: false
+ t.string :status, null: false, default: "open"
+ t.jsonb :details, null: false, default: {}
+ t.string :resolution
+ t.datetime :resolved_at
+ t.timestamps
+ end
+ add_index :financekit_conflicts, [ :financekit_item_id, :status, :created_at ],
+ name: "financekit_conflicts_status_created"
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 40ae8b50ef..1460237126 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
-ActiveRecord::Schema[8.1].define(version: 2026_09_16_220129) do
+ActiveRecord::Schema[8.1].define(version: 2026_09_22_230000) do
# These are extensions that must be enabled in order to support this database
enable_extension "pg_catalog.plpgsql"
enable_extension "pgcrypto"
@@ -881,6 +881,159 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_16_220129) do
t.index ["merchant_id"], name: "index_family_merchant_associations_on_merchant_id"
end
+ create_table "financekit_account_lineages", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
+ t.uuid "account_id"
+ t.datetime "created_at", null: false
+ t.uuid "family_id", null: false
+ t.string "status", default: "active", null: false
+ t.datetime "updated_at", null: false
+ t.index ["account_id"], name: "index_financekit_account_lineages_on_account_id"
+ t.index ["family_id", "account_id"], name: "financekit_lineage_canonical_account", unique: true, where: "(account_id IS NOT NULL)"
+ t.index ["family_id"], name: "index_financekit_account_lineages_on_family_id"
+ end
+
+ create_table "financekit_accounts", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
+ t.string "accountable_type", null: false
+ t.datetime "created_at", null: false
+ t.string "currency", null: false
+ t.uuid "financekit_account_lineage_id", null: false
+ t.uuid "financekit_item_id", null: false
+ t.string "institution_name"
+ t.string "ledger_timezone", null: false
+ t.string "mapping_digest", null: false
+ t.integer "mapping_version", default: 1, null: false
+ t.string "name", null: false
+ t.uuid "source_id", null: false
+ t.string "subtype", null: false
+ t.datetime "unavailable_at"
+ t.datetime "updated_at", null: false
+ t.index ["financekit_account_lineage_id"], name: "index_financekit_accounts_on_lineage_id"
+ t.index ["financekit_item_id", "financekit_account_lineage_id"], name: "financekit_item_lineage_identity", unique: true
+ t.index ["financekit_item_id", "source_id"], name: "index_financekit_accounts_on_financekit_item_id_and_source_id", unique: true
+ t.index ["financekit_item_id"], name: "index_financekit_accounts_on_financekit_item_id"
+ end
+
+ create_table "financekit_balance_observations", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
+ t.decimal "amount", precision: 19, scale: 4, null: false
+ t.datetime "created_at", null: false
+ t.string "currency", null: false
+ t.string "direction", null: false
+ t.uuid "financekit_account_id"
+ t.uuid "financekit_account_lineage_id", null: false
+ t.string "kind", null: false
+ t.datetime "observed_at", null: false
+ t.uuid "source_id", null: false
+ t.datetime "updated_at", null: false
+ t.index ["financekit_account_id"], name: "index_financekit_balance_observations_on_financekit_account_id"
+ t.index ["financekit_account_lineage_id", "source_id", "kind", "observed_at"], name: "financekit_balance_observation_identity", unique: true
+ t.index ["financekit_account_lineage_id"], name: "index_financekit_balances_on_lineage_id"
+ end
+
+ create_table "financekit_batches", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
+ t.datetime "accepted_at", null: false
+ t.datetime "applied_at"
+ t.integer "attempts", default: 0, null: false
+ t.uuid "batch_id", null: false
+ t.uuid "capture_id", null: false
+ t.string "capture_mode", null: false
+ t.datetime "captured_at", null: false
+ t.integer "chunk_count", null: false
+ t.integer "chunk_index", null: false
+ t.jsonb "counts", default: {}, null: false
+ t.datetime "created_at", null: false
+ t.datetime "downstream_completed_at"
+ t.string "error_code"
+ t.uuid "financekit_item_id", null: false
+ t.bigint "generation", null: false
+ t.binary "payload"
+ t.string "payload_digest", null: false
+ t.string "predecessor_digest"
+ t.datetime "retry_at"
+ t.bigint "sequence", null: false
+ t.boolean "snapshot_complete", default: false, null: false
+ t.string "status", default: "accepted", null: false
+ t.uuid "stream_id", null: false
+ t.uuid "sync_id"
+ t.datetime "updated_at", null: false
+ t.index ["financekit_item_id", "generation", "batch_id"], name: "financekit_batch_identity", unique: true
+ t.index ["financekit_item_id", "generation", "stream_id", "sequence"], name: "financekit_stream_sequence", unique: true
+ t.index ["financekit_item_id"], name: "index_financekit_batches_on_financekit_item_id"
+ t.index ["status", "retry_at"], name: "index_financekit_batches_on_status_and_retry_at"
+ t.index ["sync_id"], name: "index_financekit_batches_on_sync_id"
+ t.check_constraint "sequence > 0 AND generation > 0 AND chunk_index >= 0 AND chunk_count > 0 AND chunk_index < chunk_count", name: "financekit_batch_stream_values"
+ end
+
+ create_table "financekit_conflicts", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
+ t.datetime "created_at", null: false
+ t.jsonb "details", default: {}, null: false
+ t.uuid "family_id", null: false
+ t.uuid "financekit_account_lineage_id"
+ t.uuid "financekit_item_id", null: false
+ t.uuid "financekit_transaction_id"
+ t.string "kind", null: false
+ t.string "resolution"
+ t.datetime "resolved_at"
+ t.uuid "resolved_by_id"
+ t.string "status", default: "open", null: false
+ t.datetime "updated_at", null: false
+ t.index ["family_id"], name: "index_financekit_conflicts_on_family_id"
+ t.index ["financekit_account_lineage_id"], name: "index_financekit_conflicts_on_lineage_id"
+ t.index ["financekit_item_id", "status", "created_at"], name: "financekit_conflicts_status_created"
+ t.index ["financekit_item_id"], name: "index_financekit_conflicts_on_financekit_item_id"
+ t.index ["financekit_transaction_id"], name: "index_financekit_conflicts_on_financekit_transaction_id"
+ t.index ["resolved_by_id"], name: "index_financekit_conflicts_on_resolved_by_id"
+ end
+
+ create_table "financekit_items", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
+ t.jsonb "consent", null: false
+ t.datetime "created_at", null: false
+ t.string "credential_digest"
+ t.string "enrollment_digest", null: false
+ t.uuid "enrollment_id", null: false
+ t.uuid "family_id", null: false
+ t.bigint "generation", default: 1, null: false
+ t.datetime "last_accepted_at"
+ t.datetime "last_captured_at"
+ t.datetime "last_device_contact_at"
+ t.datetime "last_downstream_at"
+ t.datetime "last_imported_at"
+ t.bigint "next_sequence", default: 1, null: false
+ t.string "predecessor_digest"
+ t.uuid "publisher_id", null: false
+ t.string "repair_reason"
+ t.uuid "replaces_financekit_item_id"
+ t.string "status", default: "pending_mapping", null: false
+ t.uuid "stream_id"
+ t.datetime "updated_at", null: false
+ t.uuid "user_id", null: false
+ t.index ["family_id", "enrollment_id"], name: "index_financekit_items_on_family_id_and_enrollment_id", unique: true
+ t.index ["family_id"], name: "index_financekit_items_on_family_id"
+ t.index ["publisher_id"], name: "index_financekit_items_on_publisher_id", unique: true
+ t.index ["replaces_financekit_item_id"], name: "index_financekit_items_on_replaces_financekit_item_id"
+ t.index ["user_id"], name: "index_financekit_items_on_user_id"
+ t.check_constraint "generation > 0 AND next_sequence > 0", name: "financekit_items_positive_stream"
+ end
+
+ create_table "financekit_transactions", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
+ t.datetime "created_at", null: false
+ t.uuid "entry_id"
+ t.uuid "financekit_account_id"
+ t.uuid "financekit_account_lineage_id", null: false
+ t.bigint "generation", null: false
+ t.boolean "ledger_imported", default: false, null: false
+ t.jsonb "raw_payload"
+ t.boolean "review_required", default: false, null: false
+ t.bigint "sequence", null: false
+ t.uuid "source_id", null: false
+ t.string "status", null: false
+ t.datetime "tombstoned_at"
+ t.datetime "updated_at", null: false
+ t.index ["entry_id"], name: "index_financekit_transactions_on_entry_id"
+ t.index ["financekit_account_id"], name: "index_financekit_transactions_on_financekit_account_id"
+ t.index ["financekit_account_lineage_id", "source_id"], name: "financekit_transaction_lineage_identity", unique: true
+ t.index ["financekit_account_lineage_id"], name: "index_financekit_transactions_on_lineage_id"
+ end
+
create_table "fio_accounts", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
t.string "bank_id"
t.string "bic"
@@ -2773,6 +2926,25 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_16_220129) do
add_foreign_key "family_exports", "families"
add_foreign_key "family_merchant_associations", "families"
add_foreign_key "family_merchant_associations", "merchants"
+ add_foreign_key "financekit_account_lineages", "accounts", on_delete: :nullify
+ add_foreign_key "financekit_account_lineages", "families"
+ add_foreign_key "financekit_accounts", "financekit_account_lineages"
+ add_foreign_key "financekit_accounts", "financekit_items"
+ add_foreign_key "financekit_balance_observations", "financekit_account_lineages"
+ add_foreign_key "financekit_balance_observations", "financekit_accounts", on_delete: :nullify
+ add_foreign_key "financekit_batches", "financekit_items"
+ add_foreign_key "financekit_batches", "syncs", on_delete: :nullify
+ add_foreign_key "financekit_conflicts", "families"
+ add_foreign_key "financekit_conflicts", "financekit_account_lineages", on_delete: :nullify
+ add_foreign_key "financekit_conflicts", "financekit_items"
+ add_foreign_key "financekit_conflicts", "financekit_transactions", on_delete: :nullify
+ add_foreign_key "financekit_conflicts", "users", column: "resolved_by_id", on_delete: :nullify
+ add_foreign_key "financekit_items", "families"
+ add_foreign_key "financekit_items", "financekit_items", column: "replaces_financekit_item_id", on_delete: :nullify
+ add_foreign_key "financekit_items", "users"
+ add_foreign_key "financekit_transactions", "entries", on_delete: :nullify
+ add_foreign_key "financekit_transactions", "financekit_account_lineages"
+ add_foreign_key "financekit_transactions", "financekit_accounts", on_delete: :nullify
add_foreign_key "fio_accounts", "fio_items"
add_foreign_key "fio_items", "families"
add_foreign_key "goal_accounts", "accounts", on_delete: :restrict
diff --git a/docs/api/financekit/schemas.json b/docs/api/financekit/schemas.json
new file mode 100644
index 0000000000..96e842e9a1
--- /dev/null
+++ b/docs/api/financekit/schemas.json
@@ -0,0 +1,1109 @@
+{
+ "FinancekitMoney": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "amount",
+ "currency",
+ "direction"
+ ],
+ "properties": {
+ "amount": {
+ "type": "string",
+ "pattern": "^(0|[1-9][0-9]{0,14})(\\.[0-9]{1,4})?$"
+ },
+ "currency": {
+ "type": "string",
+ "pattern": "^[A-Z]{3,5}$"
+ },
+ "direction": {
+ "type": "string",
+ "enum": [
+ "credit",
+ "debit"
+ ]
+ }
+ }
+ },
+ "FinancekitConsent": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "version",
+ "granted_at",
+ "selected_source_account_ids",
+ "upload_authorized",
+ "family_visibility_acknowledged",
+ "remote_processing_acknowledged"
+ ],
+ "properties": {
+ "version": {
+ "type": "integer",
+ "enum": [
+ 1
+ ]
+ },
+ "granted_at": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "selected_source_account_ids": {
+ "type": "array",
+ "minItems": 1,
+ "maxItems": 20,
+ "uniqueItems": true,
+ "items": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ }
+ },
+ "upload_authorized": {
+ "type": "boolean",
+ "enum": [
+ true
+ ]
+ },
+ "family_visibility_acknowledged": {
+ "type": "boolean",
+ "enum": [
+ true
+ ]
+ },
+ "remote_processing_acknowledged": {
+ "type": "boolean",
+ "enum": [
+ true
+ ]
+ }
+ }
+ },
+ "FinancekitEnrollment": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "protocol_version",
+ "enrollment_id",
+ "consent"
+ ],
+ "properties": {
+ "protocol_version": {
+ "type": "integer",
+ "enum": [
+ 2
+ ]
+ },
+ "enrollment_id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "replaces_connection_id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "consent": {
+ "$ref": "#/components/schemas/FinancekitConsent"
+ }
+ }
+ },
+ "FinancekitMappingRequest": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "expected_version",
+ "action",
+ "name",
+ "institution_name",
+ "currency",
+ "accountable_type",
+ "subtype",
+ "ledger_timezone"
+ ],
+ "properties": {
+ "expected_version": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "action": {
+ "type": "string",
+ "enum": [
+ "create",
+ "link"
+ ]
+ },
+ "name": {
+ "type": "string",
+ "maxLength": 255
+ },
+ "institution_name": {
+ "type": "string",
+ "maxLength": 255
+ },
+ "currency": {
+ "type": "string"
+ },
+ "accountable_type": {
+ "type": "string",
+ "enum": [
+ "Depository",
+ "CreditCard"
+ ]
+ },
+ "subtype": {
+ "type": "string"
+ },
+ "ledger_timezone": {
+ "type": "string"
+ },
+ "account_id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "lineage_id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "booked_balance": {
+ "$ref": "#/components/schemas/FinancekitMoney"
+ },
+ "observed_at": {
+ "type": "string",
+ "format": "date-time"
+ }
+ },
+ "description": "create requires booked_balance and observed_at; link requires a writable same-family account_id and may carry a prior lineage_id"
+ },
+ "FinancekitAccountMapping": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "source_id",
+ "lineage_id",
+ "mapping_version",
+ "name",
+ "institution_name",
+ "currency",
+ "accountable_type",
+ "subtype",
+ "ledger_timezone",
+ "account_id"
+ ],
+ "properties": {
+ "source_id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "lineage_id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "mapping_version": {
+ "type": "integer",
+ "minimum": 1
+ },
+ "name": {
+ "type": "string"
+ },
+ "institution_name": {
+ "type": "string",
+ "nullable": true
+ },
+ "currency": {
+ "type": "string"
+ },
+ "accountable_type": {
+ "type": "string"
+ },
+ "subtype": {
+ "type": "string"
+ },
+ "ledger_timezone": {
+ "type": "string"
+ },
+ "account_id": {
+ "allOf": [
+ {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ }
+ ],
+ "nullable": true
+ }
+ }
+ },
+ "FinancekitAccountBinding": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "source_account_id",
+ "lineage_id",
+ "mapping_version"
+ ],
+ "properties": {
+ "source_account_id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "lineage_id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "mapping_version": {
+ "type": "integer",
+ "minimum": 1
+ }
+ }
+ },
+ "FinancekitConnection": {
+ "type": "object",
+ "required": [
+ "id",
+ "connection_id",
+ "publisher_id",
+ "status",
+ "generation",
+ "next_sequence",
+ "open_conflicts"
+ ],
+ "properties": {
+ "id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "connection_id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "publisher_id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "status": {
+ "type": "string",
+ "enum": [
+ "pending_mapping",
+ "active",
+ "repair_required",
+ "revoked"
+ ]
+ },
+ "generation": {
+ "type": "integer",
+ "minimum": 1
+ },
+ "stream_id": {
+ "allOf": [
+ {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ }
+ ],
+ "nullable": true
+ },
+ "next_sequence": {
+ "type": "integer",
+ "minimum": 1
+ },
+ "repair_reason": {
+ "type": "string",
+ "nullable": true
+ },
+ "last_device_contact_at": {
+ "allOf": [
+ {
+ "type": "string",
+ "format": "date-time"
+ }
+ ],
+ "nullable": true
+ },
+ "last_accepted_at": {
+ "allOf": [
+ {
+ "type": "string",
+ "format": "date-time"
+ }
+ ],
+ "nullable": true
+ },
+ "last_imported_at": {
+ "allOf": [
+ {
+ "type": "string",
+ "format": "date-time"
+ }
+ ],
+ "nullable": true
+ },
+ "last_downstream_at": {
+ "allOf": [
+ {
+ "type": "string",
+ "format": "date-time"
+ }
+ ],
+ "nullable": true
+ },
+ "last_captured_at": {
+ "allOf": [
+ {
+ "type": "string",
+ "format": "date-time"
+ }
+ ],
+ "nullable": true
+ },
+ "open_conflicts": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "accounts": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/FinancekitAccountMapping"
+ }
+ },
+ "pagination": {
+ "$ref": "#/components/schemas/Pagination"
+ }
+ }
+ },
+ "FinancekitPublisherConfiguration": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/FinancekitConnection"
+ },
+ {
+ "type": "object",
+ "required": [
+ "protocol_version",
+ "server_url",
+ "upload_url",
+ "consent",
+ "account_bindings",
+ "max_records_per_batch",
+ "max_bytes_per_batch",
+ "publisher_credential"
+ ],
+ "properties": {
+ "protocol_version": {
+ "type": "integer",
+ "enum": [
+ 2
+ ]
+ },
+ "server_url": {
+ "type": "string",
+ "format": "uri"
+ },
+ "upload_url": {
+ "type": "string",
+ "format": "uri"
+ },
+ "consent": {
+ "$ref": "#/components/schemas/FinancekitConsent"
+ },
+ "account_bindings": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/FinancekitAccountBinding"
+ }
+ },
+ "max_records_per_batch": {
+ "type": "integer",
+ "minimum": 1
+ },
+ "max_bytes_per_batch": {
+ "type": "integer",
+ "minimum": 1
+ },
+ "publisher_credential": {
+ "type": "string",
+ "writeOnly": true
+ }
+ }
+ }
+ ]
+ },
+ "FinancekitAccountEvent": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "source_id",
+ "lineage_id",
+ "mapping_version",
+ "display_name",
+ "institution_name",
+ "currency",
+ "kind"
+ ],
+ "properties": {
+ "source_id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "lineage_id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "mapping_version": {
+ "type": "integer",
+ "minimum": 1
+ },
+ "display_name": {
+ "type": "string",
+ "maxLength": 255
+ },
+ "institution_name": {
+ "type": "string",
+ "maxLength": 255
+ },
+ "currency": {
+ "type": "string"
+ },
+ "kind": {
+ "type": "string",
+ "enum": [
+ "asset",
+ "liability"
+ ]
+ },
+ "account_description": {
+ "type": "string",
+ "maxLength": 1000
+ },
+ "opening_date": {
+ "type": "string",
+ "format": "date-time"
+ }
+ }
+ },
+ "FinancekitBalanceEvent": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "source_id",
+ "source_account_id",
+ "lineage_id",
+ "mapping_version",
+ "kind",
+ "observed_at",
+ "money"
+ ],
+ "properties": {
+ "source_id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "source_account_id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "lineage_id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "mapping_version": {
+ "type": "integer",
+ "minimum": 1
+ },
+ "kind": {
+ "type": "string",
+ "enum": [
+ "available",
+ "booked"
+ ]
+ },
+ "observed_at": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "money": {
+ "$ref": "#/components/schemas/FinancekitMoney"
+ }
+ }
+ },
+ "FinancekitTransactionEvent": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "source_id",
+ "source_account_id",
+ "lineage_id",
+ "mapping_version",
+ "amount",
+ "transaction_description",
+ "original_transaction_description",
+ "transaction_type",
+ "status",
+ "transacted_at"
+ ],
+ "properties": {
+ "source_id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "source_account_id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "lineage_id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "mapping_version": {
+ "type": "integer",
+ "minimum": 1
+ },
+ "amount": {
+ "$ref": "#/components/schemas/FinancekitMoney"
+ },
+ "foreign_amount": {
+ "$ref": "#/components/schemas/FinancekitMoney"
+ },
+ "foreign_exchange_rate": {
+ "type": "string"
+ },
+ "transaction_description": {
+ "type": "string",
+ "maxLength": 1000
+ },
+ "original_transaction_description": {
+ "type": "string",
+ "maxLength": 1000
+ },
+ "transaction_type": {
+ "type": "string",
+ "maxLength": 100
+ },
+ "status": {
+ "type": "string",
+ "enum": [
+ "authorized",
+ "pending",
+ "booked",
+ "rejected",
+ "memo",
+ "unknown"
+ ]
+ },
+ "transacted_at": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "posted_at": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "merchant_name": {
+ "type": "string",
+ "maxLength": 255
+ },
+ "merchant_category_code": {
+ "type": "integer",
+ "minimum": -32768,
+ "maximum": 32767
+ }
+ }
+ },
+ "FinancekitTombstoneEvent": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "source_id",
+ "source_account_id",
+ "lineage_id",
+ "mapping_version"
+ ],
+ "properties": {
+ "source_id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "source_account_id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "lineage_id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "mapping_version": {
+ "type": "integer",
+ "minimum": 1
+ }
+ }
+ },
+ "FinancekitEvent": {
+ "oneOf": [
+ {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "kind",
+ "account"
+ ],
+ "properties": {
+ "kind": {
+ "type": "string",
+ "enum": [
+ "account_upsert"
+ ]
+ },
+ "account": {
+ "$ref": "#/components/schemas/FinancekitAccountEvent"
+ }
+ }
+ },
+ {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "kind",
+ "source_account_id",
+ "lineage_id",
+ "mapping_version"
+ ],
+ "properties": {
+ "kind": {
+ "type": "string",
+ "enum": [
+ "account_unavailable"
+ ]
+ },
+ "source_account_id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "lineage_id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "mapping_version": {
+ "type": "integer",
+ "minimum": 1
+ }
+ }
+ },
+ {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "kind",
+ "balance"
+ ],
+ "properties": {
+ "kind": {
+ "type": "string",
+ "enum": [
+ "balance_upsert"
+ ]
+ },
+ "balance": {
+ "$ref": "#/components/schemas/FinancekitBalanceEvent"
+ }
+ }
+ },
+ {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "kind",
+ "transaction"
+ ],
+ "properties": {
+ "kind": {
+ "type": "string",
+ "enum": [
+ "transaction_upsert"
+ ]
+ },
+ "transaction": {
+ "$ref": "#/components/schemas/FinancekitTransactionEvent"
+ }
+ }
+ },
+ {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "kind",
+ "tombstone"
+ ],
+ "properties": {
+ "kind": {
+ "type": "string",
+ "enum": [
+ "transaction_tombstone"
+ ]
+ },
+ "tombstone": {
+ "$ref": "#/components/schemas/FinancekitTombstoneEvent"
+ }
+ }
+ }
+ ]
+ },
+ "FinancekitBatch": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "protocol_version",
+ "connection_id",
+ "publisher_id",
+ "generation",
+ "stream_id",
+ "batch_id",
+ "sequence",
+ "capture_id",
+ "chunk_index",
+ "chunk_count",
+ "capture_mode",
+ "snapshot_complete",
+ "captured_at",
+ "selected_source_account_ids",
+ "events"
+ ],
+ "properties": {
+ "protocol_version": {
+ "type": "integer",
+ "enum": [
+ 2
+ ]
+ },
+ "connection_id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "publisher_id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "generation": {
+ "type": "integer",
+ "minimum": 1
+ },
+ "stream_id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "batch_id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "sequence": {
+ "type": "integer",
+ "minimum": 1
+ },
+ "predecessor_digest": {
+ "type": "string",
+ "pattern": "^[0-9a-f]{64}$"
+ },
+ "capture_id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "chunk_index": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "chunk_count": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 100
+ },
+ "capture_mode": {
+ "type": "string",
+ "enum": [
+ "snapshot",
+ "delta"
+ ]
+ },
+ "snapshot_complete": {
+ "type": "boolean"
+ },
+ "captured_at": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "selected_source_account_ids": {
+ "type": "array",
+ "minItems": 1,
+ "maxItems": 20,
+ "uniqueItems": true,
+ "items": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ }
+ },
+ "events": {
+ "type": "array",
+ "maxItems": 500,
+ "items": {
+ "$ref": "#/components/schemas/FinancekitEvent"
+ }
+ }
+ },
+ "description": "Immutable ordered publisher batch. sequence 1 omits predecessor_digest; later batches carry the SHA-256 digest of the preceding payload. Omission never deletes data."
+ },
+ "FinancekitBatchReceipt": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "connection_id",
+ "publisher_id",
+ "generation",
+ "stream_id",
+ "batch_id",
+ "sequence",
+ "payload_digest",
+ "status",
+ "accepted_at",
+ "applied_at",
+ "error_code"
+ ],
+ "properties": {
+ "connection_id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "publisher_id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "generation": {
+ "type": "integer"
+ },
+ "stream_id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "batch_id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "sequence": {
+ "type": "integer"
+ },
+ "payload_digest": {
+ "type": "string",
+ "pattern": "^[0-9a-f]{64}$"
+ },
+ "status": {
+ "type": "string",
+ "enum": [
+ "accepted",
+ "processing",
+ "applied",
+ "failed",
+ "revoked"
+ ]
+ },
+ "accepted_at": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "applied_at": {
+ "type": "string",
+ "format": "date-time",
+ "nullable": true
+ },
+ "error_code": {
+ "type": "string",
+ "nullable": true
+ }
+ }
+ },
+ "FinancekitConflict": {
+ "type": "object",
+ "required": [
+ "id",
+ "kind",
+ "status",
+ "details",
+ "created_at"
+ ],
+ "properties": {
+ "id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ },
+ "kind": {
+ "type": "string"
+ },
+ "status": {
+ "type": "string",
+ "enum": [
+ "open",
+ "resolved"
+ ]
+ },
+ "details": {
+ "type": "object"
+ },
+ "resolution": {
+ "type": "string",
+ "nullable": true
+ },
+ "resolved_at": {
+ "allOf": [
+ {
+ "type": "string",
+ "format": "date-time"
+ }
+ ],
+ "nullable": true
+ },
+ "created_at": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "financekit_account_lineage_id": {
+ "allOf": [
+ {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ }
+ ],
+ "nullable": true
+ },
+ "financekit_transaction_id": {
+ "allOf": [
+ {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ }
+ ],
+ "nullable": true
+ }
+ }
+ },
+ "FinancekitConflictResolution": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "resolution"
+ ],
+ "properties": {
+ "resolution": {
+ "type": "string",
+ "description": "`keep_sure` closes the conflict without mutating the publisher stream. `retry_after_repair` closes the conflict, moves the connection to repair_required, revokes queued work and credentials, and requires POST /repair before uploads resume.",
+ "enum": [
+ "keep_sure",
+ "retry_after_repair"
+ ]
+ }
+ }
+ },
+ "FinancekitCapabilities": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "available",
+ "protocol_versions",
+ "delivery",
+ "max_payload_bytes",
+ "max_records",
+ "max_accounts",
+ "max_queued_batches",
+ "transaction_statuses",
+ "amount_precision",
+ "amount_scale"
+ ],
+ "properties": {
+ "available": {
+ "type": "boolean"
+ },
+ "protocol_versions": {
+ "type": "array",
+ "items": {
+ "type": "integer",
+ "enum": [
+ 2
+ ]
+ }
+ },
+ "delivery": {
+ "type": "string",
+ "enum": [
+ "background_publisher"
+ ]
+ },
+ "max_payload_bytes": {
+ "type": "integer"
+ },
+ "max_records": {
+ "type": "integer"
+ },
+ "max_accounts": {
+ "type": "integer"
+ },
+ "max_queued_batches": {
+ "type": "integer"
+ },
+ "transaction_statuses": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "amount_precision": {
+ "type": "integer"
+ },
+ "amount_scale": {
+ "type": "integer"
+ }
+ }
+ },
+ "FinancekitError": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "error"
+ ],
+ "properties": {
+ "error": {
+ "type": "string"
+ }
+ }
+ }
+}
diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml
index a495f5bd6f..df3bf8cc5e 100644
--- a/docs/api/openapi.yaml
+++ b/docs/api/openapi.yaml
@@ -16,6 +16,21 @@ components:
name: X-Api-Key
in: header
description: API key for authentication. Generate one from your account settings.
+ financekitPublisher:
+ type: http
+ scheme: bearer
+ bearerFormat: opaque publisher credential
+ description: Revocable credential restricted to one FinanceKit publisher upload
+ URL.
+ oauth2:
+ type: oauth2
+ flows:
+ authorizationCode:
+ authorizationUrl: "/oauth/authorize"
+ tokenUrl: "/oauth/token"
+ scopes:
+ read: Read access
+ read_write: Read and write access
schemas:
Pagination:
type: object
@@ -3625,12 +3640,1705 @@ components:
plaid_items:
type: integer
minimum: 0
+ FinancekitMoney:
+ type: object
+ additionalProperties: false
+ required:
+ - amount
+ - currency
+ - direction
+ properties:
+ amount:
+ type: string
+ pattern: "^(0|[1-9][0-9]{0,14})(\\.[0-9]{1,4})?$"
+ currency:
+ type: string
+ pattern: "^[A-Z]{3,5}$"
+ direction:
+ type: string
+ enum:
+ - credit
+ - debit
+ FinancekitConsent:
+ type: object
+ additionalProperties: false
+ required:
+ - version
+ - granted_at
+ - selected_source_account_ids
+ - upload_authorized
+ - family_visibility_acknowledged
+ - remote_processing_acknowledged
+ properties:
+ version:
+ type: integer
+ enum:
+ - 1
+ granted_at:
+ type: string
+ format: date-time
+ selected_source_account_ids:
+ type: array
+ minItems: 1
+ maxItems: 20
+ uniqueItems: true
+ items:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ upload_authorized:
+ type: boolean
+ enum:
+ - true
+ family_visibility_acknowledged:
+ type: boolean
+ enum:
+ - true
+ remote_processing_acknowledged:
+ type: boolean
+ enum:
+ - true
+ FinancekitEnrollment:
+ type: object
+ additionalProperties: false
+ required:
+ - protocol_version
+ - enrollment_id
+ - consent
+ properties:
+ protocol_version:
+ type: integer
+ enum:
+ - 2
+ enrollment_id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ replaces_connection_id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ consent:
+ "$ref": "#/components/schemas/FinancekitConsent"
+ FinancekitMappingRequest:
+ type: object
+ additionalProperties: false
+ required:
+ - expected_version
+ - action
+ - name
+ - institution_name
+ - currency
+ - accountable_type
+ - subtype
+ - ledger_timezone
+ properties:
+ expected_version:
+ type: integer
+ minimum: 0
+ action:
+ type: string
+ enum:
+ - create
+ - link
+ name:
+ type: string
+ maxLength: 255
+ institution_name:
+ type: string
+ maxLength: 255
+ currency:
+ type: string
+ accountable_type:
+ type: string
+ enum:
+ - Depository
+ - CreditCard
+ subtype:
+ type: string
+ ledger_timezone:
+ type: string
+ account_id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ lineage_id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ booked_balance:
+ "$ref": "#/components/schemas/FinancekitMoney"
+ observed_at:
+ type: string
+ format: date-time
+ description: create requires booked_balance and observed_at; link requires a
+ writable same-family account_id and may carry a prior lineage_id
+ FinancekitAccountMapping:
+ type: object
+ additionalProperties: false
+ required:
+ - source_id
+ - lineage_id
+ - mapping_version
+ - name
+ - institution_name
+ - currency
+ - accountable_type
+ - subtype
+ - ledger_timezone
+ - account_id
+ properties:
+ source_id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ lineage_id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ mapping_version:
+ type: integer
+ minimum: 1
+ name:
+ type: string
+ institution_name:
+ type: string
+ nullable: true
+ currency:
+ type: string
+ accountable_type:
+ type: string
+ subtype:
+ type: string
+ ledger_timezone:
+ type: string
+ account_id:
+ allOf:
+ - type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ nullable: true
+ FinancekitAccountBinding:
+ type: object
+ additionalProperties: false
+ required:
+ - source_account_id
+ - lineage_id
+ - mapping_version
+ properties:
+ source_account_id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ lineage_id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ mapping_version:
+ type: integer
+ minimum: 1
+ FinancekitConnection:
+ type: object
+ required:
+ - id
+ - connection_id
+ - publisher_id
+ - status
+ - generation
+ - next_sequence
+ - open_conflicts
+ properties:
+ id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ connection_id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ publisher_id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ status:
+ type: string
+ enum:
+ - pending_mapping
+ - active
+ - repair_required
+ - revoked
+ generation:
+ type: integer
+ minimum: 1
+ stream_id:
+ allOf:
+ - type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ nullable: true
+ next_sequence:
+ type: integer
+ minimum: 1
+ repair_reason:
+ type: string
+ nullable: true
+ last_device_contact_at:
+ allOf:
+ - type: string
+ format: date-time
+ nullable: true
+ last_accepted_at:
+ allOf:
+ - type: string
+ format: date-time
+ nullable: true
+ last_imported_at:
+ allOf:
+ - type: string
+ format: date-time
+ nullable: true
+ last_downstream_at:
+ allOf:
+ - type: string
+ format: date-time
+ nullable: true
+ last_captured_at:
+ allOf:
+ - type: string
+ format: date-time
+ nullable: true
+ open_conflicts:
+ type: integer
+ minimum: 0
+ accounts:
+ type: array
+ items:
+ "$ref": "#/components/schemas/FinancekitAccountMapping"
+ pagination:
+ "$ref": "#/components/schemas/Pagination"
+ FinancekitPublisherConfiguration:
+ allOf:
+ - "$ref": "#/components/schemas/FinancekitConnection"
+ - type: object
+ required:
+ - protocol_version
+ - server_url
+ - upload_url
+ - consent
+ - account_bindings
+ - max_records_per_batch
+ - max_bytes_per_batch
+ - publisher_credential
+ properties:
+ protocol_version:
+ type: integer
+ enum:
+ - 2
+ server_url:
+ type: string
+ format: uri
+ upload_url:
+ type: string
+ format: uri
+ consent:
+ "$ref": "#/components/schemas/FinancekitConsent"
+ account_bindings:
+ type: array
+ items:
+ "$ref": "#/components/schemas/FinancekitAccountBinding"
+ max_records_per_batch:
+ type: integer
+ minimum: 1
+ max_bytes_per_batch:
+ type: integer
+ minimum: 1
+ publisher_credential:
+ type: string
+ writeOnly: true
+ FinancekitAccountEvent:
+ type: object
+ additionalProperties: false
+ required:
+ - source_id
+ - lineage_id
+ - mapping_version
+ - display_name
+ - institution_name
+ - currency
+ - kind
+ properties:
+ source_id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ lineage_id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ mapping_version:
+ type: integer
+ minimum: 1
+ display_name:
+ type: string
+ maxLength: 255
+ institution_name:
+ type: string
+ maxLength: 255
+ currency:
+ type: string
+ kind:
+ type: string
+ enum:
+ - asset
+ - liability
+ account_description:
+ type: string
+ maxLength: 1000
+ opening_date:
+ type: string
+ format: date-time
+ FinancekitBalanceEvent:
+ type: object
+ additionalProperties: false
+ required:
+ - source_id
+ - source_account_id
+ - lineage_id
+ - mapping_version
+ - kind
+ - observed_at
+ - money
+ properties:
+ source_id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ source_account_id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ lineage_id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ mapping_version:
+ type: integer
+ minimum: 1
+ kind:
+ type: string
+ enum:
+ - available
+ - booked
+ observed_at:
+ type: string
+ format: date-time
+ money:
+ "$ref": "#/components/schemas/FinancekitMoney"
+ FinancekitTransactionEvent:
+ type: object
+ additionalProperties: false
+ required:
+ - source_id
+ - source_account_id
+ - lineage_id
+ - mapping_version
+ - amount
+ - transaction_description
+ - original_transaction_description
+ - transaction_type
+ - status
+ - transacted_at
+ properties:
+ source_id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ source_account_id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ lineage_id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ mapping_version:
+ type: integer
+ minimum: 1
+ amount:
+ "$ref": "#/components/schemas/FinancekitMoney"
+ foreign_amount:
+ "$ref": "#/components/schemas/FinancekitMoney"
+ foreign_exchange_rate:
+ type: string
+ transaction_description:
+ type: string
+ maxLength: 1000
+ original_transaction_description:
+ type: string
+ maxLength: 1000
+ transaction_type:
+ type: string
+ maxLength: 100
+ status:
+ type: string
+ enum:
+ - authorized
+ - pending
+ - booked
+ - rejected
+ - memo
+ - unknown
+ transacted_at:
+ type: string
+ format: date-time
+ posted_at:
+ type: string
+ format: date-time
+ merchant_name:
+ type: string
+ maxLength: 255
+ merchant_category_code:
+ type: integer
+ minimum: -32768
+ maximum: 32767
+ FinancekitTombstoneEvent:
+ type: object
+ additionalProperties: false
+ required:
+ - source_id
+ - source_account_id
+ - lineage_id
+ - mapping_version
+ properties:
+ source_id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ source_account_id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ lineage_id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ mapping_version:
+ type: integer
+ minimum: 1
+ FinancekitEvent:
+ oneOf:
+ - type: object
+ additionalProperties: false
+ required:
+ - kind
+ - account
+ properties:
+ kind:
+ type: string
+ enum:
+ - account_upsert
+ account:
+ "$ref": "#/components/schemas/FinancekitAccountEvent"
+ - type: object
+ additionalProperties: false
+ required:
+ - kind
+ - source_account_id
+ - lineage_id
+ - mapping_version
+ properties:
+ kind:
+ type: string
+ enum:
+ - account_unavailable
+ source_account_id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ lineage_id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ mapping_version:
+ type: integer
+ minimum: 1
+ - type: object
+ additionalProperties: false
+ required:
+ - kind
+ - balance
+ properties:
+ kind:
+ type: string
+ enum:
+ - balance_upsert
+ balance:
+ "$ref": "#/components/schemas/FinancekitBalanceEvent"
+ - type: object
+ additionalProperties: false
+ required:
+ - kind
+ - transaction
+ properties:
+ kind:
+ type: string
+ enum:
+ - transaction_upsert
+ transaction:
+ "$ref": "#/components/schemas/FinancekitTransactionEvent"
+ - type: object
+ additionalProperties: false
+ required:
+ - kind
+ - tombstone
+ properties:
+ kind:
+ type: string
+ enum:
+ - transaction_tombstone
+ tombstone:
+ "$ref": "#/components/schemas/FinancekitTombstoneEvent"
+ FinancekitBatch:
+ type: object
+ additionalProperties: false
+ required:
+ - protocol_version
+ - connection_id
+ - publisher_id
+ - generation
+ - stream_id
+ - batch_id
+ - sequence
+ - capture_id
+ - chunk_index
+ - chunk_count
+ - capture_mode
+ - snapshot_complete
+ - captured_at
+ - selected_source_account_ids
+ - events
+ properties:
+ protocol_version:
+ type: integer
+ enum:
+ - 2
+ connection_id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ publisher_id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ generation:
+ type: integer
+ minimum: 1
+ stream_id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ batch_id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ sequence:
+ type: integer
+ minimum: 1
+ predecessor_digest:
+ type: string
+ pattern: "^[0-9a-f]{64}$"
+ capture_id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ chunk_index:
+ type: integer
+ minimum: 0
+ chunk_count:
+ type: integer
+ minimum: 1
+ maximum: 100
+ capture_mode:
+ type: string
+ enum:
+ - snapshot
+ - delta
+ snapshot_complete:
+ type: boolean
+ captured_at:
+ type: string
+ format: date-time
+ selected_source_account_ids:
+ type: array
+ minItems: 1
+ maxItems: 20
+ uniqueItems: true
+ items:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ events:
+ type: array
+ maxItems: 500
+ items:
+ "$ref": "#/components/schemas/FinancekitEvent"
+ description: Immutable ordered publisher batch. sequence 1 omits predecessor_digest;
+ later batches carry the SHA-256 digest of the preceding payload. Omission
+ never deletes data.
+ FinancekitBatchReceipt:
+ type: object
+ additionalProperties: false
+ required:
+ - connection_id
+ - publisher_id
+ - generation
+ - stream_id
+ - batch_id
+ - sequence
+ - payload_digest
+ - status
+ - accepted_at
+ - applied_at
+ - error_code
+ properties:
+ connection_id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ publisher_id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ generation:
+ type: integer
+ stream_id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ batch_id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ sequence:
+ type: integer
+ payload_digest:
+ type: string
+ pattern: "^[0-9a-f]{64}$"
+ status:
+ type: string
+ enum:
+ - accepted
+ - processing
+ - applied
+ - failed
+ - revoked
+ accepted_at:
+ type: string
+ format: date-time
+ applied_at:
+ type: string
+ format: date-time
+ nullable: true
+ error_code:
+ type: string
+ nullable: true
+ FinancekitConflict:
+ type: object
+ required:
+ - id
+ - kind
+ - status
+ - details
+ - created_at
+ properties:
+ id:
+ type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ kind:
+ type: string
+ status:
+ type: string
+ enum:
+ - open
+ - resolved
+ details:
+ type: object
+ resolution:
+ type: string
+ nullable: true
+ resolved_at:
+ allOf:
+ - type: string
+ format: date-time
+ nullable: true
+ created_at:
+ type: string
+ format: date-time
+ financekit_account_lineage_id:
+ allOf:
+ - type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ nullable: true
+ financekit_transaction_id:
+ allOf:
+ - type: string
+ format: uuid
+ pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"
+ nullable: true
+ FinancekitConflictResolution:
+ type: object
+ additionalProperties: false
+ required:
+ - resolution
+ properties:
+ resolution:
+ type: string
+ description: "`keep_sure` closes the conflict without mutating the publisher
+ stream. `retry_after_repair` closes the conflict, moves the connection
+ to repair_required, revokes queued work and credentials, and requires
+ POST /repair before uploads resume."
+ enum:
+ - keep_sure
+ - retry_after_repair
+ FinancekitCapabilities:
+ type: object
+ additionalProperties: false
+ required:
+ - available
+ - protocol_versions
+ - delivery
+ - max_payload_bytes
+ - max_records
+ - max_accounts
+ - max_queued_batches
+ - transaction_statuses
+ - amount_precision
+ - amount_scale
+ properties:
+ available:
+ type: boolean
+ protocol_versions:
+ type: array
+ items:
+ type: integer
+ enum:
+ - 2
+ delivery:
+ type: string
+ enum:
+ - background_publisher
+ max_payload_bytes:
+ type: integer
+ max_records:
+ type: integer
+ max_accounts:
+ type: integer
+ max_queued_batches:
+ type: integer
+ transaction_statuses:
+ type: array
+ items:
+ type: string
+ amount_precision:
+ type: integer
+ amount_scale:
+ type: integer
+ FinancekitError:
+ type: object
+ additionalProperties: false
+ required:
+ - error
+ properties:
+ error:
+ type: string
paths:
"/api/v1/accounts":
get:
- summary: List accounts
+ summary: List accounts
+ tags:
+ - Accounts
+ security:
+ - apiKeyAuth: []
+ parameters:
+ - name: page
+ in: query
+ required: false
+ description: 'Page number (default: 1)'
+ schema:
+ type: integer
+ - name: per_page
+ in: query
+ required: false
+ description: 'Items per page (default: 25, max: 100)'
+ schema:
+ type: integer
+ - name: include_disabled
+ in: query
+ required: false
+ description: Include disabled accounts in the response. Defaults to false.
+ schema:
+ type: boolean
+ responses:
+ '200':
+ description: accounts paginated
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/AccountCollection"
+ "/api/v1/accounts/{id}":
+ parameters:
+ - name: id
+ in: path
+ required: true
+ description: Account ID
+ schema:
+ type: string
+ format: uuid
+ get:
+ summary: Retrieve an account
+ tags:
+ - Accounts
+ security:
+ - apiKeyAuth: []
+ parameters:
+ - name: include_disabled
+ in: query
+ required: false
+ description: Allow retrieving a disabled account. Defaults to false.
+ schema:
+ type: boolean
+ responses:
+ '200':
+ description: account retrieved
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/AccountDetail"
+ '401':
+ description: unauthorized
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '403':
+ description: insufficient scope
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '404':
+ description: account not found
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ "/api/v1/auth/signup":
+ post:
+ summary: Sign up a new user
+ tags:
+ - Auth
+ description: Creates a new user and family. The first user on a fresh instance
+ is assigned the super_admin role; later family creators are assigned an admin
+ role.
+ parameters: []
+ responses:
+ '201':
+ description: user created
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ access_token:
+ type: string
+ refresh_token:
+ type: string
+ token_type:
+ type: string
+ expires_in:
+ type: integer
+ created_at:
+ type: integer
+ user:
+ type: object
+ properties:
+ id:
+ type: string
+ format: uuid
+ email:
+ type: string
+ first_name:
+ type: string
+ last_name:
+ type: string
+ ui_layout:
+ type: string
+ enum:
+ - dashboard
+ - intro
+ ai_enabled:
+ type: boolean
+ '422':
+ description: validation error
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '403':
+ description: invite code required or invalid
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ user:
+ type: object
+ properties:
+ email:
+ type: string
+ format: email
+ description: User email address
+ password:
+ type: string
+ description: Password (min 8 chars, mixed case, number, special
+ char)
+ first_name:
+ type: string
+ last_name:
+ type: string
+ required:
+ - email
+ - password
+ device:
+ type: object
+ properties:
+ device_id:
+ type: string
+ description: Unique device identifier
+ device_name:
+ type: string
+ description: Human-readable device name
+ device_type:
+ type: string
+ description: Device type (e.g. ios, android)
+ os_version:
+ type: string
+ app_version:
+ type: string
+ required:
+ - device_id
+ - device_name
+ - device_type
+ - os_version
+ - app_version
+ invite_code:
+ type: string
+ nullable: true
+ description: Invite code (required when invites are enforced)
+ required:
+ - user
+ - device
+ required: true
+ "/api/v1/auth/login":
+ post:
+ summary: Log in with email and password
+ tags:
+ - Auth
+ parameters: []
+ responses:
+ '200':
+ description: login successful
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ access_token:
+ type: string
+ refresh_token:
+ type: string
+ token_type:
+ type: string
+ expires_in:
+ type: integer
+ created_at:
+ type: integer
+ user:
+ type: object
+ properties:
+ id:
+ type: string
+ format: uuid
+ email:
+ type: string
+ first_name:
+ type: string
+ last_name:
+ type: string
+ ui_layout:
+ type: string
+ enum:
+ - dashboard
+ - intro
+ ai_enabled:
+ type: boolean
+ '401':
+ description: invalid credentials, MFA required, or account deactivated
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ email:
+ type: string
+ format: email
+ password:
+ type: string
+ otp_code:
+ type: string
+ nullable: true
+ description: TOTP code if MFA is enabled
+ device:
+ type: object
+ properties:
+ device_id:
+ type: string
+ device_name:
+ type: string
+ device_type:
+ type: string
+ os_version:
+ type: string
+ app_version:
+ type: string
+ required:
+ - device_id
+ - device_name
+ - device_type
+ - os_version
+ - app_version
+ required:
+ - email
+ - password
+ - device
+ required: true
+ "/api/v1/auth/sso_exchange":
+ post:
+ summary: Exchange mobile SSO authorization code for tokens
+ tags:
+ - Auth
+ description: Exchanges a one-time authorization code (received via deep link
+ after mobile SSO) for OAuth tokens. The code is single-use and expires after
+ 5 minutes.
+ parameters: []
+ responses:
+ '200':
+ description: tokens issued
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ access_token:
+ type: string
+ refresh_token:
+ type: string
+ token_type:
+ type: string
+ expires_in:
+ type: integer
+ created_at:
+ type: integer
+ user:
+ type: object
+ properties:
+ id:
+ type: string
+ format: uuid
+ email:
+ type: string
+ first_name:
+ type: string
+ last_name:
+ type: string
+ ui_layout:
+ type: string
+ enum:
+ - dashboard
+ - intro
+ ai_enabled:
+ type: boolean
+ '401':
+ description: invalid or expired code
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ code:
+ type: string
+ description: One-time authorization code from mobile SSO callback
+ required:
+ - code
+ required: true
+ "/api/v1/auth/refresh":
+ post:
+ summary: Refresh an access token
+ tags:
+ - Auth
+ parameters: []
+ responses:
+ '200':
+ description: token refreshed
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ access_token:
+ type: string
+ refresh_token:
+ type: string
+ token_type:
+ type: string
+ expires_in:
+ type: integer
+ created_at:
+ type: integer
+ '401':
+ description: invalid or revoked refresh token, or account deactivated
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '400':
+ description: missing refresh token
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ refresh_token:
+ type: string
+ description: The refresh token from a previous login or refresh
+ device:
+ type: object
+ properties:
+ device_id:
+ type: string
+ required:
+ - device_id
+ required:
+ - refresh_token
+ - device
+ required: true
+ "/api/v1/auth/sso_link":
+ post:
+ summary: Link an existing account via SSO
+ tags:
+ - Auth
+ description: Authenticates with email/password and links the SSO identity from
+ a previously issued linking code. Creates an OidcIdentity, logs the link via
+ SsoAuditLog, and issues mobile OAuth tokens.
+ parameters: []
+ responses:
+ '200':
+ description: account linked and tokens issued
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ access_token:
+ type: string
+ refresh_token:
+ type: string
+ token_type:
+ type: string
+ expires_in:
+ type: integer
+ created_at:
+ type: integer
+ user:
+ type: object
+ properties:
+ id:
+ type: string
+ format: uuid
+ email:
+ type: string
+ first_name:
+ type: string
+ last_name:
+ type: string
+ ui_layout:
+ type: string
+ enum:
+ - dashboard
+ - intro
+ ai_enabled:
+ type: boolean
+ '400':
+ description: missing linking code
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '401':
+ description: invalid credentials, expired linking code, or account deactivated
+ content:
+ application/json:
+ schema:
+ oneOf:
+ - "$ref": "#/components/schemas/ErrorResponse"
+ - "$ref": "#/components/schemas/MfaRequiredResponse"
+ '403':
+ description: SSO identity removed by an administrator
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ linking_code:
+ type: string
+ description: One-time linking code from mobile SSO onboarding redirect
+ email:
+ type: string
+ format: email
+ description: Email of the existing account to link
+ password:
+ type: string
+ description: Password for the existing account
+ required:
+ - linking_code
+ - email
+ - password
+ required: true
+ "/api/v1/auth/sso_create_account":
+ post:
+ summary: Create a new account via SSO
+ tags:
+ - Auth
+ description: Creates a new user and family from a previously issued linking
+ code. Links the SSO identity via OidcIdentity, logs the JIT account creation
+ via SsoAuditLog, and issues mobile OAuth tokens. The linking code must have
+ allow_account_creation enabled. The first user on a fresh instance is assigned
+ the super_admin role; later family creators are assigned an admin-capable
+ role.
+ parameters: []
+ responses:
+ '200':
+ description: account created and tokens issued
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ access_token:
+ type: string
+ refresh_token:
+ type: string
+ token_type:
+ type: string
+ expires_in:
+ type: integer
+ created_at:
+ type: integer
+ user:
+ type: object
+ properties:
+ id:
+ type: string
+ format: uuid
+ email:
+ type: string
+ first_name:
+ type: string
+ last_name:
+ type: string
+ ui_layout:
+ type: string
+ enum:
+ - dashboard
+ - intro
+ ai_enabled:
+ type: boolean
+ '400':
+ description: missing linking code
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '401':
+ description: invalid or expired linking code
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '403':
+ description: SSO identity removed or account creation disabled
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '422':
+ description: user validation error
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ errors:
+ type: array
+ items:
+ type: string
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ linking_code:
+ type: string
+ description: One-time linking code from mobile SSO onboarding redirect
+ first_name:
+ type: string
+ description: First name (overrides value from SSO provider if provided)
+ last_name:
+ type: string
+ description: Last name (overrides value from SSO provider if provided)
+ required:
+ - linking_code
+ required: true
+ "/api/v1/auth/enable_ai":
+ patch:
+ summary: Enable AI features for the authenticated user
+ tags:
+ - Auth
+ security:
+ - apiKeyAuth: []
+ responses:
+ '200':
+ description: ai enabled
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ user:
+ type: object
+ properties:
+ id:
+ type: string
+ format: uuid
+ email:
+ type: string
+ first_name:
+ type: string
+ nullable: true
+ last_name:
+ type: string
+ nullable: true
+ ui_layout:
+ type: string
+ enum:
+ - dashboard
+ - intro
+ ai_enabled:
+ type: boolean
+ '401':
+ description: unauthorized
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '403':
+ description: insufficient scope
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ "/api/v1/balance_sheet":
+ get:
+ summary: Show balance sheet
+ tags:
+ - Balance Sheet
+ description: Returns the family balance sheet including net worth, total assets,
+ and total liabilities with amounts converted to the family's primary currency.
+ security:
+ - apiKeyAuth: []
+ responses:
+ '200':
+ description: balance sheet returned
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/BalanceSheet"
+ '401':
+ description: unauthorized
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ "/api/v1/balances":
+ get:
+ summary: List balance history records
+ tags:
+ - Balances
+ security:
+ - apiKeyAuth: []
+ parameters:
+ - name: page
+ in: query
+ required: false
+ description: 'Page number (default: 1)'
+ schema:
+ type: integer
+ - name: per_page
+ in: query
+ required: false
+ description: 'Items per page (default: 25, max: 100)'
+ schema:
+ type: integer
+ - name: account_id
+ in: query
+ required: false
+ description: Filter by account ID
+ schema:
+ type: string
+ format: uuid
+ - name: currency
+ in: query
+ required: false
+ description: Filter by currency code
+ schema:
+ type: string
+ - name: start_date
+ in: query
+ required: false
+ description: Filter balances from this date
+ schema:
+ type: string
+ format: date
+ - name: end_date
+ in: query
+ required: false
+ description: Filter balances until this date
+ schema:
+ type: string
+ format: date
+ responses:
+ '200':
+ description: balances listed
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/BalanceCollection"
+ '401':
+ description: unauthorized
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '403':
+ description: insufficient scope
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '422':
+ description: invalid filter
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ "/api/v1/balances/{id}":
+ parameters:
+ - name: id
+ in: path
+ required: true
+ description: Balance ID
+ schema:
+ type: string
+ format: uuid
+ get:
+ summary: Retrieve a balance history record
+ tags:
+ - Balances
+ security:
+ - apiKeyAuth: []
+ responses:
+ '200':
+ description: balance retrieved
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/Balance"
+ '401':
+ description: unauthorized
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '403':
+ description: insufficient scope
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '404':
+ description: balance not found
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ "/api/v1/budget_categories":
+ get:
+ summary: List budget categories
+ tags:
+ - Budget Categories
+ security:
+ - apiKeyAuth: []
+ parameters:
+ - name: page
+ in: query
+ required: false
+ description: 'Page number (default: 1)'
+ schema:
+ type: integer
+ - name: per_page
+ in: query
+ required: false
+ description: 'Items per page (default: 25, max: 100)'
+ schema:
+ type: integer
+ - name: budget_id
+ in: query
+ required: false
+ schema:
+ type: string
+ format: uuid
+ description: Filter by budget ID
+ - name: category_id
+ in: query
+ required: false
+ schema:
+ type: string
+ format: uuid
+ description: Filter by category ID
+ - name: start_date
+ in: query
+ required: false
+ schema:
+ type: string
+ format: date
+ description: Filter budget categories whose budget starts on or after this
+ date
+ - name: end_date
+ in: query
+ required: false
+ schema:
+ type: string
+ format: date
+ description: Filter budget categories whose budget ends on or before this
+ date
+ responses:
+ '200':
+ description: budget categories listed
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/BudgetCategoryCollection"
+ '401':
+ description: unauthorized
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '403':
+ description: insufficient scope
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '422':
+ description: invalid filter
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ "/api/v1/budget_categories/{id}":
+ parameters:
+ - name: id
+ in: path
+ required: true
+ description: Budget category ID
+ schema:
+ type: string
+ format: uuid
+ get:
+ summary: Retrieve a budget category
tags:
- - Accounts
+ - Budget Categories
+ security:
+ - apiKeyAuth: []
+ responses:
+ '200':
+ description: budget category retrieved
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/BudgetCategory"
+ '401':
+ description: unauthorized
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '403':
+ description: insufficient scope
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '404':
+ description: budget category not found
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ "/api/v1/budgets":
+ get:
+ summary: List budgets
+ tags:
+ - Budgets
security:
- apiKeyAuth: []
parameters:
@@ -3646,48 +5354,67 @@ paths:
description: 'Items per page (default: 25, max: 100)'
schema:
type: integer
- - name: include_disabled
+ - name: start_date
in: query
required: false
- description: Include disabled accounts in the response. Defaults to false.
schema:
- type: boolean
+ type: string
+ format: date
+ description: Filter budgets starting on or after this date
+ - name: end_date
+ in: query
+ required: false
+ schema:
+ type: string
+ format: date
+ description: Filter budgets ending on or before this date
responses:
'200':
- description: accounts paginated
+ description: budgets listed
content:
application/json:
schema:
- "$ref": "#/components/schemas/AccountCollection"
- "/api/v1/accounts/{id}":
+ "$ref": "#/components/schemas/BudgetCollection"
+ '401':
+ description: unauthorized
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '403':
+ description: insufficient scope
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '422':
+ description: invalid date filter
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ "/api/v1/budgets/{id}":
parameters:
- name: id
in: path
required: true
- description: Account ID
+ description: Budget ID
schema:
type: string
format: uuid
get:
- summary: Retrieve an account
+ summary: Retrieve a budget
tags:
- - Accounts
+ - Budgets
security:
- apiKeyAuth: []
- parameters:
- - name: include_disabled
- in: query
- required: false
- description: Allow retrieving a disabled account. Defaults to false.
- schema:
- type: boolean
responses:
'200':
- description: account retrieved
+ description: budget retrieved
content:
application/json:
schema:
- "$ref": "#/components/schemas/AccountDetail"
+ "$ref": "#/components/schemas/Budget"
'401':
description: unauthorized
content:
@@ -3701,65 +5428,160 @@ paths:
schema:
"$ref": "#/components/schemas/ErrorResponse"
'404':
- description: account not found
+ description: budget not found
content:
application/json:
schema:
"$ref": "#/components/schemas/ErrorResponse"
- "/api/v1/auth/signup":
+ "/api/v1/cash_flow":
+ get:
+ summary: Show cash flow and optional Sankey graph
+ tags:
+ - Cash Flow
+ description: Server-calculated income, spending, savings, and daily cumulative
+ comparison in family currency. Uses the authenticated user’s finance accounts
+ and Sure reporting rules. Browser sessions do not authenticate this public
+ API.
+ parameters:
+ - name: month
+ in: query
+ required: false
+ schema:
+ type: string
+ format: date
+ description: Non-future first day YYYY-MM-01; defaults to the current month
+ in the family time zone.
+ - name: include
+ in: query
+ required: false
+ schema:
+ type: string
+ enum:
+ - sankey
+ description: Append server-calculated graph to the monthly summary; cannot
+ combine with view.
+ - name: view
+ in: query
+ required: false
+ schema:
+ type: string
+ enum:
+ - sankey
+ description: Graph-only envelope; omits daily comparison. Accepts month or
+ an explicit date range; cannot combine with include.
+ - name: start_date
+ in: query
+ required: false
+ schema:
+ type: string
+ format: date
+ description: Inclusive ISO date. Requires end_date and view=sankey; cannot
+ combine with month.
+ - name: end_date
+ in: query
+ required: false
+ schema:
+ type: string
+ format: date
+ description: Inclusive ISO date at or after start_date. Explicit ranges preserve
+ their bounds, including future dates.
+ security:
+ - apiKeyAuth: []
+ responses:
+ '200':
+ description: summary returned
+ content:
+ application/json:
+ schema:
+ anyOf:
+ - "$ref": "#/components/schemas/CashFlow"
+ - "$ref": "#/components/schemas/CashFlowGraph"
+ '422':
+ description: invalid query
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '401':
+ description: unauthorized
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ "/api/v1/categories":
+ get:
+ summary: List categories
+ tags:
+ - Categories
+ security:
+ - apiKeyAuth: []
+ parameters:
+ - name: page
+ in: query
+ required: false
+ description: 'Page number (default: 1)'
+ schema:
+ type: integer
+ - name: per_page
+ in: query
+ required: false
+ description: 'Items per page (default: 25, max: 100)'
+ schema:
+ type: integer
+ - name: roots_only
+ in: query
+ required: false
+ description: Return only root categories (no parent)
+ schema:
+ type: boolean
+ - name: parent_id
+ in: query
+ required: false
+ description: Filter by parent category ID
+ schema:
+ type: string
+ format: uuid
+ responses:
+ '200':
+ description: categories filtered by parent
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/CategoryCollection"
post:
- summary: Sign up a new user
+ summary: Create category
tags:
- - Auth
- description: Creates a new user and family. The first user on a fresh instance
- is assigned the super_admin role; later family creators are assigned an admin
- role.
+ - Categories
+ security:
+ - apiKeyAuth: []
parameters: []
responses:
'201':
- description: user created
+ description: subcategory created with parent
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/CategoryDetail"
+ '422':
+ description: validation error - duplicate name
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '403':
+ description: forbidden - api key missing read_write scope
content:
application/json:
schema:
- type: object
- properties:
- access_token:
- type: string
- refresh_token:
- type: string
- token_type:
- type: string
- expires_in:
- type: integer
- created_at:
- type: integer
- user:
- type: object
- properties:
- id:
- type: string
- format: uuid
- email:
- type: string
- first_name:
- type: string
- last_name:
- type: string
- ui_layout:
- type: string
- enum:
- - dashboard
- - intro
- ai_enabled:
- type: boolean
- '422':
- description: validation error
+ "$ref": "#/components/schemas/ErrorResponse"
+ '400':
+ description: bad request - missing category payload
content:
application/json:
schema:
"$ref": "#/components/schemas/ErrorResponse"
- '403':
- description: invite code required or invalid
+ '401':
+ description: unauthorized - missing api key
content:
application/json:
schema:
@@ -3768,192 +5590,71 @@ paths:
content:
application/json:
schema:
- type: object
- properties:
- user:
- type: object
- properties:
- email:
- type: string
- format: email
- description: User email address
- password:
- type: string
- description: Password (min 8 chars, mixed case, number, special
- char)
- first_name:
- type: string
- last_name:
- type: string
- required:
- - email
- - password
- device:
- type: object
- properties:
- device_id:
- type: string
- description: Unique device identifier
- device_name:
- type: string
- description: Human-readable device name
- device_type:
- type: string
- description: Device type (e.g. ios, android)
- os_version:
- type: string
- app_version:
- type: string
- required:
- - device_id
- - device_name
- - device_type
- - os_version
- - app_version
- invite_code:
- type: string
- nullable: true
- description: Invite code (required when invites are enforced)
- required:
- - user
- - device
+ "$ref": "#/components/schemas/CategoryCreateRequest"
required: true
- "/api/v1/auth/login":
- post:
- summary: Log in with email and password
+ "/api/v1/categories/{id}":
+ parameters:
+ - name: id
+ in: path
+ required: true
+ description: Category ID
+ schema:
+ type: string
+ get:
+ summary: Retrieve a category
tags:
- - Auth
- parameters: []
+ - Categories
+ security:
+ - apiKeyAuth: []
responses:
'200':
- description: login successful
+ description: subcategory retrieved with parent
content:
application/json:
schema:
- type: object
- properties:
- access_token:
- type: string
- refresh_token:
- type: string
- token_type:
- type: string
- expires_in:
- type: integer
- created_at:
- type: integer
- user:
- type: object
- properties:
- id:
- type: string
- format: uuid
- email:
- type: string
- first_name:
- type: string
- last_name:
- type: string
- ui_layout:
- type: string
- enum:
- - dashboard
- - intro
- ai_enabled:
- type: boolean
- '401':
- description: invalid credentials, MFA required, or account deactivated
+ "$ref": "#/components/schemas/CategoryDetail"
+ '404':
+ description: category not found
content:
application/json:
schema:
"$ref": "#/components/schemas/ErrorResponse"
- requestBody:
- content:
- application/json:
- schema:
- type: object
- properties:
- email:
- type: string
- format: email
- password:
- type: string
- otp_code:
- type: string
- nullable: true
- description: TOTP code if MFA is enabled
- device:
- type: object
- properties:
- device_id:
- type: string
- device_name:
- type: string
- device_type:
- type: string
- os_version:
- type: string
- app_version:
- type: string
- required:
- - device_id
- - device_name
- - device_type
- - os_version
- - app_version
- required:
- - email
- - password
- - device
- required: true
- "/api/v1/auth/sso_exchange":
- post:
- summary: Exchange mobile SSO authorization code for tokens
+ "/api/v1/chats":
+ get:
+ summary: List chats
tags:
- - Auth
- description: Exchanges a one-time authorization code (received via deep link
- after mobile SSO) for OAuth tokens. The code is single-use and expires after
- 5 minutes.
- parameters: []
+ - Chats
+ security:
+ - apiKeyAuth: []
responses:
'200':
- description: tokens issued
+ description: chats listed
content:
application/json:
schema:
- type: object
- properties:
- access_token:
- type: string
- refresh_token:
- type: string
- token_type:
- type: string
- expires_in:
- type: integer
- created_at:
- type: integer
- user:
- type: object
- properties:
- id:
- type: string
- format: uuid
- email:
- type: string
- first_name:
- type: string
- last_name:
- type: string
- ui_layout:
- type: string
- enum:
- - dashboard
- - intro
- ai_enabled:
- type: boolean
- '401':
- description: invalid or expired code
+ "$ref": "#/components/schemas/ChatCollection"
+ '403':
+ description: AI features disabled
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ post:
+ summary: Create chat
+ tags:
+ - Chats
+ security:
+ - apiKeyAuth: []
+ parameters: []
+ responses:
+ '201':
+ description: chat created
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ChatDetail"
+ '422':
+ description: validation error
content:
application/json:
schema:
@@ -3964,44 +5665,67 @@ paths:
schema:
type: object
properties:
- code:
+ title:
type: string
- description: One-time authorization code from mobile SSO callback
+ example: Monthly budget review
+ message:
+ type: string
+ description: Optional initial message in the chat
+ model:
+ type: string
+ description: Optional OpenAI model identifier
required:
- - code
+ - title
required: true
- "/api/v1/auth/refresh":
- post:
- summary: Refresh an access token
+ "/api/v1/chats/{id}":
+ parameters:
+ - name: id
+ in: path
+ required: true
+ description: Chat ID
+ schema:
+ type: string
+ get:
+ summary: Retrieve a chat
tags:
- - Auth
+ - Chats
+ security:
+ - apiKeyAuth: []
+ responses:
+ '200':
+ description: chat retrieved
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ChatDetail"
+ '404':
+ description: chat not found
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ patch:
+ summary: Update a chat
+ tags:
+ - Chats
+ security:
+ - apiKeyAuth: []
parameters: []
responses:
'200':
- description: token refreshed
+ description: chat updated
content:
application/json:
schema:
- type: object
- properties:
- access_token:
- type: string
- refresh_token:
- type: string
- token_type:
- type: string
- expires_in:
- type: integer
- created_at:
- type: integer
- '401':
- description: invalid or revoked refresh token, or account deactivated
+ "$ref": "#/components/schemas/ChatDetail"
+ '404':
+ description: chat not found
content:
application/json:
schema:
"$ref": "#/components/schemas/ErrorResponse"
- '400':
- description: missing refresh token
+ '422':
+ description: validation error
content:
application/json:
schema:
@@ -4012,82 +5736,51 @@ paths:
schema:
type: object
properties:
- refresh_token:
+ title:
type: string
- description: The refresh token from a previous login or refresh
- device:
- type: object
- properties:
- device_id:
- type: string
- required:
- - device_id
- required:
- - refresh_token
- - device
+ example: Updated chat title
required: true
- "/api/v1/auth/sso_link":
+ delete:
+ summary: Delete a chat
+ tags:
+ - Chats
+ security:
+ - apiKeyAuth: []
+ responses:
+ '204':
+ description: chat deleted
+ '404':
+ description: chat not found
+ "/api/v1/chats/{chat_id}/messages":
+ parameters:
+ - name: chat_id
+ in: path
+ required: true
+ description: Chat ID
+ schema:
+ type: string
post:
- summary: Link an existing account via SSO
+ summary: Create a message
tags:
- - Auth
- description: Authenticates with email/password and links the SSO identity from
- a previously issued linking code. Creates an OidcIdentity, logs the link via
- SsoAuditLog, and issues mobile OAuth tokens.
+ - Chat Messages
+ security:
+ - apiKeyAuth: []
parameters: []
responses:
- '200':
- description: account linked and tokens issued
+ '201':
+ description: message created
content:
application/json:
schema:
- type: object
- properties:
- access_token:
- type: string
- refresh_token:
- type: string
- token_type:
- type: string
- expires_in:
- type: integer
- created_at:
- type: integer
- user:
- type: object
- properties:
- id:
- type: string
- format: uuid
- email:
- type: string
- first_name:
- type: string
- last_name:
- type: string
- ui_layout:
- type: string
- enum:
- - dashboard
- - intro
- ai_enabled:
- type: boolean
- '400':
- description: missing linking code
+ "$ref": "#/components/schemas/MessageResponse"
+ '404':
+ description: chat not found
content:
application/json:
schema:
"$ref": "#/components/schemas/ErrorResponse"
- '401':
- description: invalid credentials, expired linking code, or account deactivated
- content:
- application/json:
- schema:
- oneOf:
- - "$ref": "#/components/schemas/ErrorResponse"
- - "$ref": "#/components/schemas/MfaRequiredResponse"
- '403':
- description: SSO identity removed by an administrator
+ '422':
+ description: validation error
content:
application/json:
schema:
@@ -4098,153 +5791,73 @@ paths:
schema:
type: object
properties:
- linking_code:
- type: string
- description: One-time linking code from mobile SSO onboarding redirect
- email:
+ content:
type: string
- format: email
- description: Email of the existing account to link
- password:
+ model:
type: string
- description: Password for the existing account
required:
- - linking_code
- - email
- - password
+ - content
required: true
- "/api/v1/auth/sso_create_account":
+ "/api/v1/chats/{chat_id}/messages/retry":
+ parameters:
+ - name: chat_id
+ in: path
+ required: true
+ description: Chat ID
+ schema:
+ type: string
post:
- summary: Create a new account via SSO
+ summary: Retry the last assistant response
tags:
- - Auth
- description: Creates a new user and family from a previously issued linking
- code. Links the SSO identity via OidcIdentity, logs the JIT account creation
- via SsoAuditLog, and issues mobile OAuth tokens. The linking code must have
- allow_account_creation enabled. The first user on a fresh instance is assigned
- the super_admin role; later family creators are assigned an admin-capable
- role.
- parameters: []
+ - Chat Messages
+ security:
+ - apiKeyAuth: []
responses:
- '200':
- description: account created and tokens issued
- content:
- application/json:
- schema:
- type: object
- properties:
- access_token:
- type: string
- refresh_token:
- type: string
- token_type:
- type: string
- expires_in:
- type: integer
- created_at:
- type: integer
- user:
- type: object
- properties:
- id:
- type: string
- format: uuid
- email:
- type: string
- first_name:
- type: string
- last_name:
- type: string
- ui_layout:
- type: string
- enum:
- - dashboard
- - intro
- ai_enabled:
- type: boolean
- '400':
- description: missing linking code
- content:
- application/json:
- schema:
- "$ref": "#/components/schemas/ErrorResponse"
- '401':
- description: invalid or expired linking code
+ '202':
+ description: retry started
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
- '403':
- description: SSO identity removed or account creation disabled
+ "$ref": "#/components/schemas/RetryResponse"
+ '404':
+ description: chat not found
content:
application/json:
schema:
"$ref": "#/components/schemas/ErrorResponse"
'422':
- description: user validation error
+ description: no assistant message available
content:
application/json:
schema:
- type: object
- properties:
- errors:
- type: array
- items:
- type: string
- requestBody:
- content:
- application/json:
- schema:
- type: object
- properties:
- linking_code:
- type: string
- description: One-time linking code from mobile SSO onboarding redirect
- first_name:
- type: string
- description: First name (overrides value from SSO provider if provided)
- last_name:
- type: string
- description: Last name (overrides value from SSO provider if provided)
- required:
- - linking_code
- required: true
- "/api/v1/auth/enable_ai":
- patch:
- summary: Enable AI features for the authenticated user
+ "$ref": "#/components/schemas/ErrorResponse"
+ "/api/v1/family_exports":
+ get:
+ summary: Lists family exports
tags:
- - Auth
+ - Family Exports
security:
- apiKeyAuth: []
+ parameters:
+ - name: page
+ in: query
+ required: false
+ description: 'Page number (default: 1)'
+ schema:
+ type: integer
+ - name: per_page
+ in: query
+ required: false
+ description: 'Items per page (default: 25, max: 100)'
+ schema:
+ type: integer
responses:
'200':
- description: ai enabled
+ description: family exports listed
content:
application/json:
schema:
- type: object
- properties:
- user:
- type: object
- properties:
- id:
- type: string
- format: uuid
- email:
- type: string
- first_name:
- type: string
- nullable: true
- last_name:
- type: string
- nullable: true
- ui_layout:
- type: string
- enum:
- - dashboard
- - intro
- ai_enabled:
- type: boolean
+ "$ref": "#/components/schemas/FamilyExportCollection"
'401':
description: unauthorized
content:
@@ -4252,87 +5865,71 @@ paths:
schema:
"$ref": "#/components/schemas/ErrorResponse"
'403':
- description: insufficient scope
+ description: forbidden
content:
application/json:
schema:
"$ref": "#/components/schemas/ErrorResponse"
- "/api/v1/balance_sheet":
- get:
- summary: Show balance sheet
+ post:
+ summary: Queues a family export
tags:
- - Balance Sheet
- description: Returns the family balance sheet including net worth, total assets,
- and total liabilities with amounts converted to the family's primary currency.
+ - Family Exports
security:
- apiKeyAuth: []
+ parameters: []
responses:
- '200':
- description: balance sheet returned
+ '202':
+ description: family export queued
content:
application/json:
schema:
- "$ref": "#/components/schemas/BalanceSheet"
+ "$ref": "#/components/schemas/FamilyExportResponse"
'401':
description: unauthorized
content:
application/json:
schema:
"$ref": "#/components/schemas/ErrorResponse"
- "/api/v1/balances":
+ '403':
+ description: forbidden
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '422':
+ description: invalid params
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ additionalProperties: false
+ description: Family export creation does not accept request parameters.
+ "/api/v1/family_exports/{id}":
+ parameters:
+ - name: id
+ in: path
+ format: uuid
+ required: true
+ schema:
+ type: string
get:
- summary: List balance history records
+ summary: Shows a family export
tags:
- - Balances
+ - Family Exports
security:
- apiKeyAuth: []
- parameters:
- - name: page
- in: query
- required: false
- description: 'Page number (default: 1)'
- schema:
- type: integer
- - name: per_page
- in: query
- required: false
- description: 'Items per page (default: 25, max: 100)'
- schema:
- type: integer
- - name: account_id
- in: query
- required: false
- description: Filter by account ID
- schema:
- type: string
- format: uuid
- - name: currency
- in: query
- required: false
- description: Filter by currency code
- schema:
- type: string
- - name: start_date
- in: query
- required: false
- description: Filter balances from this date
- schema:
- type: string
- format: date
- - name: end_date
- in: query
- required: false
- description: Filter balances until this date
- schema:
- type: string
- format: date
responses:
'200':
- description: balances listed
+ description: family export shown
content:
application/json:
schema:
- "$ref": "#/components/schemas/BalanceCollection"
+ "$ref": "#/components/schemas/FamilyExportResponse"
'401':
description: unauthorized
content:
@@ -4340,39 +5937,34 @@ paths:
schema:
"$ref": "#/components/schemas/ErrorResponse"
'403':
- description: insufficient scope
+ description: forbidden
content:
application/json:
schema:
"$ref": "#/components/schemas/ErrorResponse"
- '422':
- description: invalid filter
+ '404':
+ description: not found
content:
application/json:
schema:
"$ref": "#/components/schemas/ErrorResponse"
- "/api/v1/balances/{id}":
+ "/api/v1/family_exports/{id}/download":
parameters:
- name: id
in: path
+ format: uuid
required: true
- description: Balance ID
schema:
type: string
- format: uuid
get:
- summary: Retrieve a balance history record
+ summary: Downloads a completed family export
tags:
- - Balances
+ - Family Exports
security:
- apiKeyAuth: []
responses:
- '200':
- description: balance retrieved
- content:
- application/json:
- schema:
- "$ref": "#/components/schemas/Balance"
+ '302':
+ description: family export download redirected
'401':
description: unauthorized
content:
@@ -4380,74 +5972,38 @@ paths:
schema:
"$ref": "#/components/schemas/ErrorResponse"
'403':
- description: insufficient scope
+ description: forbidden
content:
application/json:
schema:
"$ref": "#/components/schemas/ErrorResponse"
'404':
- description: balance not found
+ description: not found
content:
application/json:
schema:
"$ref": "#/components/schemas/ErrorResponse"
- "/api/v1/budget_categories":
+ '409':
+ description: export not ready
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ "/api/v1/family_settings":
get:
- summary: List budget categories
+ summary: Retrieve family settings
+ description: Retrieve a read-only snapshot of non-secret family configuration.
tags:
- - Budget Categories
+ - Family Settings
security:
- apiKeyAuth: []
- parameters:
- - name: page
- in: query
- required: false
- description: 'Page number (default: 1)'
- schema:
- type: integer
- - name: per_page
- in: query
- required: false
- description: 'Items per page (default: 25, max: 100)'
- schema:
- type: integer
- - name: budget_id
- in: query
- required: false
- schema:
- type: string
- format: uuid
- description: Filter by budget ID
- - name: category_id
- in: query
- required: false
- schema:
- type: string
- format: uuid
- description: Filter by category ID
- - name: start_date
- in: query
- required: false
- schema:
- type: string
- format: date
- description: Filter budget categories whose budget starts on or after this
- date
- - name: end_date
- in: query
- required: false
- schema:
- type: string
- format: date
- description: Filter budget categories whose budget ends on or before this
- date
responses:
'200':
- description: budget categories listed
+ description: family settings retrieved
content:
application/json:
schema:
- "$ref": "#/components/schemas/BudgetCategoryCollection"
+ "$ref": "#/components/schemas/FamilySettings"
'401':
description: unauthorized
content:
@@ -4460,734 +6016,1015 @@ paths:
application/json:
schema:
"$ref": "#/components/schemas/ErrorResponse"
- '422':
- description: invalid filter
- content:
- application/json:
- schema:
- "$ref": "#/components/schemas/ErrorResponse"
- "/api/v1/budget_categories/{id}":
- parameters:
- - name: id
- in: path
- required: true
- description: Budget category ID
- schema:
- type: string
- format: uuid
+ "/api/v1/financekit/capabilities":
get:
- summary: Retrieve a budget category
+ summary: Discover FinanceKit background publisher support
tags:
- - Budget Categories
+ - FinanceKit
security:
- apiKeyAuth: []
+ - oauth2:
+ - read
responses:
'200':
- description: budget category retrieved
+ description: Publisher limits and protocol versions
content:
application/json:
schema:
- "$ref": "#/components/schemas/BudgetCategory"
+ "$ref": "#/components/schemas/FinancekitCapabilities"
+ '400':
+ description: Malformed or unsupported protocol
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
'401':
- description: unauthorized
+ description: Invalid or missing authentication
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
+ "$ref": "#/components/schemas/FinancekitError"
'403':
- description: insufficient scope
+ description: Insufficient permission or publisher eligibility
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
+ "$ref": "#/components/schemas/FinancekitError"
'404':
- description: budget category not found
+ description: Resource not found
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
- "/api/v1/budgets":
- get:
- summary: List budgets
- tags:
- - Budgets
- security:
- - apiKeyAuth: []
- parameters:
- - name: page
- in: query
- required: false
- description: 'Page number (default: 1)'
- schema:
- type: integer
- - name: per_page
- in: query
- required: false
- description: 'Items per page (default: 25, max: 100)'
- schema:
- type: integer
- - name: start_date
- in: query
- required: false
- schema:
- type: string
- format: date
- description: Filter budgets starting on or after this date
- - name: end_date
- in: query
- required: false
- schema:
- type: string
- format: date
- description: Filter budgets ending on or before this date
- responses:
- '200':
- description: budgets listed
+ "$ref": "#/components/schemas/FinancekitError"
+ '409':
+ description: Enrollment, mapping, lineage, generation, or stream conflict
content:
application/json:
schema:
- "$ref": "#/components/schemas/BudgetCollection"
- '401':
- description: unauthorized
+ "$ref": "#/components/schemas/FinancekitError"
+ '413':
+ description: Payload or record limit exceeded
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
- '403':
- description: insufficient scope
+ "$ref": "#/components/schemas/FinancekitError"
+ '422':
+ description: Invalid typed record or consent
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
- '422':
- description: invalid date filter
+ "$ref": "#/components/schemas/FinancekitError"
+ '429':
+ description: Rate limited or publisher inbox full
+ headers:
+ Retry-After:
+ schema:
+ type: integer
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
- "/api/v1/budgets/{id}":
- parameters:
- - name: id
- in: path
- required: true
- description: Budget ID
- schema:
- type: string
- format: uuid
- get:
- summary: Retrieve a budget
+ "$ref": "#/components/schemas/FinancekitError"
+ '503':
+ description: Feature unavailable
+ headers:
+ Retry-After:
+ schema:
+ type: integer
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ "/api/v1/financekit/connections":
+ post:
+ summary: Enroll a FinanceKit device publisher
tags:
- - Budgets
+ - FinanceKit
security:
- apiKeyAuth: []
+ - oauth2:
+ - read_write
+ parameters: []
responses:
- '200':
- description: budget retrieved
+ '201':
+ description: Publisher enrolled pending account mapping
content:
application/json:
schema:
- "$ref": "#/components/schemas/Budget"
+ "$ref": "#/components/schemas/FinancekitConnection"
+ '400':
+ description: Malformed or unsupported protocol
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
'401':
- description: unauthorized
+ description: Invalid or missing authentication
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
+ "$ref": "#/components/schemas/FinancekitError"
'403':
- description: insufficient scope
+ description: Insufficient permission or publisher eligibility
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
+ "$ref": "#/components/schemas/FinancekitError"
'404':
- description: budget not found
+ description: Resource not found
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
- "/api/v1/cash_flow":
- get:
- summary: Show cash flow and optional Sankey graph
- tags:
- - Cash Flow
- description: Server-calculated income, spending, savings, and daily cumulative
- comparison in family currency. Uses the authenticated user’s finance accounts
- and Sure reporting rules. Browser sessions do not authenticate this public
- API.
- parameters:
- - name: month
- in: query
- required: false
- schema:
- type: string
- format: date
- description: Non-future first day YYYY-MM-01; defaults to the current month
- in the family time zone.
- - name: include
- in: query
- required: false
- schema:
- type: string
- enum:
- - sankey
- description: Append server-calculated graph to the monthly summary; cannot
- combine with view.
- - name: view
- in: query
- required: false
- schema:
- type: string
- enum:
- - sankey
- description: Graph-only envelope; omits daily comparison. Accepts month or
- an explicit date range; cannot combine with include.
- - name: start_date
- in: query
- required: false
- schema:
- type: string
- format: date
- description: Inclusive ISO date. Requires end_date and view=sankey; cannot
- combine with month.
- - name: end_date
- in: query
- required: false
- schema:
- type: string
- format: date
- description: Inclusive ISO date at or after start_date. Explicit ranges preserve
- their bounds, including future dates.
- security:
- - apiKeyAuth: []
- responses:
- '200':
- description: summary returned
+ "$ref": "#/components/schemas/FinancekitError"
+ '409':
+ description: Enrollment, mapping, lineage, generation, or stream conflict
content:
application/json:
schema:
- anyOf:
- - "$ref": "#/components/schemas/CashFlow"
- - "$ref": "#/components/schemas/CashFlowGraph"
+ "$ref": "#/components/schemas/FinancekitError"
+ '413':
+ description: Payload or record limit exceeded
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
'422':
- description: invalid query
+ description: Invalid typed record or consent
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
- '401':
- description: unauthorized
+ "$ref": "#/components/schemas/FinancekitError"
+ '429':
+ description: Rate limited or publisher inbox full
+ headers:
+ Retry-After:
+ schema:
+ type: integer
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
- "/api/v1/categories":
+ "$ref": "#/components/schemas/FinancekitError"
+ '503':
+ description: Feature unavailable
+ headers:
+ Retry-After:
+ schema:
+ type: integer
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ requestBody:
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitEnrollment"
+ required: true
+ "/api/v1/financekit/connections/{id}":
+ parameters:
+ - name: id
+ in: path
+ required: true
+ schema:
+ type: string
+ format: uuid
get:
- summary: List categories
+ summary: Read publisher health and paginated mappings
tags:
- - Categories
+ - FinanceKit
security:
- apiKeyAuth: []
+ - oauth2:
+ - read
parameters:
- name: page
in: query
- required: false
- description: 'Page number (default: 1)'
schema:
type: integer
- name: per_page
in: query
- required: false
- description: 'Items per page (default: 25, max: 100)'
schema:
type: integer
- - name: roots_only
- in: query
- required: false
- description: Return only root categories (no parent)
- schema:
- type: boolean
- - name: parent_id
- in: query
- required: false
- description: Filter by parent category ID
- schema:
- type: string
- format: uuid
responses:
'200':
- description: categories filtered by parent
+ description: Publisher health
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitConnection"
+ '400':
+ description: Malformed or unsupported protocol
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ '401':
+ description: Invalid or missing authentication
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ '403':
+ description: Insufficient permission or publisher eligibility
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ '404':
+ description: Resource not found
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ '409':
+ description: Enrollment, mapping, lineage, generation, or stream conflict
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ '413':
+ description: Payload or record limit exceeded
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ '422':
+ description: Invalid typed record or consent
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ '429':
+ description: Rate limited or publisher inbox full
+ headers:
+ Retry-After:
+ schema:
+ type: integer
content:
application/json:
schema:
- "$ref": "#/components/schemas/CategoryCollection"
- post:
- summary: Create category
+ "$ref": "#/components/schemas/FinancekitError"
+ '503':
+ description: Feature unavailable
+ headers:
+ Retry-After:
+ schema:
+ type: integer
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ delete:
+ summary: Revoke a publisher and retain imported financial history
tags:
- - Categories
+ - FinanceKit
security:
- apiKeyAuth: []
- parameters: []
+ - oauth2:
+ - read_write
responses:
- '201':
- description: subcategory created with parent
+ '204':
+ description: Publisher revoked
+ '400':
+ description: Malformed or unsupported protocol
content:
application/json:
schema:
- "$ref": "#/components/schemas/CategoryDetail"
- '422':
- description: validation error - duplicate name
+ "$ref": "#/components/schemas/FinancekitError"
+ '401':
+ description: Invalid or missing authentication
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
+ "$ref": "#/components/schemas/FinancekitError"
'403':
- description: forbidden - api key missing read_write scope
+ description: Insufficient permission or publisher eligibility
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
- '400':
- description: bad request - missing category payload
+ "$ref": "#/components/schemas/FinancekitError"
+ '404':
+ description: Resource not found
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
- '401':
- description: unauthorized - missing api key
+ "$ref": "#/components/schemas/FinancekitError"
+ '409':
+ description: Enrollment, mapping, lineage, generation, or stream conflict
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
- requestBody:
- content:
- application/json:
- schema:
- "$ref": "#/components/schemas/CategoryCreateRequest"
- required: true
- "/api/v1/categories/{id}":
+ "$ref": "#/components/schemas/FinancekitError"
+ '413':
+ description: Payload or record limit exceeded
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ '422':
+ description: Invalid typed record or consent
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ '429':
+ description: Rate limited or publisher inbox full
+ headers:
+ Retry-After:
+ schema:
+ type: integer
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ '503':
+ description: Feature unavailable
+ headers:
+ Retry-After:
+ schema:
+ type: integer
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ "/api/v1/financekit/connections/{connection_id}/account_mappings/{source_id}":
parameters:
- - name: id
+ - name: connection_id
in: path
required: true
- description: Category ID
schema:
type: string
- get:
- summary: Retrieve a category
+ format: uuid
+ - name: source_id
+ in: path
+ required: true
+ schema:
+ type: string
+ format: uuid
+ put:
+ summary: Explicitly create or link a canonical account lineage
tags:
- - Categories
+ - FinanceKit
security:
- apiKeyAuth: []
+ - oauth2:
+ - read_write
+ parameters: []
responses:
'200':
- description: subcategory retrieved with parent
+ description: Stable account lineage binding
content:
application/json:
schema:
- "$ref": "#/components/schemas/CategoryDetail"
- '404':
- description: category not found
+ "$ref": "#/components/schemas/FinancekitAccountMapping"
+ '400':
+ description: Malformed or unsupported protocol
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
- "/api/v1/chats":
- get:
- summary: List chats
- tags:
- - Chats
- security:
- - apiKeyAuth: []
- responses:
- '200':
- description: chats listed
+ "$ref": "#/components/schemas/FinancekitError"
+ '401':
+ description: Invalid or missing authentication
content:
application/json:
schema:
- "$ref": "#/components/schemas/ChatCollection"
+ "$ref": "#/components/schemas/FinancekitError"
'403':
- description: AI features disabled
+ description: Insufficient permission or publisher eligibility
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
- post:
- summary: Create chat
- tags:
- - Chats
- security:
- - apiKeyAuth: []
- parameters: []
- responses:
- '201':
- description: chat created
+ "$ref": "#/components/schemas/FinancekitError"
+ '404':
+ description: Resource not found
content:
application/json:
schema:
- "$ref": "#/components/schemas/ChatDetail"
+ "$ref": "#/components/schemas/FinancekitError"
+ '409':
+ description: Enrollment, mapping, lineage, generation, or stream conflict
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ '413':
+ description: Payload or record limit exceeded
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
'422':
- description: validation error
+ description: Invalid typed record or consent
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
+ "$ref": "#/components/schemas/FinancekitError"
+ '429':
+ description: Rate limited or publisher inbox full
+ headers:
+ Retry-After:
+ schema:
+ type: integer
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ '503':
+ description: Feature unavailable
+ headers:
+ Retry-After:
+ schema:
+ type: integer
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
requestBody:
content:
application/json:
schema:
- type: object
- properties:
- title:
- type: string
- example: Monthly budget review
- message:
- type: string
- description: Optional initial message in the chat
- model:
- type: string
- description: Optional OpenAI model identifier
- required:
- - title
+ "$ref": "#/components/schemas/FinancekitMappingRequest"
required: true
- "/api/v1/chats/{id}":
+ "/api/v1/financekit/connections/{connection_id}/activate":
parameters:
- - name: id
+ - name: connection_id
in: path
required: true
- description: Chat ID
schema:
type: string
- get:
- summary: Retrieve a chat
+ format: uuid
+ post:
+ summary: Activate the background publisher
tags:
- - Chats
+ - FinanceKit
security:
- apiKeyAuth: []
+ - oauth2:
+ - read_write
responses:
'200':
- description: chat retrieved
+ description: Publisher configuration and a newly issued restricted credential
content:
application/json:
schema:
- "$ref": "#/components/schemas/ChatDetail"
- '404':
- description: chat not found
+ "$ref": "#/components/schemas/FinancekitPublisherConfiguration"
+ '400':
+ description: Malformed or unsupported protocol
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
- patch:
- summary: Update a chat
- tags:
- - Chats
- security:
- - apiKeyAuth: []
- parameters: []
- responses:
- '200':
- description: chat updated
+ "$ref": "#/components/schemas/FinancekitError"
+ '401':
+ description: Invalid or missing authentication
content:
application/json:
schema:
- "$ref": "#/components/schemas/ChatDetail"
+ "$ref": "#/components/schemas/FinancekitError"
+ '403':
+ description: Insufficient permission or publisher eligibility
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
'404':
- description: chat not found
+ description: Resource not found
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
+ "$ref": "#/components/schemas/FinancekitError"
+ '409':
+ description: Enrollment, mapping, lineage, generation, or stream conflict
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ '413':
+ description: Payload or record limit exceeded
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
'422':
- description: validation error
+ description: Invalid typed record or consent
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
- requestBody:
- content:
- application/json:
- schema:
- type: object
- properties:
- title:
- type: string
- example: Updated chat title
- required: true
- delete:
- summary: Delete a chat
- tags:
- - Chats
- security:
- - apiKeyAuth: []
- responses:
- '204':
- description: chat deleted
- '404':
- description: chat not found
- "/api/v1/chats/{chat_id}/messages":
+ "$ref": "#/components/schemas/FinancekitError"
+ '429':
+ description: Rate limited or publisher inbox full
+ headers:
+ Retry-After:
+ schema:
+ type: integer
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ '503':
+ description: Feature unavailable
+ headers:
+ Retry-After:
+ schema:
+ type: integer
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ "/api/v1/financekit/connections/{connection_id}/credential":
parameters:
- - name: chat_id
+ - name: connection_id
in: path
required: true
- description: Chat ID
schema:
type: string
+ format: uuid
post:
- summary: Create a message
+ summary: Credential the background publisher
tags:
- - Chat Messages
+ - FinanceKit
security:
- apiKeyAuth: []
- parameters: []
+ - oauth2:
+ - read_write
responses:
- '201':
- description: message created
+ '200':
+ description: Publisher configuration and a newly issued restricted credential
content:
application/json:
schema:
- "$ref": "#/components/schemas/MessageResponse"
+ "$ref": "#/components/schemas/FinancekitPublisherConfiguration"
+ '400':
+ description: Malformed or unsupported protocol
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ '401':
+ description: Invalid or missing authentication
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ '403':
+ description: Insufficient permission or publisher eligibility
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
'404':
- description: chat not found
+ description: Resource not found
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
+ "$ref": "#/components/schemas/FinancekitError"
+ '409':
+ description: Enrollment, mapping, lineage, generation, or stream conflict
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ '413':
+ description: Payload or record limit exceeded
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
'422':
- description: validation error
+ description: Invalid typed record or consent
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
- requestBody:
- content:
- application/json:
- schema:
- type: object
- properties:
- content:
- type: string
- model:
- type: string
- required:
- - content
- required: true
- "/api/v1/chats/{chat_id}/messages/retry":
+ "$ref": "#/components/schemas/FinancekitError"
+ '429':
+ description: Rate limited or publisher inbox full
+ headers:
+ Retry-After:
+ schema:
+ type: integer
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ '503':
+ description: Feature unavailable
+ headers:
+ Retry-After:
+ schema:
+ type: integer
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ "/api/v1/financekit/connections/{connection_id}/repair":
parameters:
- - name: chat_id
+ - name: connection_id
in: path
required: true
- description: Chat ID
schema:
type: string
+ format: uuid
post:
- summary: Retry the last assistant response
+ summary: Repair the background publisher
tags:
- - Chat Messages
+ - FinanceKit
security:
- apiKeyAuth: []
+ - oauth2:
+ - read_write
responses:
- '202':
- description: retry started
+ '200':
+ description: Publisher configuration and a newly issued restricted credential
content:
application/json:
schema:
- "$ref": "#/components/schemas/RetryResponse"
+ "$ref": "#/components/schemas/FinancekitPublisherConfiguration"
+ '400':
+ description: Malformed or unsupported protocol
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ '401':
+ description: Invalid or missing authentication
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ '403':
+ description: Insufficient permission or publisher eligibility
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
'404':
- description: chat not found
+ description: Resource not found
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
+ "$ref": "#/components/schemas/FinancekitError"
+ '409':
+ description: Enrollment, mapping, lineage, generation, or stream conflict
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ '413':
+ description: Payload or record limit exceeded
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
'422':
- description: no assistant message available
+ description: Invalid typed record or consent
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
- "/api/v1/family_exports":
- get:
- summary: Lists family exports
+ "$ref": "#/components/schemas/FinancekitError"
+ '429':
+ description: Rate limited or publisher inbox full
+ headers:
+ Retry-After:
+ schema:
+ type: integer
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ '503':
+ description: Feature unavailable
+ headers:
+ Retry-After:
+ schema:
+ type: integer
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ "/api/v1/financekit/publishers/{publisher_id}/batches":
+ parameters:
+ - name: publisher_id
+ in: path
+ required: true
+ schema:
+ type: string
+ format: uuid
+ post:
+ summary: Durably accept an ordered FinanceKit publisher batch
tags:
- - Family Exports
+ - FinanceKit
security:
- - apiKeyAuth: []
+ - financekitPublisher: []
parameters:
- - name: page
- in: query
+ - name: Authorization
+ in: header
+ required: true
+ schema:
+ type: string
+ - name: Idempotency-Key
+ in: header
required: false
- description: 'Page number (default: 1)'
schema:
- type: integer
- - name: per_page
- in: query
+ type: string
+ format: uuid
+ - name: X-Sure-Payload-SHA256
+ in: header
required: false
- description: 'Items per page (default: 25, max: 100)'
schema:
- type: integer
+ type: string
+ pattern: "^[0-9a-f]{64}$"
responses:
- '200':
- description: family exports listed
+ '202':
+ description: Immutable bytes accepted into the inbox
content:
application/json:
schema:
- "$ref": "#/components/schemas/FamilyExportCollection"
- '401':
- description: unauthorized
+ "$ref": "#/components/schemas/FinancekitBatchReceipt"
+ '400':
+ description: Malformed or unsupported protocol
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
- '403':
- description: forbidden
+ "$ref": "#/components/schemas/FinancekitError"
+ '401':
+ description: Invalid publisher credential
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
- post:
- summary: Queues a family export
- tags:
- - Family Exports
- security:
- - apiKeyAuth: []
- parameters: []
- responses:
- '202':
- description: family export queued
+ "$ref": "#/components/schemas/FinancekitError"
+ '409':
+ description: Digest, sequence, predecessor, generation, or idempotency conflict
content:
application/json:
schema:
- "$ref": "#/components/schemas/FamilyExportResponse"
- '401':
- description: unauthorized
+ "$ref": "#/components/schemas/FinancekitError"
+ '413':
+ description: Payload or record limit exceeded
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
- '403':
- description: forbidden
- content:
- application/json:
+ "$ref": "#/components/schemas/FinancekitError"
+ '429':
+ description: Publisher inbox full
+ headers:
+ Retry-After:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
- '422':
- description: invalid params
+ type: integer
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
+ "$ref": "#/components/schemas/FinancekitError"
requestBody:
content:
application/json:
schema:
- type: object
- additionalProperties: false
- description: Family export creation does not accept request parameters.
- "/api/v1/family_exports/{id}":
+ "$ref": "#/components/schemas/FinancekitBatch"
+ required: true
+ "/api/v1/financekit/publishers/{publisher_id}/batches/{batch_id}":
parameters:
- - name: id
+ - name: publisher_id
+ in: path
+ required: true
+ schema:
+ type: string
+ format: uuid
+ - name: batch_id
in: path
- format: uuid
required: true
schema:
type: string
+ format: uuid
get:
- summary: Shows a family export
+ summary: Read the durable receipt for an accepted batch
+ description: Recover an accepted batch receipt, including its current processing
+ status.
tags:
- - Family Exports
+ - FinanceKit
security:
- - apiKeyAuth: []
+ - financekitPublisher: []
+ parameters:
+ - name: Authorization
+ in: header
+ required: true
+ schema:
+ type: string
responses:
'200':
- description: family export shown
+ description: Durable receipt for a previously accepted batch
content:
application/json:
schema:
- "$ref": "#/components/schemas/FamilyExportResponse"
- '401':
- description: unauthorized
+ "$ref": "#/components/schemas/FinancekitBatchReceipt"
+ '429':
+ description: Rate limited
+ headers:
+ Retry-After:
+ schema:
+ type: integer
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
- '403':
- description: forbidden
+ "$ref": "#/components/schemas/FinancekitError"
+ '401':
+ description: Invalid publisher credential
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
+ "$ref": "#/components/schemas/FinancekitError"
'404':
- description: not found
+ description: No batch with that identity in the current generation
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
- "/api/v1/family_exports/{id}/download":
+ "$ref": "#/components/schemas/FinancekitError"
+ "/api/v1/financekit/connections/{connection_id}/conflicts":
parameters:
- - name: id
+ - name: connection_id
in: path
- format: uuid
required: true
schema:
type: string
+ format: uuid
get:
- summary: Downloads a completed family export
+ summary: List conflicts requiring user review
tags:
- - Family Exports
+ - FinanceKit
security:
- apiKeyAuth: []
+ - oauth2:
+ - read
responses:
- '302':
- description: family export download redirected
+ '200':
+ description: Conflict collection
+ content:
+ application/json:
+ schema:
+ type: object
+ required:
+ - conflicts
+ properties:
+ conflicts:
+ type: array
+ items:
+ "$ref": "#/components/schemas/FinancekitConflict"
+ '400':
+ description: Malformed or unsupported protocol
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
'401':
- description: unauthorized
+ description: Invalid or missing authentication
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
+ "$ref": "#/components/schemas/FinancekitError"
'403':
- description: forbidden
+ description: Insufficient permission or publisher eligibility
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
+ "$ref": "#/components/schemas/FinancekitError"
'404':
- description: not found
+ description: Resource not found
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
+ "$ref": "#/components/schemas/FinancekitError"
'409':
- description: export not ready
+ description: Enrollment, mapping, lineage, generation, or stream conflict
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
- "/api/v1/family_settings":
- get:
- summary: Retrieve family settings
- description: Retrieve a read-only snapshot of non-secret family configuration.
+ "$ref": "#/components/schemas/FinancekitError"
+ '413':
+ description: Payload or record limit exceeded
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ '422':
+ description: Invalid typed record or consent
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ '429':
+ description: Rate limited or publisher inbox full
+ headers:
+ Retry-After:
+ schema:
+ type: integer
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ '503':
+ description: Feature unavailable
+ headers:
+ Retry-After:
+ schema:
+ type: integer
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ "/api/v1/financekit/connections/{connection_id}/conflicts/{id}":
+ parameters:
+ - name: connection_id
+ in: path
+ required: true
+ schema:
+ type: string
+ format: uuid
+ - name: id
+ in: path
+ required: true
+ schema:
+ type: string
+ format: uuid
+ patch:
+ summary: Resolve a FinanceKit import conflict
tags:
- - Family Settings
+ - FinanceKit
security:
- apiKeyAuth: []
+ - oauth2:
+ - read_write
+ parameters: []
responses:
'200':
- description: family settings retrieved
+ description: Conflict resolved
content:
application/json:
schema:
- "$ref": "#/components/schemas/FamilySettings"
+ "$ref": "#/components/schemas/FinancekitConflict"
+ '400':
+ description: Malformed or unsupported protocol
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
'401':
- description: unauthorized
+ description: Invalid or missing authentication
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
+ "$ref": "#/components/schemas/FinancekitError"
'403':
- description: insufficient scope
+ description: Insufficient permission or publisher eligibility
content:
application/json:
schema:
- "$ref": "#/components/schemas/ErrorResponse"
+ "$ref": "#/components/schemas/FinancekitError"
+ '404':
+ description: Resource not found
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ '409':
+ description: Enrollment, mapping, lineage, generation, or stream conflict
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ '413':
+ description: Payload or record limit exceeded
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ '422':
+ description: Invalid typed record or consent
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ '429':
+ description: Rate limited or publisher inbox full
+ headers:
+ Retry-After:
+ schema:
+ type: integer
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ '503':
+ description: Feature unavailable
+ headers:
+ Retry-After:
+ schema:
+ type: integer
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitError"
+ requestBody:
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/FinancekitConflictResolution"
+ required: true
"/api/v1/holdings":
get:
summary: List holdings
diff --git a/docs/clients.md b/docs/clients.md
index 32901ab36d..e8264236fc 100644
--- a/docs/clients.md
+++ b/docs/clients.md
@@ -108,7 +108,7 @@ All clients should connect to a Sure server the user controls or trusts. Native,
mobile, API, and MCP clients do not replace the server; they are different ways
to access it.
-### Native reporting and device continuity
+## Native reporting and device continuity
Read monthly server-calculated totals and the daily spending comparison using
[`GET /api/v1/cash_flow`](api/openapi.yaml). Native clients should
@@ -157,3 +157,7 @@ a matching key allows atomic replacement with a **new subscription ID**, making
old queued deliveries and deletes harmless. A missing or wrong proof returns 422.
An existing registration without a digest must first be enrolled by its original
owner or removed by that owner; knowing the APNs token alone never authorizes transfer.
+
+## FinanceKit device publisher
+
+The native Apple client can enroll as a FinanceKit device publisher, map explicitly selected Wallet accounts, and upload an ordered local outbox during foreground or iOS-granted background execution. Setup and repair use normal Sure authentication; uploads use a revocable one-purpose credential that cannot read Sure data. Stable server-issued account lineages preserve identity across publisher replacement. See the [OpenAPI reference](api/openapi.yaml) and [operator guide](hosting/financekit.md).
diff --git a/docs/hosting/financekit.md b/docs/hosting/financekit.md
new file mode 100644
index 0000000000..211772f15c
--- /dev/null
+++ b/docs/hosting/financekit.md
@@ -0,0 +1,43 @@
+# Operating the FinanceKit device publisher
+
+This guide covers Sure's server-side ingestion of FinanceKit uploads. It applies to foreground "Sync now" in alpha builds and to optional background delivery by the iOS client. Both use the same enrollment, upload, receipt, and repair protocol; background delivery is not required to begin alpha testing.
+
+Sure's server-side worker and scheduled inbox sweep are required for either delivery mode. They apply accepted batches, retry processing, complete downstream account updates, and remove expired payload bytes. These server jobs are separate from the iOS app's ability to run in the background.
+
+FinanceKit is default-off and requires:
+
+- `FINANCEKIT_ENABLED=true`;
+- `FINANCEKIT_FAMILY_IDS`, a comma-separated exact family UUID allowlist;
+- an active enrolling family administrator with preview features enabled; and
+- the scheduled `FinancekitInboxJob` sweep in addition to jobs enqueued when a batch arrives.
+
+No Apple Wallet entitlement, private key, or FinanceKit framework is installed on the server. Sure never receives the user's Apple credentials. The iOS app obtains Wallet authorization directly from Apple and uploads only the accounts the user selected and consented to share.
+
+## Deployment
+
+Deploy the migration, application, worker, and scheduler with the feature flag disabled. The migration introduces publisher connections, stable account lineages, immutable batch receipts, source transaction identities, balance observations, and conflicts.
+
+After deploy:
+
+1. Confirm the high-priority job queue and recurring scheduler are healthy.
+2. Enable only a disposable test family.
+3. Enroll and activate a synthetic publisher over HTTPS.
+4. Upload sequences 2 then 1 and confirm the inbox applies them in order.
+5. Retry identical bytes and confirm the receipt is stable and no ledger row duplicates.
+6. Rotate the credential and confirm the prior credential cannot upload or call normal APIs.
+7. Replace the publisher and confirm the canonical account, source identities, and tombstones are reused.
+8. Induce a bad predecessor and confirm the connection enters `repair_required`; repair must create a new generation and stream.
+9. Confirm health reports device contact, acceptance, import, and downstream completion separately.
+10. Confirm applied, permanently failed, and revoked payload bytes are removed after seven days.
+
+Monitor queue depth, oldest accepted batch age, `repair_required` connections, and downstream lag. Diagnostics may include publisher, batch, sequence, generation, and typed error codes. They must not include credentials, raw request bodies, transaction descriptions, merchant names, amounts, account names, or server authentication headers.
+
+## Capacity and retention
+
+Protocol 2 limits each publisher to 20 selected accounts, 500 events per batch, 1 MiB of JSON, and 100 accepted/processing batches. Each capture is limited to 100 chunks so the complete capture fits in the inbox. A client can upload larger histories using multiple consecutive captures.
+
+Exact payload bytes are retained for seven days after apply, permanent failure, or revocation for response-loss recovery and operational investigation. Canonical financial data and source identity records follow Sure's normal family retention and deletion behavior. Family financial-data reset removes FinanceKit connections, lineages, observations, identities, conflicts, and batch receipts for that family.
+
+## Rollback
+
+Disable `FINANCEKIT_ENABLED` first. Existing Sure data remains readable, uploads return a retryable unavailable response, and workers stop applying FinanceKit batches. Do not drop the tables during an application rollback; keep receipts and lineage data until all deployed versions no longer reference them and the retention decision is explicit.
diff --git a/spec/requests/api/v1/financekit_spec.rb b/spec/requests/api/v1/financekit_spec.rb
new file mode 100644
index 0000000000..bd8ffaadad
--- /dev/null
+++ b/spec/requests/api/v1/financekit_spec.rb
@@ -0,0 +1,304 @@
+require "swagger_helper"
+
+RSpec.describe "Api::V1::Financekit", type: :request do
+ FINANCEKIT_READ_SECURITY = [ { apiKeyAuth: [] }, { oauth2: %w[read] } ].freeze
+ FINANCEKIT_WRITE_SECURITY = [ { apiKeyAuth: [] }, { oauth2: %w[read_write] } ].freeze
+ FINANCEKIT_PUBLISHER_SECURITY = [ { financekitPublisher: [] } ].freeze
+
+ let(:family) do
+ Family.create!(name: "FinanceKit API Family", currency: "USD", locale: "en", date_format: "%m-%d-%Y")
+ end
+ let(:user) do
+ family.users.create!(email: "financekit-api-#{SecureRandom.hex(8)}@example.com", password: "password123",
+ password_confirmation: "password123", role: "admin", preferences: { "preview_features_enabled" => true })
+ end
+ let(:api_key) do
+ key = ApiKey.generate_secure_key
+ ApiKey.create!(user: user, name: "API Docs Key", key: key, scopes: %w[read_write], source: "web")
+ end
+ let(:'X-Api-Key') { api_key.plain_key }
+ let(:source_id) { SecureRandom.uuid }
+ let(:enrollment_input) do
+ { protocol_version: 2, enrollment_id: SecureRandom.uuid,
+ consent: { version: 1, granted_at: Time.current.iso8601, selected_source_account_ids: [ source_id ],
+ upload_authorized: true, family_visibility_acknowledged: true, remote_processing_acknowledged: true } }
+ end
+ let(:connection) { Financekit::Enrollment.create!(user, enrollment_input.deep_stringify_keys).item }
+ let(:mapping_input) do
+ { expected_version: 0, action: "create", name: "Wallet Checking", institution_name: "Apple Wallet",
+ currency: "USD", accountable_type: "Depository", subtype: "checking", ledger_timezone: "America/New_York",
+ booked_balance: { amount: "25.00", currency: "USD", direction: "credit" }, observed_at: Time.current.iso8601 }
+ end
+ let(:mapping) { FinancekitAccount.map!(connection, source_id, mapping_input.deep_stringify_keys) }
+ let(:publisher_credential) { mapping && connection.activate! }
+ let(:id) { connection.id }
+ let(:connection_id) { connection.id }
+ let(:page) { nil }
+ let(:per_page) { nil }
+
+ before do
+ allow(Financekit).to receive(:enabled?).and_return(true)
+ allow(ApiRateLimiter).to receive(:limit).and_return(nil)
+ end
+
+ # Error behavior is covered in Minitest. Rswag still needs an example to emit
+ # each response during its documentation-only dry run.
+ shared_examples "financekit normal API errors" do
+ response "400", "Malformed or unsupported protocol" do
+ schema "$ref" => "#/components/schemas/FinancekitError"
+ run_test! skip: "Documentation only; behavior covered by Minitest"
+ end
+ response "401", "Invalid or missing authentication" do
+ schema "$ref" => "#/components/schemas/FinancekitError"
+ run_test! skip: "Documentation only; behavior covered by Minitest"
+ end
+ response "403", "Insufficient permission or publisher eligibility" do
+ schema "$ref" => "#/components/schemas/FinancekitError"
+ run_test! skip: "Documentation only; behavior covered by Minitest"
+ end
+ response "404", "Resource not found" do
+ schema "$ref" => "#/components/schemas/FinancekitError"
+ run_test! skip: "Documentation only; behavior covered by Minitest"
+ end
+ response "409", "Enrollment, mapping, lineage, generation, or stream conflict" do
+ schema "$ref" => "#/components/schemas/FinancekitError"
+ run_test! skip: "Documentation only; behavior covered by Minitest"
+ end
+ response "413", "Payload or record limit exceeded" do
+ schema "$ref" => "#/components/schemas/FinancekitError"
+ run_test! skip: "Documentation only; behavior covered by Minitest"
+ end
+ response "422", "Invalid typed record or consent" do
+ schema "$ref" => "#/components/schemas/FinancekitError"
+ run_test! skip: "Documentation only; behavior covered by Minitest"
+ end
+ response "429", "Rate limited or publisher inbox full" do
+ schema "$ref" => "#/components/schemas/FinancekitError"
+ header "Retry-After", schema: { type: :integer }
+ run_test! skip: "Documentation only; behavior covered by Minitest"
+ end
+ response "503", "Feature unavailable" do
+ schema "$ref" => "#/components/schemas/FinancekitError"
+ header "Retry-After", schema: { type: :integer }
+ run_test! skip: "Documentation only; behavior covered by Minitest"
+ end
+ end
+
+ path "/api/v1/financekit/capabilities" do
+ get "Discover FinanceKit background publisher support" do
+ tags "FinanceKit"
+ produces "application/json"
+ security FINANCEKIT_READ_SECURITY
+ response "200", "Publisher limits and protocol versions" do
+ schema "$ref" => "#/components/schemas/FinancekitCapabilities"
+ run_test!
+ end
+ include_examples "financekit normal API errors"
+ end
+ end
+
+ path "/api/v1/financekit/connections" do
+ post "Enroll a FinanceKit device publisher" do
+ tags "FinanceKit"
+ consumes "application/json"
+ produces "application/json"
+ security FINANCEKIT_WRITE_SECURITY
+ parameter name: :body, in: :body, required: true, schema: { "$ref" => "#/components/schemas/FinancekitEnrollment" }
+ response "201", "Publisher enrolled pending account mapping" do
+ let(:body) { enrollment_input }
+ schema "$ref" => "#/components/schemas/FinancekitConnection"
+ run_test!
+ end
+ include_examples "financekit normal API errors"
+ end
+ end
+
+ path "/api/v1/financekit/connections/{id}" do
+ parameter name: :id, in: :path, required: true, schema: { type: :string, format: :uuid }
+ get "Read publisher health and paginated mappings" do
+ tags "FinanceKit"
+ produces "application/json"
+ security FINANCEKIT_READ_SECURITY
+ parameter name: :page, in: :query, type: :integer
+ parameter name: :per_page, in: :query, type: :integer
+ response "200", "Publisher health" do
+ schema "$ref" => "#/components/schemas/FinancekitConnection"
+ run_test!
+ end
+ include_examples "financekit normal API errors"
+ end
+ delete "Revoke a publisher and retain imported financial history" do
+ tags "FinanceKit"
+ produces "application/json"
+ security FINANCEKIT_WRITE_SECURITY
+ response "204", "Publisher revoked" do
+ run_test!
+ end
+ include_examples "financekit normal API errors"
+ end
+ end
+
+ path "/api/v1/financekit/connections/{connection_id}/account_mappings/{source_id}" do
+ parameter name: :connection_id, in: :path, required: true, schema: { type: :string, format: :uuid }
+ parameter name: :source_id, in: :path, required: true, schema: { type: :string, format: :uuid }
+ put "Explicitly create or link a canonical account lineage" do
+ tags "FinanceKit"
+ consumes "application/json"
+ produces "application/json"
+ security FINANCEKIT_WRITE_SECURITY
+ parameter name: :body, in: :body, required: true, schema: { "$ref" => "#/components/schemas/FinancekitMappingRequest" }
+ response "200", "Stable account lineage binding" do
+ let(:body) { mapping_input }
+ schema "$ref" => "#/components/schemas/FinancekitAccountMapping"
+ run_test!
+ end
+ include_examples "financekit normal API errors"
+ end
+ end
+
+ %w[activate credential repair].each do |operation|
+ path "/api/v1/financekit/connections/{connection_id}/#{operation}" do
+ parameter name: :connection_id, in: :path, required: true, schema: { type: :string, format: :uuid }
+ post "#{operation.capitalize} the background publisher" do
+ tags "FinanceKit"
+ produces "application/json"
+ security FINANCEKIT_WRITE_SECURITY
+ response "200", "Publisher configuration and a newly issued restricted credential" do
+ before do
+ mapping
+ connection.activate! if operation != "activate"
+ end
+ schema "$ref" => "#/components/schemas/FinancekitPublisherConfiguration"
+ run_test!
+ end
+ include_examples "financekit normal API errors"
+ end
+ end
+ end
+
+ path "/api/v1/financekit/publishers/{publisher_id}/batches" do
+ parameter name: :publisher_id, in: :path, required: true, schema: { type: :string, format: :uuid }
+ post "Durably accept an ordered FinanceKit publisher batch" do
+ tags "FinanceKit"
+ consumes "application/json"
+ produces "application/json"
+ security FINANCEKIT_PUBLISHER_SECURITY
+ parameter name: :Authorization, in: :header, type: :string, required: true
+ parameter name: :'Idempotency-Key', in: :header, required: false, schema: { type: :string, format: :uuid }
+ parameter name: :'X-Sure-Payload-SHA256', in: :header, required: false,
+ schema: { type: :string, pattern: '^[0-9a-f]{64}$' }
+ parameter name: :body, in: :body, required: true, schema: { "$ref" => "#/components/schemas/FinancekitBatch" }
+ let(:publisher_id) { connection.publisher_id }
+ let(:Authorization) { "Bearer #{publisher_credential}" }
+ let(:body) do
+ { protocol_version: 2, connection_id: connection.id, publisher_id: connection.publisher_id,
+ generation: connection.generation, stream_id: connection.stream_id, batch_id: SecureRandom.uuid,
+ sequence: 1, capture_id: SecureRandom.uuid, chunk_index: 0, chunk_count: 1, capture_mode: "delta",
+ snapshot_complete: false, captured_at: Time.current.iso8601, selected_source_account_ids: [ source_id ],
+ events: [] }
+ end
+ response "202", "Immutable bytes accepted into the inbox" do
+ schema "$ref" => "#/components/schemas/FinancekitBatchReceipt"
+ run_test!
+ end
+ response "400", "Malformed or unsupported protocol" do
+ schema "$ref" => "#/components/schemas/FinancekitError"
+ run_test! skip: "Documentation only; behavior covered by Minitest"
+ end
+ response "401", "Invalid publisher credential" do
+ schema "$ref" => "#/components/schemas/FinancekitError"
+ run_test! skip: "Documentation only; behavior covered by Minitest"
+ end
+ response "409", "Digest, sequence, predecessor, generation, or idempotency conflict" do
+ schema "$ref" => "#/components/schemas/FinancekitError"
+ run_test! skip: "Documentation only; behavior covered by Minitest"
+ end
+ response "413", "Payload or record limit exceeded" do
+ schema "$ref" => "#/components/schemas/FinancekitError"
+ run_test! skip: "Documentation only; behavior covered by Minitest"
+ end
+ response "429", "Publisher inbox full" do
+ schema "$ref" => "#/components/schemas/FinancekitError"
+ header "Retry-After", schema: { type: :integer }
+ run_test! skip: "Documentation only; behavior covered by Minitest"
+ end
+ end
+ end
+
+ path "/api/v1/financekit/publishers/{publisher_id}/batches/{batch_id}" do
+ parameter name: :publisher_id, in: :path, required: true, schema: { type: :string, format: :uuid }
+ parameter name: :batch_id, in: :path, required: true, schema: { type: :string, format: :uuid }
+ get "Read the durable receipt for an accepted batch" do
+ description "Recover an accepted batch receipt, including its current processing status."
+ tags "FinanceKit"
+ produces "application/json"
+ security FINANCEKIT_PUBLISHER_SECURITY
+ parameter name: :Authorization, in: :header, type: :string, required: true
+ let(:publisher_id) { connection.publisher_id }
+ let(:Authorization) { "Bearer #{publisher_credential}" }
+ let(:accepted_batch) do
+ publisher_credential
+ payload = { protocol_version: 2, connection_id: connection.id, publisher_id: connection.publisher_id,
+ generation: connection.generation, stream_id: connection.stream_id, batch_id: SecureRandom.uuid,
+ sequence: 1, capture_id: SecureRandom.uuid, chunk_index: 0, chunk_count: 1, capture_mode: "delta",
+ snapshot_complete: false, captured_at: Time.current.iso8601,
+ selected_source_account_ids: [ source_id ], events: [] }
+ FinancekitBatch.accept!(connection, JSON.generate(payload.deep_stringify_keys))
+ end
+ let(:batch_id) { accepted_batch.batch_id }
+ response "200", "Durable receipt for a previously accepted batch" do
+ schema "$ref" => "#/components/schemas/FinancekitBatchReceipt"
+ run_test!
+ end
+ response "429", "Rate limited" do
+ schema "$ref" => "#/components/schemas/FinancekitError"
+ header "Retry-After", schema: { type: :integer }
+ run_test! skip: "Documentation only; behavior covered by Minitest"
+ end
+ response "401", "Invalid publisher credential" do
+ schema "$ref" => "#/components/schemas/FinancekitError"
+ run_test! skip: "Documentation only; behavior covered by Minitest"
+ end
+ response "404", "No batch with that identity in the current generation" do
+ schema "$ref" => "#/components/schemas/FinancekitError"
+ run_test! skip: "Documentation only; behavior covered by Minitest"
+ end
+ end
+ end
+
+ path "/api/v1/financekit/connections/{connection_id}/conflicts" do
+ parameter name: :connection_id, in: :path, required: true, schema: { type: :string, format: :uuid }
+ get "List conflicts requiring user review" do
+ tags "FinanceKit"
+ produces "application/json"
+ security FINANCEKIT_READ_SECURITY
+ response "200", "Conflict collection" do
+ schema type: :object, required: %w[conflicts], properties: {
+ conflicts: { type: :array, items: { "$ref" => "#/components/schemas/FinancekitConflict" } }
+ }
+ run_test!
+ end
+ include_examples "financekit normal API errors"
+ end
+ end
+
+ path "/api/v1/financekit/connections/{connection_id}/conflicts/{id}" do
+ parameter name: :connection_id, in: :path, required: true, schema: { type: :string, format: :uuid }
+ parameter name: :id, in: :path, required: true, schema: { type: :string, format: :uuid }
+ patch "Resolve a FinanceKit import conflict" do
+ tags "FinanceKit"
+ consumes "application/json"
+ produces "application/json"
+ security FINANCEKIT_WRITE_SECURITY
+ parameter name: :body, in: :body, required: true, schema: { "$ref" => "#/components/schemas/FinancekitConflictResolution" }
+ let(:conflict) { connection.financekit_conflicts.create!(family: family, kind: "protected_tombstone", details: {}) }
+ let(:id) { conflict.id }
+ let(:body) { { resolution: "keep_sure" } }
+ response "200", "Conflict resolved" do
+ schema "$ref" => "#/components/schemas/FinancekitConflict"
+ run_test!
+ end
+ include_examples "financekit normal API errors"
+ end
+ end
+end
diff --git a/spec/swagger_helper.rb b/spec/swagger_helper.rb
index 059bc27d5b..7fc44227cd 100644
--- a/spec/swagger_helper.rb
+++ b/spec/swagger_helper.rb
@@ -31,6 +31,25 @@ RSpec.configure do |config|
name: 'X-Api-Key',
in: :header,
description: 'API key for authentication. Generate one from your account settings.'
+ },
+ financekitPublisher: {
+ type: :http,
+ scheme: :bearer,
+ bearerFormat: 'opaque publisher credential',
+ description: 'Revocable credential restricted to one FinanceKit publisher upload URL.'
+ },
+ oauth2: {
+ type: :oauth2,
+ flows: {
+ authorizationCode: {
+ authorizationUrl: '/oauth/authorize',
+ tokenUrl: '/oauth/token',
+ scopes: {
+ read: 'Read access',
+ read_write: 'Read and write access'
+ }
+ }
+ }
}
},
schemas: {
@@ -1854,5 +1873,9 @@ RSpec.configure do |config|
}
}
+ config.openapi_specs["openapi.yaml"][:components][:schemas].merge!(
+ JSON.parse(Rails.root.join("docs/api/financekit/schemas.json").read)
+ )
+
config.openapi_format = :yaml
end
diff --git a/test/controllers/api/v1/financekit/connections_controller_test.rb b/test/controllers/api/v1/financekit/connections_controller_test.rb
new file mode 100644
index 0000000000..a7e05376b1
--- /dev/null
+++ b/test/controllers/api/v1/financekit/connections_controller_test.rb
@@ -0,0 +1,224 @@
+require "test_helper"
+require "rswag/specs/extended_schema"
+require_relative "../../../../support/financekit_test_helper"
+
+class Api::V1::Financekit::ConnectionsControllerTest < ActionDispatch::IntegrationTest
+ include FinancekitTestHelper
+ include ActiveJob::TestHelper
+
+ setup do
+ financekit_setup
+ @user.api_keys.active.destroy_all
+ @key = ApiKey.create!(user: @user, name: "FinanceKit test", scopes: [ "read_write" ],
+ display_key: "test_#{SecureRandom.hex(16)}", source: "web")
+ @headers = { "X-Api-Key" => @key.display_key }
+ @publisher_headers = { "Authorization" => "Bearer #{@credential}", "Content-Type" => "application/json" }
+ ApiRateLimiter.stubs(:limit).returns(nil)
+ clear_enqueued_jobs
+ end
+
+ test "capabilities are authenticated scoped and explicit about background delivery" do
+ get "/api/v1/financekit/capabilities"
+ assert_response :unauthorized
+
+ get "/api/v1/financekit/capabilities", headers: @headers
+ assert_response :success
+ assert_equal true, response.parsed_body.fetch("available")
+ assert_equal "background_publisher", response.parsed_body.fetch("delivery")
+ assert_equal Financekit::VERSION, response.parsed_body.fetch("protocol_versions").sole
+
+ @key.update!(scopes: [ "read" ])
+ post "/api/v1/financekit/connections", params: @enrollment, headers: @headers, as: :json
+ assert_response :forbidden
+ end
+
+ test "enrollment is idempotent and activation returns a one-purpose publisher configuration" do
+ post "/api/v1/financekit/connections", params: @enrollment, headers: @headers, as: :json
+ assert_response :success
+ assert_equal @item.id, response.parsed_body.fetch("connection_id")
+
+ post "/api/v1/financekit/connections/#{@item.id}/credential", headers: @headers
+ assert_response :success
+ body = response.parsed_body
+ assert_equal Financekit::VERSION, body.fetch("protocol_version")
+ assert_equal @item.publisher_id, body.fetch("publisher_id")
+ assert_equal @source.financekit_account_lineage_id, body.fetch("account_bindings").sole.fetch("lineage_id")
+ assert_match %r{/api/v1/financekit/publishers/#{@item.publisher_id}/batches\z}, body.fetch("upload_url")
+ assert body.fetch("publisher_credential").present?
+ assert_not_includes body.fetch("consent").keys, "recorded_at"
+ end
+
+ test "financial publisher parameters and consent are redacted from diagnostics" do
+ filter = ActiveSupport::ParameterFilter.new(Rails.application.config.filter_parameters)
+ filtered = filter.filter("events" => financekit_events, "consent" => @enrollment.fetch("consent"),
+ "publisher_credential" => @credential)
+
+ assert_equal "[FILTERED]", filtered.fetch("events")
+ assert_equal "[FILTERED]", filtered.fetch("consent")
+ assert_equal "[FILTERED]", filtered.fetch("publisher_credential")
+ end
+
+ test "publisher credential uploads a durable batch but cannot call the general API" do
+ payload = financekit_payload
+ raw = JSON.generate(payload)
+ headers = @publisher_headers.merge("X-Sure-Payload-SHA256" => Digest::SHA256.hexdigest(raw),
+ "Idempotency-Key" => payload.fetch("batch_id"))
+
+ assert_enqueued_with(job: FinancekitInboxJob) do
+ post "/api/v1/financekit/publishers/#{@item.publisher_id}/batches", params: raw, headers: headers
+ end
+ assert_response :accepted
+ assert_equal "accepted", response.parsed_body.fetch("status")
+ assert_receipt_schema
+ assert_equal raw, FinancekitBatch.sole.payload
+ assert_empty @source.account.entries
+
+ FinancekitInboxJob.perform_now(@item.id)
+ get "/api/v1/financekit/publishers/#{@item.publisher_id}/batches/#{payload.fetch("batch_id")}",
+ headers: @publisher_headers.except("Content-Type")
+ assert_response :success
+ assert_equal "applied", response.parsed_body.fetch("status")
+ assert_receipt_schema
+ assert response.parsed_body.fetch("applied_at").present?
+
+ get "/api/v1/accounts", headers: { "Authorization" => "Bearer #{@credential}" }
+ assert_response :unauthorized
+ end
+
+ test "lost upload response can be retried for the same receipt" do
+ payload = financekit_payload
+ raw = JSON.generate(payload)
+ headers = @publisher_headers.merge("X-Sure-Payload-SHA256" => Digest::SHA256.hexdigest(raw),
+ "Idempotency-Key" => payload.fetch("batch_id"))
+
+ post "/api/v1/financekit/publishers/#{@item.publisher_id}/batches", params: raw, headers: headers
+ first_receipt = response.parsed_body
+ assert_response :accepted
+
+ assert_no_difference "FinancekitBatch.count" do
+ post "/api/v1/financekit/publishers/#{@item.publisher_id}/batches", params: raw, headers: headers
+ end
+ assert_response :accepted
+ assert_equal first_receipt, response.parsed_body
+ end
+
+ test "publisher endpoint rejects invalid revoked and oversized credentials or bodies" do
+ post "/api/v1/financekit/publishers/#{@item.publisher_id}/batches", params: JSON.generate(financekit_payload),
+ headers: @publisher_headers.merge("Authorization" => "Bearer invalid")
+ assert_response :unauthorized
+
+ @item.disconnect!
+ post "/api/v1/financekit/publishers/#{@item.publisher_id}/batches", params: JSON.generate(financekit_payload),
+ headers: @publisher_headers
+ assert_response :unauthorized
+
+ post "/api/v1/financekit/publishers/#{@item.publisher_id}/batches", params: "x" * (Financekit::MAX_BYTES + 1),
+ headers: @publisher_headers.merge("Content-Length" => (Financekit::MAX_BYTES + 1).to_s)
+ assert_response :payload_too_large
+ end
+
+ test "connection health separates device receipt import and downstream timestamps" do
+ batch = accept_and_apply
+ @item.reload
+
+ get "/api/v1/financekit/connections/#{@item.id}", headers: @headers
+ assert_response :success
+ body = response.parsed_body
+ assert_not_nil body.fetch("last_device_contact_at")
+ assert_not_nil body.fetch("last_accepted_at")
+ assert_not_nil body.fetch("last_imported_at")
+ assert_not_nil body.fetch("last_downstream_at")
+ assert_equal batch.applied_at.iso8601(3), Time.iso8601(body.fetch("last_imported_at")).iso8601(3)
+ end
+
+ test "conflicts are visible and require an explicit resolution" do
+ first = accept_and_apply
+ @source.account.entries.sole.update!(import_locked: true)
+ tombstone = {
+ "kind" => "transaction_tombstone",
+ "tombstone" => {
+ "source_id" => @transaction_id,
+ "source_account_id" => @source_id,
+ "lineage_id" => @source.financekit_account_lineage_id,
+ "mapping_version" => @source.mapping_version
+ }
+ }
+ accept_and_apply(financekit_payload(sequence: 2, predecessor_digest: first.payload_digest, events: [ tombstone ]))
+ conflict = @item.financekit_conflicts.sole
+
+ get "/api/v1/financekit/connections/#{@item.id}/conflicts", headers: @headers
+ assert_response :success
+ assert_equal conflict.id, response.parsed_body.fetch("conflicts").sole.fetch("id")
+
+ patch "/api/v1/financekit/connections/#{@item.id}/conflicts/#{conflict.id}",
+ params: { resolution: "keep_sure" }, headers: @headers, as: :json
+ assert_response :success
+ assert_equal "resolved", conflict.reload.status
+ assert_not conflict.financekit_transaction.reload.review_required?
+
+ get "/api/v1/financekit/connections/#{@item.id}/conflicts", headers: @headers
+ assert_response :success
+ assert_empty response.parsed_body.fetch("conflicts")
+ end
+
+ test "retry after repair resolution fences the publisher stream" do
+ first = accept_and_apply
+ @source.account.entries.sole.update!(import_locked: true)
+ tombstone = {
+ "kind" => "transaction_tombstone",
+ "tombstone" => {
+ "source_id" => @transaction_id,
+ "source_account_id" => @source_id,
+ "lineage_id" => @source.financekit_account_lineage_id,
+ "mapping_version" => @source.mapping_version
+ }
+ }
+ second = accept_and_apply(financekit_payload(sequence: 2, predecessor_digest: first.payload_digest, events: [ tombstone ]))
+ queued, = accept_batch(financekit_payload(sequence: 3, predecessor_digest: second.payload_digest, events: []))
+ conflict = @item.financekit_conflicts.sole
+ old_credential = @credential
+
+ patch "/api/v1/financekit/connections/#{@item.id}/conflicts/#{conflict.id}",
+ params: { resolution: "retry_after_repair" }, headers: @headers, as: :json
+ assert_response :success
+
+ assert_equal "resolved", conflict.reload.status
+ assert_equal "retry_after_repair", conflict.resolution
+ assert_equal "repair_required", @item.reload.status
+ assert_equal "conflict_retry_requested", @item.repair_reason
+ assert_nil @item.credential_digest
+ assert_equal "revoked", queued.reload.status
+ assert_equal "conflict_retry_requested", queued.error_code
+
+ payload = financekit_payload(sequence: 3, predecessor_digest: second.payload_digest, events: [])
+ post "/api/v1/financekit/publishers/#{@item.publisher_id}/batches", params: JSON.generate(payload),
+ headers: @publisher_headers.merge("Authorization" => "Bearer #{old_credential}")
+ assert_response :unauthorized
+ end
+
+ test "non-admin and foreign-family access is rejected" do
+ member = users(:family_member)
+ member.update!(preferences: member.preferences.merge("preview_features_enabled" => true))
+ key = ApiKey.create!(user: member, name: "FinanceKit member test", scopes: [ "read_write" ],
+ display_key: "test_#{SecureRandom.hex(16)}", source: "web")
+
+ get "/api/v1/financekit/capabilities", headers: { "X-Api-Key" => key.display_key }
+ assert_response :forbidden
+ assert_equal "publisher_forbidden", response.parsed_body.fetch("error")
+
+ other = users(:empty)
+ other_key = ApiKey.create!(user: other, name: "FinanceKit other test", scopes: [ "read" ],
+ display_key: "test_#{SecureRandom.hex(16)}", source: "web")
+ get "/api/v1/financekit/connections/#{@item.id}", headers: { "X-Api-Key" => other_key.display_key }
+ assert_response :forbidden
+ end
+
+ private
+
+ def assert_receipt_schema
+ schemas = JSON.parse(Rails.root.join("docs/api/financekit/schemas.json").read)
+ schema = schemas.fetch("FinancekitBatchReceipt").merge(
+ "$schema" => "http://tempuri.org/rswag/specs/extended_schema")
+ assert_empty JSON::Validator.fully_validate(schema, response.body)
+ end
+end
diff --git a/test/models/financekit/inbox_test.rb b/test/models/financekit/inbox_test.rb
new file mode 100644
index 0000000000..e25c1e892d
--- /dev/null
+++ b/test/models/financekit/inbox_test.rb
@@ -0,0 +1,228 @@
+require "test_helper"
+require_relative "../../support/financekit_test_helper"
+
+class Financekit::InboxTest < ActiveSupport::TestCase
+ include FinancekitTestHelper
+ include ActiveJob::TestHelper
+
+ setup { financekit_setup }
+
+ test "capture chunks are accepted contiguously and applied atomically after final chunk" do
+ capture_id = SecureRandom.uuid
+ first_payload = financekit_payload(events: [])
+ first_payload.merge!("capture_id" => capture_id, "chunk_index" => 0, "chunk_count" => 2)
+ first, first_raw = accept_batch(first_payload)
+ first_digest = Digest::SHA256.hexdigest(first_raw)
+
+ assert_not Financekit::Processor.new(@item).apply_next!
+ assert_equal "accepted", first.reload.status
+
+ second_payload = financekit_payload(sequence: 2, predecessor_digest: first_digest, events: [])
+ second_payload.merge!("capture_id" => capture_id, "chunk_index" => 1, "chunk_count" => 2)
+ second, = accept_batch(second_payload)
+ FinancekitInboxJob.perform_now(@item.id)
+
+ assert_equal "applied", first.reload.status
+ assert_equal "applied", second.reload.status
+ assert_equal 3, @item.reload.next_sequence
+ end
+
+ test "a payload body that is not a JSON object is rejected before the idempotency check" do
+ error = assert_raises(Financekit::Error) do
+ FinancekitBatch.accept!(@item, "[]", idempotency_key: SecureRandom.uuid)
+ end
+
+ assert_equal "invalid_payload", error.code
+ assert_equal 422, error.status
+ end
+
+ test "capture cannot begin at a later chunk" do
+ payload = financekit_payload(events: [])
+ payload.merge!("chunk_index" => 1, "chunk_count" => 2)
+
+ error = assert_raises(Financekit::Error) { accept_batch(payload) }
+ assert_equal "capture_conflict", error.code
+ end
+
+ test "an oversized capture is rejected before filling the inbox" do
+ payload = financekit_payload(events: []).merge("chunk_count" => Financekit::MAX_QUEUED + 1)
+
+ assert_no_difference "FinancekitBatch.count" do
+ error = assert_raises(Financekit::Error) { accept_batch(payload) }
+ assert_equal "capture_limit", error.code
+ assert_equal 413, error.status
+ end
+ assert_equal "active", @item.reload.status
+ end
+
+ test "a bad predecessor inside a capture rolls back all of its ledger changes" do
+ first_payload = financekit_payload.merge("chunk_count" => 2)
+ first, = accept_batch(first_payload)
+ second_payload = financekit_payload(sequence: 2, predecessor_digest: "0" * 64, events: [])
+ .merge("capture_id" => first.capture_id, "chunk_index" => 1, "chunk_count" => 2)
+ second, = accept_batch(second_payload)
+
+ assert_not Financekit::Processor.new(@item).apply_next!
+
+ assert_empty @source.account.entries.reload
+ assert_empty @source.financekit_balance_observations.reload
+ assert_equal "revoked", first.reload.status
+ assert_equal "failed", second.reload.status
+ assert_equal "predecessor_conflict", second.error_code
+ assert_equal 1, @item.reload.next_sequence
+ assert_equal "repair_required", @item.status
+ end
+
+ test "a later chunk failure waits for its retry deadline before reapplying the capture" do
+ first_payload = financekit_payload(events: []).merge("chunk_count" => 2)
+ first, = accept_batch(first_payload)
+ second_payload = financekit_payload(sequence: 2, predecessor_digest: first.payload_digest)
+ .merge("capture_id" => first.capture_id, "chunk_index" => 1, "chunk_count" => 2)
+ second, = accept_batch(second_payload)
+ Account::ProviderImportAdapter.any_instance.stubs(:update_balance)
+ .raises(ActiveRecord::RecordInvalid.new(Account.new))
+ Rails.error.stubs(:report)
+
+ assert_not Financekit::Processor.new(@item).apply_next!
+ assert_equal 1, second.reload.attempts
+ deadline = second.retry_at
+ Financekit::MAX_ATTEMPTS.times { assert_not Financekit::Processor.new(@item).apply_next! }
+ assert_equal 1, second.reload.attempts
+ assert_equal "active", @item.reload.status
+ assert @item.authenticate_credential?(@credential)
+ assert_empty @source.account.entries.reload
+
+ Account::ProviderImportAdapter.any_instance.unstub(:update_balance)
+ travel_to deadline
+ assert Financekit::Processor.new(@item).apply_next!
+ assert_equal "applied", first.reload.status
+ assert_equal "applied", second.reload.status
+ assert_equal 1, @source.account.entries.reload.count
+ end
+
+ test "repeated delivery returns the original receipt without another batch" do
+ payload = financekit_payload
+ original, raw = accept_batch(payload)
+ accepted_receipt = original.receipt
+ assert Financekit::Processor.new(@item).apply_next!
+
+ assert_no_difference "FinancekitBatch.count" do
+ repeated = FinancekitBatch.accept!(@item, raw, claimed_digest: original.payload_digest,
+ idempotency_key: payload.fetch("batch_id"))
+ assert_equal original.id, repeated.id
+ assert_equal accepted_receipt.except(:status, :applied_at), repeated.receipt.except(:status, :applied_at)
+ assert_equal "applied", repeated.receipt.fetch(:status)
+ end
+ end
+
+ test "same batch ID or stream position with different bytes is rejected" do
+ payload = financekit_payload
+ original, = accept_batch(payload)
+ payload["events"] = []
+
+ error = assert_raises(Financekit::Error) { accept_batch(payload) }
+ assert_equal "batch_conflict", error.code
+
+ collision = financekit_payload
+ error = assert_raises(Financekit::Error) { accept_batch(collision) }
+ assert_equal "sequence_conflict", error.code
+ assert_equal "accepted", original.reload.status
+ end
+
+ test "a permanent stream failure requires explicit repair and revokes following batches" do
+ first, = accept_batch
+ second_payload = financekit_payload(sequence: 2, predecessor_digest: "0" * 64, events: [])
+ second, = accept_batch(second_payload)
+ FinancekitInboxJob.perform_now(@item.id)
+
+ assert_equal "applied", first.reload.status
+ assert_equal "failed", second.reload.status
+ assert_equal "predecessor_conflict", second.error_code
+ assert_equal "repair_required", @item.reload.status
+ assert_nil @item.credential_digest
+ end
+
+ test "unexpected processing errors are reported before retry" do
+ batch, = accept_batch
+ error = RuntimeError.new("financekit importer exploded")
+ Financekit::Payload.stubs(:validate_batch!).raises(error)
+ Rails.error.expects(:report).with(error, handled: true,
+ context: { financekit_item_id: @item.id, batch_id: batch.batch_id })
+
+ assert_not Financekit::Processor.new(@item).apply_next!
+
+ assert_equal "accepted", batch.reload.status
+ assert_equal "processing_error", batch.error_code
+ end
+
+ test "a record validation failure retries instead of fencing the publisher" do
+ batch, = accept_batch
+ Financekit::Payload.stubs(:validate_batch!).raises(ActiveRecord::RecordInvalid.new(Account.new))
+ Rails.error.stubs(:report)
+
+ assert_not Financekit::Processor.new(@item).apply_next!
+
+ assert_equal "accepted", batch.reload.status
+ assert_equal "import_validation", batch.error_code
+ assert_equal 1, batch.attempts
+ assert_not_nil batch.retry_at
+ # The publisher keeps uploading: a background wake cannot reissue a
+ # credential, so a single unlucky save must not clear it.
+ assert_equal "active", @item.reload.status
+ assert_not_nil @item.credential_digest
+ end
+
+ test "a persistent record validation failure still fences after the bounded attempts" do
+ batch, = accept_batch
+ Financekit::Payload.stubs(:validate_batch!).raises(ActiveRecord::RecordInvalid.new(Account.new))
+ Rails.error.stubs(:report)
+
+ Financekit::MAX_ATTEMPTS.times do
+ batch.reload.update_columns(retry_at: nil)
+ Financekit::Processor.new(@item).apply_next!
+ end
+
+ assert_equal "failed", batch.reload.status
+ assert_equal "import_validation", batch.error_code
+ assert_equal Financekit::MAX_ATTEMPTS, batch.attempts
+ assert_equal "repair_required", @item.reload.status
+ assert_nil @item.credential_digest
+ end
+
+ test "payload bytes are removed after the bounded replay window" do
+ batch = accept_and_apply
+ batch.update_columns(updated_at: 8.days.ago)
+
+ FinancekitInboxJob.perform_now
+
+ assert_nil batch.reload.payload
+ assert_equal "applied", batch.status
+ assert_not_nil batch.payload_digest
+ end
+
+ test "payload bytes from permanently failed batches are removed after the bounded replay window" do
+ first, = accept_batch
+ second, = accept_batch(financekit_payload(sequence: 2, predecessor_digest: "0" * 64, events: []))
+ FinancekitInboxJob.perform_now(@item.id)
+ second.update_columns(updated_at: 8.days.ago)
+
+ FinancekitInboxJob.perform_now
+
+ assert_equal "applied", first.reload.status
+ assert_equal "failed", second.reload.status
+ assert_nil second.payload
+ assert_not_nil second.payload_digest
+ end
+ test "future transaction status remains source-only instead of failing the stream" do
+ payload = financekit_payload
+ transaction = payload.fetch("events").find { |event| event["kind"] == "transaction_upsert" }.fetch("transaction")
+ transaction["status"] = "unknown"
+
+ batch = accept_and_apply(payload)
+
+ assert_equal "applied", batch.status
+ assert_equal "active", @item.reload.status
+ assert_empty @source.account.entries
+ assert_equal "unknown", @source.financekit_transactions.find_by!(source_id: @transaction_id).status
+ end
+end
diff --git a/test/models/financekit/lifecycle_test.rb b/test/models/financekit/lifecycle_test.rb
new file mode 100644
index 0000000000..71a885d734
--- /dev/null
+++ b/test/models/financekit/lifecycle_test.rb
@@ -0,0 +1,149 @@
+require "test_helper"
+require_relative "../../support/financekit_test_helper"
+
+class Financekit::LifecycleTest < ActiveSupport::TestCase
+ include FinancekitTestHelper
+
+ setup { financekit_setup }
+
+ test "another provider cannot attach to a FinanceKit canonical account" do
+ assert_raises(ActiveRecord::RecordInvalid) do
+ @source.account.account_providers.create!(provider: plaid_accounts(:one))
+ end
+ end
+
+ test "a provider link pointing at a missing account is invalid rather than raising" do
+ provider_link = AccountProvider.new(account_id: SecureRandom.uuid, provider: plaid_accounts(:one))
+
+ assert_not provider_link.valid?
+ assert_includes provider_link.errors[:account], "must exist"
+ end
+
+ test "a source account cannot link to another family" do
+ other = users(:empty)
+ account = other.family.accounts.create!(owner: other, name: "Other household", currency: "USD", balance: 25,
+ accountable: Depository.new(subtype: "checking"))
+ new_source = SecureRandom.uuid
+ @item.update!(status: "repair_required", consent: @item.consent.merge(
+ "selected_source_account_ids" => [ @source_id, new_source ]))
+
+ assert_raises(ActiveRecord::RecordNotFound) do
+ FinancekitAccount.map!(@item, new_source, @mapping_input.except("booked_balance", "observed_at").merge(
+ "action" => "link", "account_id" => account.id))
+ end
+ end
+
+ test "family reset removes publisher source records without touching another family" do
+ Provider::Plaid.any_instance.stubs(:remove_item)
+ other = users(:empty)
+ other.update!(preferences: other.preferences.merge("preview_features_enabled" => true))
+ source_id = SecureRandom.uuid
+ enrollment = @enrollment.deep_dup
+ enrollment["enrollment_id"] = SecureRandom.uuid
+ enrollment["consent"]["selected_source_account_ids"] = [ source_id ]
+ other_item = Financekit::Enrollment.create!(other, enrollment).item
+ accept_and_apply
+
+ Family::FinancialDataReset.new(family: @family, dry_run: false, confirmed: true).call
+
+ assert_not FinancekitItem.exists?(@item.id)
+ assert_not FinancekitAccountLineage.where(family: @family).exists?
+ assert FinancekitItem.exists?(other_item.id)
+ end
+
+ test "disconnect revokes the restricted credential and releases the canonical writer" do
+ account = @source.account
+ credential = @credential
+
+ @item.disconnect!
+
+ assert_equal "revoked", @item.reload.status
+ assert_not @item.authenticate_credential?(credential)
+ assert_nil @source.financekit_account_lineage.reload.account_provider
+ assert_not account.reload.linked?
+ end
+
+ test "replacement enrollment reuses lineage and source identity without duplicating ledger entries" do
+ accept_and_apply
+ account = @source.account
+ entry = account.entries.sole
+ lineage = @source.financekit_account_lineage
+
+ replacement_enrollment = @enrollment.deep_dup
+ replacement_enrollment["enrollment_id"] = SecureRandom.uuid
+ replacement_enrollment["replaces_connection_id"] = @item.id
+ replacement = Financekit::Enrollment.create!(@user, replacement_enrollment).item
+ input = @mapping_input.except("booked_balance", "observed_at").merge(
+ "action" => "link", "account_id" => account.id, "lineage_id" => lineage.id)
+ replacement_mapping = FinancekitAccount.map!(replacement, @source_id, input)
+ assert_equal 2, replacement_mapping.mapping_version
+ assert_no_difference "FinancekitAccount.count" do
+ assert_equal replacement_mapping, FinancekitAccount.map!(replacement, @source_id, input)
+ end
+ error = assert_raises(Financekit::Error) do
+ FinancekitAccount.map!(replacement, @source_id, input.merge("name" => "Changed mapping"))
+ end
+ assert_equal "mapping_conflict", error.code
+ replacement.activate!
+ @source = replacement_mapping
+ payload = financekit_payload(item: replacement)
+
+ accept_and_apply(payload, item: replacement)
+
+ @item.disconnect!
+
+ assert_equal [ entry.id ], account.entries.reload.pluck(:id)
+ assert_equal lineage, FinancekitTransaction.find_by!(source_id: @transaction_id).financekit_account_lineage
+ assert_equal "revoked", @item.reload.status
+ assert_equal lineage, account.reload.account_providers.sole.provider
+ assert_equal @item.generation + 1, replacement.generation
+ error = assert_raises(Financekit::Error) do
+ @item.update_column(:status, "repair_required")
+ @item.repair!
+ end
+ assert_equal "lineage_writer_conflict", error.code
+ end
+
+ test "purging a publisher user releases provider links without another active writer" do
+ account = @source.account
+ lineage = @source.financekit_account_lineage
+
+ @user.purge
+
+ assert_not FinancekitItem.exists?(@item.id)
+ assert_nil lineage.reload.account_provider
+ assert_not account.reload.linked?
+ end
+
+ test "repair fences accepted work and starts a new generation and stream" do
+ queued, = accept_batch
+ old_stream = @item.stream_id
+ old_credential = @credential
+
+ new_credential = @item.repair!
+
+ assert_equal "revoked", queued.reload.status
+ assert_equal "generation_replaced", queued.error_code
+ assert_equal 2, @item.reload.generation
+ assert_not_equal old_stream, @item.stream_id
+ assert_not @item.authenticate_credential?(old_credential)
+ assert @item.authenticate_credential?(new_credential)
+ assert_equal 1, @item.next_sequence
+ assert_nil @item.predecessor_digest
+ end
+
+ test "repair requires every selected mapping to still have an account" do
+ @source.financekit_account_lineage.update!(account: nil)
+ @item.update!(status: "repair_required")
+
+ error = assert_raises(Financekit::Error) { @item.repair! }
+
+ assert_equal "account_setup_required", error.code
+ assert_equal "repair_required", @item.reload.status
+ end
+
+ test "background publisher is not part of server initiated family sync" do
+ assert_empty @family.financekit_items.syncable
+ assert_nil @item.last_imported_at
+ end
+end
diff --git a/test/models/financekit/mapping_test.rb b/test/models/financekit/mapping_test.rb
new file mode 100644
index 0000000000..73f841b707
--- /dev/null
+++ b/test/models/financekit/mapping_test.rb
@@ -0,0 +1,297 @@
+require "test_helper"
+require_relative "../../support/financekit_test_helper"
+
+class Financekit::MappingTest < ActiveSupport::TestCase
+ include FinancekitTestHelper
+
+ setup { financekit_setup }
+
+ test "lossless signs include zero large values and non-two-decimal currencies" do
+ %w[0 1 1.234 999999999999999.9999].each do |amount|
+ assert_equal BigDecimal(amount), Financekit::Mapping.transaction_amount("amount" => money(amount, "debit"))
+ assert_equal(-BigDecimal(amount), Financekit::Mapping.transaction_amount("amount" => money(amount, "credit")))
+ end
+ assert_equal BigDecimal("42"), Financekit::Mapping.balance(money("42", "credit"), "Depository")
+ assert_equal BigDecimal("42"), Financekit::Mapping.balance(money("42", "debit"), "CreditCard")
+ assert_equal BigDecimal("100"), Financekit::Payload.money!(money("100", "debit", "JPY"))
+ assert_equal BigDecimal("1.234"), Financekit::Payload.money!(money("1.234", "debit", "KWD"))
+ end
+
+ test "invalid numeric representations and currency defaults are rejected" do
+ [ 1.23, "-1", "NaN", "1e2", "1.12345", "1000000000000000" ].each do |amount|
+ assert_raises(Financekit::Error) { Financekit::Payload.money!(money(amount)) }
+ end
+ assert_raises(Financekit::Error) { Financekit::Payload.money!(money("1", "debit", "NOPE")) }
+ assert_raises(Financekit::Error) { Financekit::Payload.money!(money.except("currency")) }
+ end
+
+ test "ledger date uses the confirmed account timezone at a month boundary" do
+ record = { "transacted_at" => "2026-03-01T00:30:00Z" }
+ assert_equal Date.new(2026, 2, 28), Financekit::Mapping.ledger_date(record, "America/Los_Angeles")
+ record["posted_at"] = "2026-03-01T08:30:00Z"
+ assert_equal Date.new(2026, 3, 1), Financekit::Mapping.ledger_date(record, "America/Los_Angeles")
+ end
+
+ test "a malformed event rejects the whole batch before it enters the inbox" do
+ events = financekit_events
+ events.last.fetch("transaction")["amount"]["amount"] = 12.34
+ payload = financekit_payload(events: events)
+
+ assert_no_difference "FinancekitBatch.count" do
+ error = assert_raises(Financekit::Error) { accept_batch(payload) }
+ assert_equal "invalid_payload", error.code
+ end
+ assert_empty @source.account.entries
+ end
+
+ test "imports never claim an ambiguous manual transaction" do
+ account = @source.account
+ manual = account.entries.create!(amount: "12.34", currency: "USD", date: Date.new(2026, 9, 1),
+ name: "Manual purchase", entryable: Transaction.new)
+
+ accept_and_apply
+
+ assert_equal 2, account.entries.count
+ assert_nil manual.reload.external_id
+ end
+
+ test "same source identity moves pending to booked without replacing user edits" do
+ pending_events = financekit_events
+ pending = pending_events.last.fetch("transaction")
+ pending["status"] = "pending"
+ pending.delete("posted_at")
+ first = accept_and_apply(financekit_payload(events: pending_events))
+ entry = @source.account.entries.sole
+ entry.update!(name: "My edited purchase", user_modified: true)
+
+ accept_and_apply(financekit_payload(sequence: 2, predecessor_digest: first.payload_digest))
+
+ assert_equal "My edited purchase", entry.reload.name
+ assert_not entry.transaction.reload.pending?
+ assert_equal 1, @source.account.entries.count
+ end
+
+ test "explicit tombstones retract only provider-owned entries and prevent resurrection" do
+ first = accept_and_apply
+ tombstone = {
+ "kind" => "transaction_tombstone",
+ "tombstone" => {
+ "source_id" => @transaction_id,
+ "source_account_id" => @source_id,
+ "lineage_id" => @source.financekit_account_lineage_id,
+ "mapping_version" => @source.mapping_version
+ }
+ }
+ second = accept_and_apply(financekit_payload(sequence: 2, predecessor_digest: first.payload_digest,
+ events: [ tombstone ]))
+
+ assert_empty @source.account.entries.reload
+ assert @source.financekit_transactions.sole.tombstoned_at?
+
+ third = accept_and_apply(financekit_payload(sequence: 3, predecessor_digest: second.payload_digest,
+ events: [ financekit_events.last ]))
+ assert_empty @source.account.entries.reload
+ assert_equal 1, third.counts.fetch("review_required")
+ assert_equal "source_reappeared", @item.financekit_conflicts.sole.kind
+ end
+
+ test "reconciled entries retain ledger fields and produce a conflict on upsert" do
+ first = accept_and_apply
+ entry = @source.account.entries.sole
+ entry.mark_reconciled!
+ original = entry.attributes.slice("amount", "date", "name", "reconciled_at")
+ event = financekit_events.last
+ event["transaction"]["amount"] = money("99.00")
+ event["transaction"]["posted_at"] = "2026-09-02T12:00:00Z"
+ event["transaction"]["merchant_name"] = "Changed shop"
+
+ batch = accept_and_apply(financekit_payload(sequence: 2, predecessor_digest: first.payload_digest, events: [ event ]))
+
+ assert_equal original, entry.reload.attributes.slice(*original.keys)
+ assert_equal 1, batch.counts.fetch("review_required")
+ assert_equal "protected_entry", @item.financekit_conflicts.sole.kind
+ end
+
+ test "attribute locks protect entries even without user_modified" do
+ first = accept_and_apply
+ entry = @source.account.entries.sole
+ entry.lock_attr!(:amount)
+ assert_not entry.user_modified?
+ event = financekit_events.last
+ event["transaction"]["amount"] = money("99.00")
+
+ accept_and_apply(financekit_payload(sequence: 2, predecessor_digest: first.payload_digest, events: [ event ]))
+
+ assert_equal BigDecimal("12.34"), entry.reload.amount
+ assert_equal "protected_entry", @item.financekit_conflicts.sole.kind
+ end
+
+ test "transfer pairs are protected from upserts and tombstones" do
+ first = accept_and_apply
+ entry = @source.account.entries.sole
+ other_account = @family.accounts.create!(name: "Transfer destination", balance: 0, currency: "USD",
+ accountable: Depository.new(subtype: "checking"))
+ other = other_account.entries.create!(name: "Transfer in", amount: -entry.amount, currency: entry.currency,
+ date: entry.date, entryable: Transaction.new)
+ transfer = Transfer.create!(inflow_transaction: other.transaction, outflow_transaction: entry.transaction)
+ event = financekit_events.last
+ event["transaction"]["amount"] = money("99.00")
+ second = accept_and_apply(financekit_payload(sequence: 2, predecessor_digest: first.payload_digest, events: [ event ]))
+ tombstone = { "kind" => "transaction_tombstone",
+ "tombstone" => event["transaction"].slice("source_id", "source_account_id", "lineage_id", "mapping_version") }
+
+ accept_and_apply(financekit_payload(sequence: 3, predecessor_digest: second.payload_digest, events: [ tombstone ]))
+
+ assert_equal BigDecimal("12.34"), entry.reload.amount
+ assert Transfer.exists?(transfer.id)
+ assert_equal %w[protected_entry protected_tombstone], @item.financekit_conflicts.order(:kind).pluck(:kind)
+ end
+
+ test "an edited pending entry still settles while its conflict awaits review" do
+ event = financekit_events.last
+ event["transaction"]["status"] = "pending"
+ event["transaction"].delete("posted_at")
+ first = accept_and_apply(financekit_payload(events: [ event ]))
+ entry = @source.account.entries.sole
+ entry.update!(name: "User name", user_modified: true)
+ second = accept_and_apply(financekit_payload(sequence: 2, predecessor_digest: first.payload_digest, events: [ event ]))
+ assert @source.financekit_transactions.sole.review_required?
+
+ accept_and_apply(financekit_payload(sequence: 3, predecessor_digest: second.payload_digest, events: [ financekit_events.last ]))
+
+ assert_equal "User name", entry.reload.name
+ assert_not entry.transaction.reload.pending?
+ assert_equal 1, @item.financekit_conflicts.open.count
+ end
+
+ test "retry after repair permits an unlocked transaction to import again" do
+ first = accept_and_apply
+ entry = @source.account.entries.sole
+ entry.update!(import_locked: true)
+ event = financekit_events.last
+ event["transaction"]["amount"] = money("99.00")
+ accept_and_apply(financekit_payload(sequence: 2, predecessor_digest: first.payload_digest, events: [ event ]))
+ conflict = @item.financekit_conflicts.sole
+
+ entry.unlock_for_sync!
+ conflict.resolve!(user: @user, resolution: "retry_after_repair")
+ assert_equal "repair_required", @item.reload.status
+ @item.repair!
+ batch = accept_and_apply(financekit_payload(events: [ event ]))
+
+ assert_equal BigDecimal("99.00"), entry.reload.amount
+ assert_equal 1, batch.counts.fetch("upserted")
+ assert_not @source.financekit_transactions.sole.review_required?
+ assert_empty @item.financekit_conflicts.open
+ end
+
+ test "conflicting balance observation reuse preserves the stored and canonical money" do
+ first = accept_and_apply
+ event = financekit_events.find { |record| record["kind"] == "balance_upsert" }
+ event["balance"]["money"] = money("999.00", "credit")
+ second, = accept_batch(financekit_payload(sequence: 2, predecessor_digest: first.payload_digest, events: [ event ]))
+
+ assert_not Financekit::Processor.new(@item).apply_next!
+
+ assert_equal "balance_observation_conflict", second.reload.error_code
+ assert_equal "failed", second.status
+ assert_equal BigDecimal("112.66"), @source.account.reload.balance
+ assert_equal BigDecimal("112.66"), @source.financekit_balance_observations.sole.amount
+ end
+
+ test "a second wallet account cannot map onto an already mapped canonical account" do
+ other_source = SecureRandom.uuid
+ @item.update!(status: "repair_required", consent: @item.consent.merge(
+ "selected_source_account_ids" => [ @source_id, other_source ]))
+
+ error = assert_raises(Financekit::Error) do
+ FinancekitAccount.map!(@item, other_source, @mapping_input.except("booked_balance", "observed_at").merge(
+ "action" => "link", "account_id" => @source.account.id))
+ end
+
+ assert_equal "lineage_account_conflict", error.code
+ assert_equal 409, error.status
+ end
+
+ test "a conflict resolved with keep_sure is not reopened by later captures" do
+ first = accept_and_apply
+ tombstone = {
+ "kind" => "transaction_tombstone",
+ "tombstone" => {
+ "source_id" => @transaction_id,
+ "source_account_id" => @source_id,
+ "lineage_id" => @source.financekit_account_lineage_id,
+ "mapping_version" => @source.mapping_version
+ }
+ }
+ second = accept_and_apply(financekit_payload(sequence: 2, predecessor_digest: first.payload_digest,
+ events: [ tombstone ]))
+ third = accept_and_apply(financekit_payload(sequence: 3, predecessor_digest: second.payload_digest,
+ events: [ financekit_events.last ]))
+ conflict = @item.financekit_conflicts.sole
+ conflict.resolve!(user: @user, resolution: "keep_sure")
+
+ fourth = accept_and_apply(financekit_payload(sequence: 4, predecessor_digest: third.payload_digest,
+ events: [ financekit_events.last ]))
+
+ assert_equal 1, @item.financekit_conflicts.count
+ assert_equal "resolved", conflict.reload.status
+ assert_equal 1, fourth.counts.fetch("settled")
+ assert_empty @source.account.entries.reload
+ assert_not @source.financekit_transactions.sole.review_required?
+ end
+
+ test "a replacement identity awaiting review is not imported by the next capture" do
+ accept_and_apply
+ account = @source.account
+ lineage = @source.financekit_account_lineage
+
+ replacement_enrollment = @enrollment.deep_dup
+ replacement_enrollment["enrollment_id"] = SecureRandom.uuid
+ replacement_enrollment["replaces_connection_id"] = @item.id
+ replacement = Financekit::Enrollment.create!(@user, replacement_enrollment).item
+ @source = FinancekitAccount.map!(replacement, @source_id,
+ @mapping_input.except("booked_balance", "observed_at").merge(
+ "action" => "link", "account_id" => account.id, "lineage_id" => lineage.id))
+ replacement.activate!
+
+ unknown_identity = financekit_events.last
+ unknown_identity.fetch("transaction")["source_id"] = SecureRandom.uuid
+ first = accept_and_apply(financekit_payload(item: replacement, events: [ unknown_identity ]),
+ item: replacement)
+
+ assert_equal 1, first.counts.fetch("review_required")
+ assert_equal "replacement_identity", replacement.financekit_conflicts.sole.kind
+ assert_equal 1, account.entries.reload.count
+
+ second = accept_and_apply(financekit_payload(sequence: 2, predecessor_digest: first.payload_digest,
+ item: replacement, events: [ unknown_identity ]), item: replacement)
+
+ assert_equal 1, second.counts.fetch("review_required")
+ assert_equal 1, account.entries.reload.count
+ assert_equal 1, replacement.financekit_conflicts.count
+
+ replacement.financekit_conflicts.sole.resolve!(user: @user, resolution: "retry_after_repair")
+ replacement.repair!
+ repaired = accept_and_apply(financekit_payload(item: replacement, events: [ unknown_identity ]), item: replacement)
+
+ assert_equal 1, repaired.counts.fetch("upserted")
+ assert_equal 2, account.entries.reload.count
+ assert_empty replacement.financekit_conflicts.open
+ end
+
+ test "balance observations are retained while only the latest booked value is materialized" do
+ first = accept_and_apply
+ second_events = financekit_events.select { |event| event["kind"] == "balance_upsert" }
+ second_balance = second_events.sole.fetch("balance")
+ second_balance["source_id"] = SecureRandom.uuid
+ second_balance["observed_at"] = 1.minute.from_now.iso8601
+ second_balance["money"] = money("111.25", "credit")
+
+ accept_and_apply(financekit_payload(sequence: 2, predecessor_digest: first.payload_digest,
+ events: second_events, captured_at: 1.minute.from_now.iso8601))
+
+ assert_equal 2, @source.financekit_balance_observations.count
+ assert_equal BigDecimal("111.25"), @source.account.reload.balance
+ end
+end
diff --git a/test/models/user_test.rb b/test/models/user_test.rb
index 8cc7b95651..8e484355fa 100644
--- a/test/models/user_test.rb
+++ b/test/models/user_test.rb
@@ -724,6 +724,78 @@ class UserTest < ActiveSupport::TestCase
assert_equal user, plaid_item.owner
end
+ test "transfer_to_family! moves unmapped FinanceKit items owned by the user" do
+ user = users(:family_member)
+ source_family = user.family
+ new_family = Family.create!(name: "Transferred FinanceKit Family")
+ user.update!(role: "admin", preferences: user.preferences.merge("preview_features_enabled" => true))
+ financekit_item = Financekit::Enrollment.create!(user, {
+ "enrollment_id" => SecureRandom.uuid,
+ "protocol_version" => Financekit::VERSION,
+ "consent" => {
+ "version" => 1,
+ "granted_at" => Time.current.iso8601,
+ "selected_source_account_ids" => [ SecureRandom.uuid ],
+ "upload_authorized" => true,
+ "family_visibility_acknowledged" => true,
+ "remote_processing_acknowledged" => true
+ }
+ }).item
+
+ user.transfer_to_family!(new_family, role: "admin")
+
+ assert_equal new_family, user.reload.family
+ assert_equal new_family, financekit_item.reload.family
+ assert financekit_item.pending_account_setup?
+ assert_not_equal source_family, financekit_item.family
+ end
+
+ test "transfer_to_family! rejects FinanceKit lineages mapped by another user" do
+ user = users(:family_member)
+ other_user = users(:family_admin)
+ source_family = user.family
+ new_family = Family.create!(name: "Rejected FinanceKit Family")
+ moved_account = Account.create!(family: source_family, owner: user, name: "Shared FinanceKit Checking",
+ balance: 100, currency: "USD", accountable: Depository.new(subtype: "checking"))
+ AccountShare.create!(account: moved_account, user: other_user, permission: "full_control")
+ other_user.update!(preferences: other_user.preferences.merge("preview_features_enabled" => true))
+ source_id = SecureRandom.uuid
+ financekit_item = Financekit::Enrollment.create!(other_user, {
+ "enrollment_id" => SecureRandom.uuid,
+ "protocol_version" => Financekit::VERSION,
+ "consent" => {
+ "version" => 1,
+ "granted_at" => Time.current.iso8601,
+ "selected_source_account_ids" => [ source_id ],
+ "upload_authorized" => true,
+ "family_visibility_acknowledged" => true,
+ "remote_processing_acknowledged" => true
+ }
+ }).item
+ FinancekitAccount.map!(financekit_item, source_id, {
+ "expected_version" => 0,
+ "action" => "link",
+ "account_id" => moved_account.id,
+ "name" => "Shared FinanceKit Checking",
+ "institution_name" => "Apple Wallet",
+ "currency" => "USD",
+ "accountable_type" => "Depository",
+ "subtype" => "checking",
+ "ledger_timezone" => "America/New_York"
+ })
+ financekit_item.activate!
+
+ error = assert_raises(ActiveRecord::RecordInvalid) do
+ user.transfer_to_family!(new_family, role: "admin")
+ end
+
+ assert_includes error.record.errors[:base], I18n.t("activerecord.errors.models.user.attributes.base.provider_item_has_other_accounts")
+ assert_equal source_family, user.reload.family
+ assert_equal source_family, moved_account.reload.family
+ assert_equal source_family, financekit_item.reload.family
+ assert_equal source_family, financekit_item.financekit_account_lineages.sole.reload.family
+ end
+
test "transfer_to_family! rejects provider items linked to accounts outside the transfer" do
user = users(:family_member)
other_user = users(:family_admin)
diff --git a/test/support/financekit_test_helper.rb b/test/support/financekit_test_helper.rb
new file mode 100644
index 0000000000..e2ecc43c33
--- /dev/null
+++ b/test/support/financekit_test_helper.rb
@@ -0,0 +1,126 @@
+module FinancekitTestHelper
+ def financekit_setup(user: users(:family_admin))
+ travel_to Time.utc(2026, 9, 10, 12)
+ @user = user
+ @user.update!(preferences: @user.preferences.merge("preview_features_enabled" => true))
+ @family = @user.family
+ Financekit.stubs(:enabled?).returns(true)
+ @source_id = "11111111-1111-4111-8111-111111111111"
+ @balance_id = "22222222-2222-4222-8222-222222222222"
+ @transaction_id = "33333333-3333-4333-8333-333333333333"
+ @enrollment = {
+ "enrollment_id" => SecureRandom.uuid,
+ "protocol_version" => Financekit::VERSION,
+ "consent" => {
+ "version" => 1,
+ "granted_at" => Time.current.iso8601,
+ "selected_source_account_ids" => [ @source_id ],
+ "upload_authorized" => true,
+ "family_visibility_acknowledged" => true,
+ "remote_processing_acknowledged" => true
+ }
+ }
+ @item = Financekit::Enrollment.create!(@user, @enrollment).item
+ @mapping_input = {
+ "expected_version" => 0,
+ "action" => "create",
+ "name" => "Test Wallet",
+ "institution_name" => "Apple Wallet",
+ "currency" => "USD",
+ "accountable_type" => "Depository",
+ "subtype" => "checking",
+ "ledger_timezone" => "America/Los_Angeles",
+ "booked_balance" => money("125.00", "credit"),
+ "observed_at" => Time.current.iso8601
+ }
+ @source = FinancekitAccount.map!(@item, @source_id, @mapping_input)
+ @credential = @item.activate!
+ end
+
+ def money(amount = "12.34", direction = "debit", currency = "USD")
+ { "amount" => amount, "currency" => currency, "direction" => direction }
+ end
+
+ def financekit_payload(sequence: 1, predecessor_digest: nil, events: financekit_events,
+ item: @item, captured_at: Time.current.iso8601)
+ payload = {
+ "protocol_version" => Financekit::VERSION,
+ "connection_id" => item.id,
+ "publisher_id" => item.publisher_id,
+ "generation" => item.generation,
+ "stream_id" => item.stream_id,
+ "batch_id" => SecureRandom.uuid,
+ "sequence" => sequence,
+ "capture_id" => SecureRandom.uuid,
+ "chunk_index" => 0,
+ "chunk_count" => 1,
+ "capture_mode" => "delta",
+ "snapshot_complete" => false,
+ "captured_at" => captured_at,
+ "selected_source_account_ids" => item.consented_source_ids,
+ "events" => events
+ }
+ payload["predecessor_digest"] = predecessor_digest if predecessor_digest
+ payload
+ end
+
+ def financekit_events
+ now = Time.current.iso8601
+ [
+ {
+ "kind" => "account_upsert",
+ "account" => {
+ "source_id" => @source_id,
+ "lineage_id" => @source.financekit_account_lineage_id,
+ "mapping_version" => @source.mapping_version,
+ "display_name" => "Test Wallet",
+ "institution_name" => "Apple Wallet",
+ "currency" => "USD",
+ "kind" => "asset"
+ }
+ },
+ {
+ "kind" => "balance_upsert",
+ "balance" => {
+ "source_id" => @balance_id,
+ "source_account_id" => @source_id,
+ "lineage_id" => @source.financekit_account_lineage_id,
+ "mapping_version" => @source.mapping_version,
+ "kind" => "booked",
+ "observed_at" => now,
+ "money" => money("112.66", "credit")
+ }
+ },
+ {
+ "kind" => "transaction_upsert",
+ "transaction" => {
+ "source_id" => @transaction_id,
+ "source_account_id" => @source_id,
+ "lineage_id" => @source.financekit_account_lineage_id,
+ "mapping_version" => @source.mapping_version,
+ "amount" => money,
+ "transaction_description" => "Synthetic shop",
+ "original_transaction_description" => "SYNTHETIC SHOP",
+ "transaction_type" => "purchase",
+ "status" => "booked",
+ "transacted_at" => "2026-09-01T06:00:00Z",
+ "posted_at" => "2026-09-01T07:00:00Z",
+ "merchant_name" => "Synthetic shop"
+ }
+ }
+ ]
+ end
+
+ def accept_batch(payload = financekit_payload, item: @item)
+ raw = JSON.generate(payload)
+ batch = FinancekitBatch.accept!(item, raw, claimed_digest: Digest::SHA256.hexdigest(raw),
+ idempotency_key: payload.fetch("batch_id"))
+ [ batch, raw ]
+ end
+
+ def accept_and_apply(payload = financekit_payload, item: @item)
+ batch, = accept_batch(payload, item: item)
+ assert Financekit::Processor.new(item).apply_next!
+ batch.reload
+ end
+end