bible270 1.17.2 → 1.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,97 @@
1
+ <%
2
+ config = Bible270.config
3
+ destinations = config.respond_to?(:progress_sync_destinations) ? config.progress_sync_destinations : {}
4
+ destinations = {} unless destinations.is_a?(Hash)
5
+ schema_available = Bible270::ProgressSync.available?
6
+ links = schema_available ? Bible270::ProgressSyncLink.joins(:participation)
7
+ .where(bible270_participations: { reader_id: @reader.id }).includes(:participation).order(created_at: :desc, id: :desc).to_a : []
8
+ %>
9
+ <% if destinations.any? || links.any? %>
10
+ <details class="b270-panel b270-admin-section" id="b270-progress-sync-panel">
11
+ <summary id="b270-progress-sync-heading">
12
+ <span class="b270-disclosure-show">Show Progress sync</span>
13
+ <span class="b270-disclosure-hide">Hide Progress sync</span>
14
+ </summary>
15
+ <section class="b270-progress-sync b270-admin-section-content" id="b270-progress-sync" aria-labelledby="b270-progress-sync-heading">
16
+ <p class="b270-hint">New check-offs sync one way to an account with the same email.</p>
17
+ <% unless schema_available %>
18
+ <p class="b270-flash alert">Progress sync needs a site update. Contact the site administrator.</p>
19
+ <% else %>
20
+ <% destination_options = destinations.filter_map do |key, entry|
21
+ next unless entry.is_a?(Hash)
22
+ [(entry[:label] || entry['label']).presence || key.to_s, key.to_s]
23
+ end %>
24
+ <% instance_configured = config.respond_to?(:progress_sync_instance_id) && config.progress_sync_instance_id.to_s.strip.present? %>
25
+ <% membership = Bible270::Participation.chosen.active.find_by(reader_id: @reader.id) %>
26
+ <% email_valid = @reader.email.to_s.bytesize <= 320 && @reader.email.to_s.strip.match?(%r{\A[^@\s]+@[^@\s]+\z}) %>
27
+ <% if destination_options.empty? || !instance_configured %>
28
+ <p class="b270-hint">Ask the site administrator to set up progress sync.</p>
29
+ <% elsif !membership %>
30
+ <p class="b270-hint">Make this reader active to link an account.</p>
31
+ <% elsif !email_valid %>
32
+ <p class="b270-hint">Add a valid email address to find an account.</p>
33
+ <% else %>
34
+ <% candidate_token = session[Bible270::AdminProgressSyncsController::CANDIDATE_SESSION_KEY] %>
35
+ <% candidate = Bible270::AdminProgressSyncsController.candidate_for(candidate_token, reader: @reader, admin: current_reader) %>
36
+ <%= form_with url: lookup_admin_reader_progress_sync_path(@reader), method: :post, local: true, class: 'b270-emailform' do %>
37
+ <label class="b270-field" for="b270-progress-sync-destination">Destination</label>
38
+ <span class="b270-select-wrap b270-select-wrap--full">
39
+ <%= select_tag :destination, options_for_select(destination_options, candidate && candidate['destination']),
40
+ id: 'b270-progress-sync-destination', class: 'b270-select' %>
41
+ </span>
42
+ <%= submit_tag 'Find account', class: 'b270-btn' %>
43
+ <% end %>
44
+ <% if candidate %>
45
+ <% remote = candidate.fetch('remote') %>
46
+ <div class="b270-progress-sync-candidate">
47
+ <p><strong><%= remote['name'] %></strong> · <%= remote['email'] %></p>
48
+ <p class="b270-hint">Confirm this account. Existing progress is copied only when requested.</p>
49
+ <%= form_with url: admin_reader_progress_syncs_path(@reader), method: :post, local: true, class: 'b270-emailform' do %>
50
+ <%= hidden_field_tag :candidate, candidate_token %>
51
+ <%= hidden_field_tag :destination, candidate['destination'] %>
52
+ <%= submit_tag 'Link account', class: 'b270-btn' %>
53
+ <% end %>
54
+ </div>
55
+ <% end %>
56
+ <% end %>
57
+
58
+ <% if links.empty? %>
59
+ <p class="b270-hint">No linked accounts.</p>
60
+ <% else %>
61
+ <ul class="b270-progress-sync-links">
62
+ <% links.each do |link| %>
63
+ <% entry = destinations[link.destination] %>
64
+ <% label = entry.is_a?(Hash) ? ((entry[:label] || entry['label']).presence || link.destination) : link.destination %>
65
+ <li class="b270-progress-sync-link">
66
+ <p><strong><%= label %></strong> · <%= link.remote_name %> · <%= link.status %></p>
67
+ <p class="b270-hint">
68
+ Run <%= link.participation.plan_run_id %> ·
69
+ Last synced: <%= link.last_synced_at ? b270_datetime(link.last_synced_at) : 'Never' %> ·
70
+ Pending: <%= link.pending_count %>
71
+ <% unless link.last_added.nil? || link.last_existing.nil? %>
72
+ · <%= link.last_added %> added; <%= link.last_existing %> already present
73
+ <% end %>
74
+ </p>
75
+ <% if link.last_error.present? %>
76
+ <p class="b270-flash alert"><%= link.last_error %></p>
77
+ <% end %>
78
+ <% usable = link.usable? %>
79
+ <% unless usable %>
80
+ <p class="b270-hint">Find and link the account again to resume syncing.</p>
81
+ <% end %>
82
+ <div class="b270-progress-sync-actions">
83
+ <% if usable %>
84
+ <%= button_to 'Sync existing progress', copy_admin_reader_progress_sync_path(@reader, link), method: :post,
85
+ class: 'b270-btn', form: { class: 'b270-admin-inline-form', data: { b270_admin_confirm: 'Sync existing progress? Only missing check-offs will be added. Nothing will be removed.' } } %>
86
+ <% end %>
87
+ <%= button_to 'Unlink', admin_reader_progress_sync_path(@reader, link), method: :delete,
88
+ class: 'b270-btn', form: { class: 'b270-admin-inline-form', data: { b270_admin_confirm: 'Unlink this account? Queued syncs will stop. All check-offs will remain.' } } %>
89
+ </div>
90
+ </li>
91
+ <% end %>
92
+ </ul>
93
+ <% end %>
94
+ <% end %>
95
+ </section>
96
+ </details>
97
+ <% end %>
@@ -0,0 +1,4 @@
1
+ <%# locals: (reader:, days_completed:, percentage: false) %>
2
+ <%= days_completed %>/<%= Bible270::Plan::DAYS %> days
3
+ <% if percentage %>· <%= (days_completed.to_f / Bible270::Plan::DAYS * 100).round %>%<% end %>
4
+ · <%= reader.progress_status(completed_days: days_completed) %>
@@ -19,8 +19,7 @@
19
19
  <%= reader.provider %>
20
20
  <% end %>
21
21
  <% if reader.dated? %>· started <%= reader.effective_start_date.strftime('%b %-d, %Y') %><% end %>
22
- · <%= days_completed[reader.id] %>/<%= Bible270::Plan::DAYS %> days
23
- · <%= report.status_for(reader) %>
22
+ · <%= render 'bible270/admin/reader_completion_summary', reader: reader, days_completed: days_completed[reader.id] %>
24
23
  </div>
25
24
  <% consistency = report.consistency_for(reader) %>
26
25
  <div class="sub b270-reader-consistency">
@@ -199,14 +199,31 @@
199
199
  </div>
200
200
 
201
201
 
202
- <div class="b270-panel">
203
- <%= render "bible270/shared/interaction_status" %>
204
- <%= render "bible270/shared/reflections", comments: @comments, moderate: true, editable: true, actions: true %>
205
- </div>
202
+ <%= render 'progress_sync' %>
206
203
 
204
+ <%= render "bible270/shared/interaction_status" %>
205
+ <details class="b270-panel b270-admin-section" id="b270-reader-reflections">
206
+ <summary>
207
+ <span class="b270-disclosure-show">Show Their reflections</span>
208
+ <span class="b270-disclosure-hide">Hide Their reflections</span>
209
+ </summary>
210
+ <div class="b270-admin-section-content">
211
+ <%= render "bible270/shared/reflections", comments: @comments, title: nil, moderate: true, editable: true, actions: true %>
212
+ </div>
213
+ </details>
207
214
 
208
- <div class="b270-panel">
209
- <h2 class="b270-subhead">Completions</h2>
215
+
216
+ <details class="b270-panel b270-admin-section" id="b270-reader-completions">
217
+ <summary>
218
+ <span class="b270-disclosure-label">
219
+ <span class="b270-disclosure-show">Show Completions</span>
220
+ <span class="b270-disclosure-hide">Hide Completions</span>
221
+ </span>
222
+ <span class="b270-completions-summary">
223
+ <%= render 'reader_completion_summary', reader: @reader, days_completed: @days_completed, percentage: true %>
224
+ </span>
225
+ </summary>
226
+ <div class="b270-admin-section-content">
210
227
  <% unless @reader.alumni? %>
211
228
  <%= form_with url: admin_reader_through_path(@reader), method: :patch, class: "b270-startform" do %>
212
229
  <%= hidden_field_tag :participation_id, @reader.participation.id %>
@@ -232,7 +249,8 @@
232
249
  <% end %>
233
250
  </div>
234
251
  <p class="b270-hint"><%= @reader.alumni? ? 'Archived completions are read-only.' : 'Click a day to toggle it complete.' %></p>
235
- </div>
252
+ </div>
253
+ </details>
236
254
 
237
255
  <% if @past_participations.any? %>
238
256
  <div class="b270-panel" id="b270-run-history">
@@ -516,6 +516,11 @@
516
516
  .b270-scripture-panel-header>.b270-subhead,.b270 .b270-scripture-panel-header>.b270-btn{margin:0}
517
517
  .b270-scripture-panel-header>.b270-subhead{min-width:0;overflow-wrap:anywhere}
518
518
  .b270 .b270-scripture-panel-header>.b270-btn{flex-shrink:0;padding:6px 10px;font-size:12.5px;white-space:nowrap}
519
+ .b270-progress-sync-links{list-style:none;padding:0;margin:12px 0 0}
520
+ .b270-progress-sync-link{padding:12px 0;border-top:1px solid var(--line-soft);overflow-wrap:anywhere}
521
+ .b270-progress-sync-link p,.b270-progress-sync-candidate p{margin:0 0 8px}
522
+ .b270-progress-sync-actions{display:flex;align-items:center;flex-wrap:wrap;gap:8px}
523
+ .b270-progress-sync-actions form,.b270-progress-sync-actions .b270-btn{margin:0}
519
524
  .b270-scripture-actions{display:flex;align-items:center;gap:10px;margin:0;white-space:nowrap}
520
525
  .b270-scripture-actions>form{margin:0}
521
526
  .b270-scripture-actions>a,.b270-scripture-actions .b270-linkbtn{margin:0;font-size:12.5px;color:var(--oxblood)}
@@ -774,6 +779,17 @@
774
779
  .b270-footer p{margin:0;line-height:1.5}
775
780
  details.b270-index>summary{cursor:pointer;font-family:"Spectral",serif;font-size:18px;font-weight:600;list-style:none;margin-top:30px}
776
781
  details.b270-index>summary::-webkit-details-marker{display:none}
782
+ details.b270-admin-section>summary{display:flex;align-items:center;flex-wrap:wrap;gap:8px 16px;cursor:pointer;
783
+ list-style:none;font-family:"Spectral",serif;font-size:18px;font-weight:600}
784
+ details.b270-admin-section>summary::-webkit-details-marker{display:none}
785
+ details.b270-admin-section>summary:focus-visible{outline:2px solid var(--gold);outline-offset:4px;border-radius:4px}
786
+ .b270-admin-section>summary .b270-disclosure-hide{display:none}
787
+ .b270-admin-section[open]>summary .b270-disclosure-show{display:none}
788
+ .b270-admin-section[open]>summary .b270-disclosure-hide{display:inline}
789
+ .b270-admin-section:not([open])>:not(summary){display:none}
790
+ .b270-admin-section-content{margin-top:12px}
791
+ .b270-disclosure-label{flex:none}
792
+ .b270-completions-summary{min-width:0;font-family:system-ui,sans-serif;font-size:12.5px;font-weight:400;color:var(--muted)}
777
793
  details.b270-active-readers{margin-bottom:24px}
778
794
  details.b270-active-readers>summary{margin:0 0 12px}
779
795
  details.b270-active-readers .b270-active-readers-hide{display:none}
data/config/routes.rb CHANGED
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  # Rails routes are intentionally kept in one cohesive DSL block.
4
- Bible270::Engine.routes.draw do
4
+ Bible270::Engine.routes.draw do # rubocop:disable Metrics/BlockLength
5
5
  root to: 'days#index'
6
6
  get 'scripture-frame', to: 'scripture_frames#show', as: :scripture_frame, defaults: { format: 'json' }
7
7
 
@@ -19,7 +19,15 @@ Bible270::Engine.routes.draw do
19
19
  patch 'comments/:id', to: 'comments#update'
20
20
  delete 'comments/:id', to: 'comments#destroy', as: :comment
21
21
 
22
+ # Server-to-server requests use signed instance credentials, never browser sessions.
23
+ post 'progress-sync/lookup', to: 'progress_sync#lookup', defaults: { format: :json }
24
+ post 'progress-sync/complete', to: 'progress_sync#complete', defaults: { format: :json }
25
+
22
26
  # Admin panel — configured site-admins and readers granted admin access.
27
+ post 'admin/readers/:reader_id/progress-sync/lookup', to: 'admin_progress_syncs#lookup', as: :lookup_admin_reader_progress_sync
28
+ post 'admin/readers/:reader_id/progress-sync', to: 'admin_progress_syncs#create', as: :admin_reader_progress_syncs
29
+ post 'admin/readers/:reader_id/progress-sync/:id/copy', to: 'admin_progress_syncs#copy', as: :copy_admin_reader_progress_sync
30
+ delete 'admin/readers/:reader_id/progress-sync/:id', to: 'admin_progress_syncs#destroy', as: :admin_reader_progress_sync
23
31
  patch 'admin/scripture-frame-defaults/:id', to: 'admin_scripture_frames#update_default', as: :admin_default_scripture_frame
24
32
  resources :admin_scripture_frames, path: 'admin/scripture-frames', only: %i[index new create edit update destroy]
25
33
  get 'admin', to: 'admin#index', as: :admin
@@ -92,6 +92,16 @@
92
92
  but it shall accomplish that which I purpose,
93
93
  and shall succeed in the thing for which I sent it.
94
94
  attribution: ESV © 2001 Crossway.
95
+ - id: isaiah-66-2
96
+ reference: Isaiah 66:2
97
+ translation: ESV
98
+ text: |-
99
+ All these things my hand has made,
100
+ and so all these things came to be, declares the LORD.
101
+ But this is the one to whom I will look:
102
+ he who is humble and contrite in spirit
103
+ and trembles at my word.
104
+ attribution: ESV © 2001 Crossway.
95
105
  - id: jeremiah-15-16
96
106
  reference: Jeremiah 15:16
97
107
  translation: NASB95
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ class CreateBible270ProgressSync < ActiveRecord::Migration[7.0]
4
+ def change
5
+ add_column :bible270_participations, :progress_sync_generation, :integer, null: false, default: 0
6
+
7
+ create_table :bible270_progress_sync_links do |t|
8
+ t.references :participation, null: false,
9
+ foreign_key: { to_table: :bible270_participations, on_delete: :cascade },
10
+ index: { name: 'idx_b270_sync_links_participation' }
11
+ t.integer :source_generation, null: false
12
+ t.string :destination, null: false
13
+ t.string :destination_url, null: false
14
+ t.bigint :remote_reader_id, null: false
15
+ t.bigint :remote_participation_id, null: false
16
+ t.integer :remote_generation, null: false
17
+ t.string :remote_name, null: false
18
+ t.string :email, null: false
19
+ t.string :plan_fingerprint, null: false
20
+ t.string :state, null: false, default: 'active'
21
+ t.datetime :last_synced_at
22
+ t.text :last_error
23
+ t.integer :last_added
24
+ t.integer :last_existing
25
+ t.timestamps
26
+ end
27
+ # Paused links retain their immutable target and delivery history. Explicit
28
+ # relinking creates a new row; old outbox entries can never change recipients.
29
+ add_index :bible270_progress_sync_links, %i[participation_id destination], unique: true,
30
+ where: "state = 'active'", name: 'idx_b270_sync_links_active_destination'
31
+
32
+ create_table :bible270_progress_sync_deliveries do |t|
33
+ t.references :progress_sync_link, null: false,
34
+ foreign_key: { to_table: :bible270_progress_sync_links, on_delete: :cascade },
35
+ index: { name: 'idx_b270_sync_deliveries_link' }
36
+ t.json :readings, null: false
37
+ t.integer :attempts, null: false, default: 0
38
+ t.datetime :next_attempt_at, null: false
39
+ t.datetime :locked_until
40
+ t.string :claim_token
41
+ t.datetime :delivered_at
42
+ t.text :last_error
43
+ t.timestamps
44
+ end
45
+ add_index :bible270_progress_sync_deliveries, %i[delivered_at next_attempt_at locked_until],
46
+ name: 'idx_b270_sync_deliveries_due'
47
+ end
48
+ end
@@ -287,6 +287,11 @@ module Bible270
287
287
  # are stored separately and supplement either the bundled or host catalog.
288
288
  attr_accessor :scripture_frames_path
289
289
 
290
+ # Explicit trust between installations; credentials stay in host configuration.
291
+ attr_accessor :progress_sync_instance_id, :progress_sync_destinations, :progress_sync_sources
292
+ # Enable only with a persistent Active Job adapter and a running worker.
293
+ attr_accessor :progress_sync_deliver_later
294
+
290
295
  # Who to email when someone new joins. Three forms:
291
296
  #
292
297
  # config.registration_notice_emails = %w[andrew@example.org] # an explicit list
@@ -373,6 +378,10 @@ module Bible270
373
378
  @mention_notifications = true
374
379
  @header_mark = nil
375
380
  @scripture_frames_path = nil
381
+ @progress_sync_instance_id = nil
382
+ @progress_sync_destinations = {}
383
+ @progress_sync_sources = {}
384
+ @progress_sync_deliver_later = false
376
385
  @remember_for = 365 * 24 * 60 * 60
377
386
  @require_sign_in_to_participate = true
378
387
  self.mount_at = '/daily-bread'
@@ -37,6 +37,7 @@ module Bible270
37
37
  'AddAdminToBible270Readers' => :check_admin,
38
38
  'AddRevertToBible270PlanRuns' => :check_run_revert,
39
39
  'CreateBible270ScriptureFrames' => :check_scripture_frames,
40
+ 'CreateBible270ProgressSync' => :check_progress_sync,
40
41
 
41
42
  'CreateActiveStorageTables' => :check_active_storage
42
43
  }.freeze
@@ -297,6 +298,15 @@ module Bible270
297
298
  enabled: { type: :boolean, null: false, default: true })
298
299
  end
299
300
 
301
+ def check_progress_sync
302
+ missing_progress_sync_columns(
303
+ :bible270_participations,
304
+ progress_sync_generation: { type: :integer, default: 0 }
305
+ ) + missing_progress_sync_columns(:bible270_progress_sync_links, progress_sync_link_columns) +
306
+ missing_progress_sync_columns(:bible270_progress_sync_deliveries, progress_sync_delivery_columns) +
307
+ progress_sync_relationships_missing + progress_sync_link_indexes_missing
308
+ end
309
+
300
310
  def check_admin
301
311
  table_missing(:bible270_readers, columns: %i[admin]) +
302
312
  missing_column_definitions(:bible270_readers, admin: { type: :boolean, null: false, default: false })
@@ -339,6 +349,125 @@ module Bible270
339
349
 
340
350
  attr_reader :connection, :migration_context
341
351
 
352
+ def progress_sync_link_columns
353
+ {
354
+ id: progress_sync_id_definition,
355
+ participation_id: progress_sync_id_definition,
356
+ source_generation: { type: :integer },
357
+ destination: { type: :string },
358
+ destination_url: { type: :string },
359
+ remote_reader_id: progress_sync_id_definition,
360
+ remote_participation_id: progress_sync_id_definition,
361
+ remote_generation: { type: :integer },
362
+ remote_name: { type: :string },
363
+ email: { type: :string },
364
+ plan_fingerprint: { type: :string },
365
+ state: { type: :string, default: 'active' },
366
+ last_synced_at: { type: :datetime, null: true },
367
+ last_error: { type: :text, null: true },
368
+ last_added: { type: :integer, null: true },
369
+ last_existing: { type: :integer, null: true },
370
+ created_at: { type: :datetime },
371
+ updated_at: { type: :datetime }
372
+ }
373
+ end
374
+
375
+ def progress_sync_delivery_columns
376
+ {
377
+ id: progress_sync_id_definition,
378
+ progress_sync_link_id: progress_sync_id_definition,
379
+ readings: { type: :json },
380
+ attempts: { type: :integer, default: 0 },
381
+ next_attempt_at: { type: :datetime },
382
+ locked_until: { type: :datetime, null: true },
383
+ claim_token: { type: :string, null: true },
384
+ delivered_at: { type: :datetime, null: true },
385
+ last_error: { type: :text, null: true },
386
+ created_at: { type: :datetime },
387
+ updated_at: { type: :datetime }
388
+ }
389
+ end
390
+
391
+ def progress_sync_id_definition
392
+ # SQLite uses 64-bit integers for both INTEGER references and bigint IDs.
393
+ { type: :integer, limit: connection.adapter_name == 'SQLite' ? nil : 8 }
394
+ end
395
+
396
+ def missing_progress_sync_columns(table, definitions)
397
+ definitions = definitions.to_h do |name, attributes|
398
+ definition = { null: false, default: nil, default_function: nil }.merge(attributes)
399
+ # PostgreSQL's generated primary key uses a sequence default.
400
+ definition.delete(:default_function) if name == :id
401
+ [name, definition]
402
+ end
403
+ table_missing(table, columns: definitions.keys) + missing_column_definitions(table, definitions)
404
+ end
405
+
406
+ def progress_sync_relationships_missing
407
+ table_missing(
408
+ :bible270_progress_sync_links,
409
+ columns: [],
410
+ indexes: [{ columns: %i[participation_id] }],
411
+ foreign_keys: [{ column: :participation_id, to_table: :bible270_participations, primary_key: :id, on_delete: :cascade }]
412
+ ) + table_missing(
413
+ :bible270_progress_sync_deliveries,
414
+ columns: [],
415
+ indexes: [{ columns: %i[progress_sync_link_id] }, { columns: %i[delivered_at next_attempt_at locked_until] }],
416
+ foreign_keys: [{ column: :progress_sync_link_id, to_table: :bible270_progress_sync_links, primary_key: :id, on_delete: :cascade }]
417
+ )
418
+ end
419
+
420
+ def progress_sync_link_indexes_missing
421
+ table = :bible270_progress_sync_links
422
+ return [] unless connection.data_source_exists?(table)
423
+
424
+ columns = %w[participation_id destination]
425
+ indexes = connection.indexes(table)
426
+ missing = []
427
+ unless indexes.any? { |index| index.columns == columns && index.unique && active_destination_predicate?(index.where) }
428
+ missing << "unique index #{table}(participation_id, destination) where state = 'active'"
429
+ end
430
+ if indexes.any? { |index| index.unique && index.where.nil? && index.columns.is_a?(Array) && index.columns.sort == columns.sort }
431
+ missing << "conflicting unconditional unique index #{table}(participation_id, destination)"
432
+ end
433
+ missing
434
+ end
435
+
436
+ def active_destination_predicate?(predicate)
437
+ operands = unwrap_index_expression(predicate.to_s.strip).split('=', -1)
438
+ return false unless operands.length == 2
439
+
440
+ ['state', '"state"'].include?(unwrap_index_text_operand(operands[0])) &&
441
+ unwrap_index_text_operand(operands[1]) == "'active'"
442
+ end
443
+
444
+ def unwrap_index_text_operand(expression)
445
+ loop do
446
+ expression = unwrap_index_expression(expression.strip)
447
+ uncast = expression.sub(%r{\s*::\s*(?:text|varchar|character\s+varying)\z}, '')
448
+ return expression if expression == uncast
449
+
450
+ expression = uncast
451
+ end
452
+ end
453
+
454
+ # Only peel enclosing pairs, never parentheses inside an identifier/literal
455
+ # or a broader expression. Operand matching then allows just state = 'active'.
456
+ def unwrap_index_expression(expression)
457
+ while expression.start_with?('(') && expression.end_with?(')')
458
+ depth = 0
459
+ closing = expression.each_char.with_index.find do |character, _index|
460
+ depth += 1 if character == '('
461
+ depth -= 1 if character == ')'
462
+ depth.zero?
463
+ end
464
+ break unless closing && closing.last == expression.length - 1
465
+
466
+ expression = expression[1...-1].strip
467
+ end
468
+ expression
469
+ end
470
+
342
471
  def table_missing(table, columns:, indexes: [], foreign_keys: [])
343
472
  return ["table #{table}"] unless connection.data_source_exists?(table)
344
473
 
@@ -361,6 +490,9 @@ module Bible270
361
490
  definitions.fetch(column.name.to_sym, {}).filter_map do |attribute, expected|
362
491
  actual = column.public_send(attribute)
363
492
  actual = ActiveModel::Type::Boolean.new.cast(actual) if attribute == :default && column.type == :boolean
493
+ if attribute == :default && column.type == :integer && actual.is_a?(String) && actual.match?(%r{\A[+-]?\d+\z})
494
+ actual = Integer(actual, 10)
495
+ end
364
496
  "column #{table}.#{column.name} #{attribute} #{expected}" unless actual == expected
365
497
  end
366
498
  end
@@ -394,6 +526,7 @@ module Bible270
394
526
  def matching_foreign_key?(foreign_key, expected)
395
527
  foreign_key.column.to_s == expected.fetch(:column).to_s &&
396
528
  foreign_key.to_table.to_s == expected.fetch(:to_table).to_s &&
529
+ (!expected.key?(:primary_key) || foreign_key.primary_key.to_s == expected[:primary_key].to_s) &&
397
530
  (!expected.key?(:on_delete) || foreign_key.on_delete == expected[:on_delete])
398
531
  end
399
532
  end
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'openssl'
4
+ require 'digest'
5
+ require 'active_support/security_utils'
6
+
7
+ module Bible270
8
+ module ProgressSync
9
+ module Authentication
10
+ VERSION = '1'
11
+ MAX_BYTES = 256 * 1024
12
+ TTL = 300
13
+ SOURCE_HEADER = 'X-Bible270-Sync-Source'
14
+ TIMESTAMP_HEADER = 'X-Bible270-Sync-Timestamp'
15
+ SIGNATURE_HEADER = 'X-Bible270-Sync-Signature'
16
+ VERSION_HEADER = 'X-Bible270-Sync-Version'
17
+
18
+ module_function
19
+
20
+ def valid_source?(source)
21
+ source.is_a?(String) && source.match?(%r{\A[A-Za-z0-9._:-]{1,128}\z})
22
+ end
23
+
24
+ def signature(secret:, source:, timestamp:, method:, path:, body:) # rubocop:disable Metrics/ParameterLists
25
+ message = [VERSION, source, timestamp, method.upcase, path, Digest::SHA256.hexdigest(body)].join("\n")
26
+ OpenSSL::HMAC.hexdigest('SHA256', secret, message)
27
+ end
28
+
29
+ def headers(secret:, source:, method:, path:, body:, timestamp: Time.now.to_i.to_s) # rubocop:disable Metrics/ParameterLists
30
+ {
31
+ SOURCE_HEADER => source, TIMESTAMP_HEADER => timestamp, VERSION_HEADER => VERSION,
32
+ SIGNATURE_HEADER => signature(secret: secret, source: source, timestamp: timestamp, method: method, path: path, body: body)
33
+ }
34
+ end
35
+
36
+ def authenticate!(headers:, sources:, method:, path:, body:, now: Time.now.to_i) # rubocop:disable Metrics/ParameterLists
37
+ source = headers[SOURCE_HEADER]
38
+ timestamp = headers[TIMESTAMP_HEADER]
39
+ supplied = headers[SIGNATURE_HEADER]
40
+ unless headers[VERSION_HEADER] == VERSION && valid_source?(source) &&
41
+ timestamp.is_a?(String) && timestamp.match?(%r{\A\d{1,12}\z}) &&
42
+ (now - timestamp.to_i).abs <= TTL && supplied.is_a?(String) && supplied.match?(%r{\A[0-9a-f]{64}\z})
43
+ raise Unauthorized, 'Progress sync authentication failed'
44
+ end
45
+
46
+ entry = sources.is_a?(Hash) ? sources[source] : nil
47
+ secret = entry.is_a?(Hash) ? (entry[:secret] || entry['secret']) : nil
48
+ unless secret.is_a?(String) && secret.length >= 32
49
+ raise Unauthorized, 'Progress sync authentication failed'
50
+ end
51
+
52
+ expected = signature(secret: secret, source: source, timestamp: timestamp, method: method, path: path, body: body)
53
+ unless ActiveSupport::SecurityUtils.secure_compare(expected, supplied)
54
+ raise Unauthorized, 'Progress sync authentication failed'
55
+ end
56
+
57
+ source
58
+ end
59
+ end
60
+ end
61
+ end