bible270 1.17.1 → 1.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,92 @@
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
+ <section class="b270-panel b270-progress-sync" id="b270-progress-sync" aria-labelledby="b270-progress-sync-heading">
11
+ <h2 class="b270-subhead" id="b270-progress-sync-heading">Progress sync</h2>
12
+ <p class="b270-hint">New check-offs sync one way to an account with the same email.</p>
13
+ <% unless schema_available %>
14
+ <p class="b270-flash alert">Progress sync needs a site update. Contact the site administrator.</p>
15
+ <% else %>
16
+ <% destination_options = destinations.filter_map do |key, entry|
17
+ next unless entry.is_a?(Hash)
18
+ [(entry[:label] || entry['label']).presence || key.to_s, key.to_s]
19
+ end %>
20
+ <% instance_configured = config.respond_to?(:progress_sync_instance_id) && config.progress_sync_instance_id.to_s.strip.present? %>
21
+ <% membership = Bible270::Participation.chosen.active.find_by(reader_id: @reader.id) %>
22
+ <% email_valid = @reader.email.to_s.bytesize <= 320 && @reader.email.to_s.strip.match?(%r{\A[^@\s]+@[^@\s]+\z}) %>
23
+ <% if destination_options.empty? || !instance_configured %>
24
+ <p class="b270-hint">Ask the site administrator to set up progress sync.</p>
25
+ <% elsif !membership %>
26
+ <p class="b270-hint">Make this reader active to link an account.</p>
27
+ <% elsif !email_valid %>
28
+ <p class="b270-hint">Add a valid email address to find an account.</p>
29
+ <% else %>
30
+ <% candidate_token = session[Bible270::AdminProgressSyncsController::CANDIDATE_SESSION_KEY] %>
31
+ <% candidate = Bible270::AdminProgressSyncsController.candidate_for(candidate_token, reader: @reader, admin: current_reader) %>
32
+ <%= form_with url: lookup_admin_reader_progress_sync_path(@reader), method: :post, local: true, class: 'b270-emailform' do %>
33
+ <label class="b270-field" for="b270-progress-sync-destination">Destination</label>
34
+ <span class="b270-select-wrap b270-select-wrap--full">
35
+ <%= select_tag :destination, options_for_select(destination_options, candidate && candidate['destination']),
36
+ id: 'b270-progress-sync-destination', class: 'b270-select' %>
37
+ </span>
38
+ <%= submit_tag 'Find account', class: 'b270-btn' %>
39
+ <% end %>
40
+ <% if candidate %>
41
+ <% remote = candidate.fetch('remote') %>
42
+ <div class="b270-progress-sync-candidate">
43
+ <p><strong><%= remote['name'] %></strong> · <%= remote['email'] %></p>
44
+ <p class="b270-hint">Confirm this account. Existing progress is copied only when requested.</p>
45
+ <%= form_with url: admin_reader_progress_syncs_path(@reader), method: :post, local: true, class: 'b270-emailform' do %>
46
+ <%= hidden_field_tag :candidate, candidate_token %>
47
+ <%= hidden_field_tag :destination, candidate['destination'] %>
48
+ <%= submit_tag 'Link account', class: 'b270-btn' %>
49
+ <% end %>
50
+ </div>
51
+ <% end %>
52
+ <% end %>
53
+
54
+ <% if links.empty? %>
55
+ <p class="b270-hint">No linked accounts.</p>
56
+ <% else %>
57
+ <ul class="b270-progress-sync-links">
58
+ <% links.each do |link| %>
59
+ <% entry = destinations[link.destination] %>
60
+ <% label = entry.is_a?(Hash) ? ((entry[:label] || entry['label']).presence || link.destination) : link.destination %>
61
+ <li class="b270-progress-sync-link">
62
+ <p><strong><%= label %></strong> · <%= link.remote_name %> · <%= link.status %></p>
63
+ <p class="b270-hint">
64
+ Run <%= link.participation.plan_run_id %> ·
65
+ Last synced: <%= link.last_synced_at ? link.last_synced_at.strftime('%b %-d, %Y %H:%M %Z') : 'Never' %> ·
66
+ Pending: <%= link.pending_count %>
67
+ <% unless link.last_added.nil? || link.last_existing.nil? %>
68
+ · <%= link.last_added %> added; <%= link.last_existing %> already present
69
+ <% end %>
70
+ </p>
71
+ <% if link.last_error.present? %>
72
+ <p class="b270-flash alert"><%= link.last_error %></p>
73
+ <% end %>
74
+ <% usable = link.usable? %>
75
+ <% unless usable %>
76
+ <p class="b270-hint">Find and link the account again to resume syncing.</p>
77
+ <% end %>
78
+ <div class="b270-progress-sync-actions">
79
+ <% if usable %>
80
+ <%= button_to 'Sync existing progress', copy_admin_reader_progress_sync_path(@reader, link), method: :post,
81
+ 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.' } } %>
82
+ <% end %>
83
+ <%= button_to 'Unlink', admin_reader_progress_sync_path(@reader, link), method: :delete,
84
+ 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.' } } %>
85
+ </div>
86
+ </li>
87
+ <% end %>
88
+ </ul>
89
+ <% end %>
90
+ <% end %>
91
+ </section>
92
+ <% end %>
@@ -1,10 +1,15 @@
1
1
  <section class="b270-panel" id="b270-scripture-frames" aria-labelledby="b270-scripture-frames-heading">
2
- <div class="b270-scripture-panel-header">
3
- <h2 class="b270-subhead" id="b270-scripture-frames-heading">Scripture frames</h2>
2
+ <details class="b270-index b270-scripture-frames" id="b270-scripture-frames-list"
3
+ data-b270-admin-disclosure-key="<%= "#{admin_path}:#{@active_readers_session_key}:scripture-frames" %>" open>
4
+ <summary class="b270-scripture-panel-header">
5
+ <span class="b270-subhead" id="b270-scripture-frames-heading">
6
+ <span class="b270-disclosure-show">Show Scripture frames</span>
7
+ <span class="b270-disclosure-hide">Hide Scripture frames</span>
8
+ </span>
4
9
  <% if @scripture_frame_storage %>
5
10
  <%= link_to 'Add text', new_admin_scripture_frame_path(sort: @reader_sort), class: 'b270-btn' %>
6
11
  <% end %>
7
- </div>
12
+ </summary>
8
13
  <% unless @scripture_frame_storage %>
9
14
  <p class="b270-hint">Run the pending database migration to add custom texts.</p>
10
15
  <% end %>
@@ -31,4 +36,5 @@
31
36
  <% end %>
32
37
  </div>
33
38
  <% end %>
39
+ </details>
34
40
  </section>
@@ -199,6 +199,8 @@
199
199
  </div>
200
200
 
201
201
 
202
+ <%= render 'progress_sync' %>
203
+
202
204
  <div class="b270-panel">
203
205
  <%= render "bible270/shared/interaction_status" %>
204
206
  <%= render "bible270/shared/reflections", comments: @comments, moderate: true, editable: true, actions: true %>
@@ -5,14 +5,18 @@
5
5
  return;
6
6
  }
7
7
 
8
- const selector = "details[data-b270-active-readers-key]";
8
+ const selector = "details[data-b270-active-readers-key], details[data-b270-admin-disclosure-key]";
9
9
  const initialized = new WeakSet();
10
10
  const states = new Map();
11
- const keyFor = (element) => `b270-active-readers:${element.dataset.b270ActiveReadersKey}`;
11
+ const keyFor = (element) => {
12
+ if (element.dataset.b270AdminDisclosureKey) return `b270-admin-disclosure:${element.dataset.b270AdminDisclosureKey}`;
13
+ if (element.dataset.b270ActiveReadersKey) return `b270-active-readers:${element.dataset.b270ActiveReadersKey}`;
14
+ return null;
15
+ };
12
16
 
13
17
  function remember(element) {
14
- if (!element.isConnected || !element.dataset.b270ActiveReadersKey) return;
15
18
  const key = keyFor(element);
19
+ if (!element.isConnected || !key) return;
16
20
  const value = element.open ? "open" : "closed";
17
21
  states.set(key, value);
18
22
  try { window.sessionStorage.setItem(key, value); } catch (_error) { /* Keep Turbo visits working without storage. */ }
@@ -20,8 +24,8 @@
20
24
 
21
25
  function restore(force = false) {
22
26
  document.querySelectorAll(selector).forEach((element) => {
23
- if (!element.dataset.b270ActiveReadersKey || (initialized.has(element) && !force)) return;
24
27
  const key = keyFor(element);
28
+ if (!key || (initialized.has(element) && !force)) return;
25
29
  let value = states.get(key);
26
30
  if (value === undefined) {
27
31
  try { value = window.sessionStorage.getItem(key); } catch (_error) { /* Native disclosure remains usable. */ }
@@ -508,9 +508,19 @@
508
508
  .b270-scripture-fields label{white-space:nowrap}
509
509
  .b270-scripture-fields .b270-field>input,.b270-scripture-fields .b270-select-wrap{flex:1;min-width:0}
510
510
  .b270-scripture-panel-header{display:flex;align-items:center;justify-content:space-between;gap:8px;margin:0 0 8px}
511
+ details.b270-scripture-frames>summary.b270-scripture-panel-header{margin:0 0 8px}
512
+ .b270-scripture-frames:not([open])>:not(summary){display:none}
513
+ .b270-scripture-frames>.b270-scripture-panel-header .b270-disclosure-hide{display:none}
514
+ .b270-scripture-frames[open]>.b270-scripture-panel-header .b270-disclosure-show{display:none}
515
+ .b270-scripture-frames[open]>.b270-scripture-panel-header .b270-disclosure-hide{display:inline}
511
516
  .b270-scripture-panel-header>.b270-subhead,.b270 .b270-scripture-panel-header>.b270-btn{margin:0}
512
517
  .b270-scripture-panel-header>.b270-subhead{min-width:0;overflow-wrap:anywhere}
513
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}
514
524
  .b270-scripture-actions{display:flex;align-items:center;gap:10px;margin:0;white-space:nowrap}
515
525
  .b270-scripture-actions>form{margin:0}
516
526
  .b270-scripture-actions>a,.b270-scripture-actions .b270-linkbtn{margin:0;font-size:12.5px;color:var(--oxblood)}
@@ -767,8 +777,8 @@
767
777
 
768
778
  .b270-footer{margin-top:20px;padding-top:11px;border-top:1px solid var(--line-soft);color:var(--faint);font-size:13px}
769
779
  .b270-footer p{margin:0;line-height:1.5}
770
- details.b270-index summary{cursor:pointer;font-family:"Spectral",serif;font-size:18px;font-weight:600;list-style:none;margin-top:30px}
771
- details.b270-index summary::-webkit-details-marker{display:none}
780
+ details.b270-index>summary{cursor:pointer;font-family:"Spectral",serif;font-size:18px;font-weight:600;list-style:none;margin-top:30px}
781
+ details.b270-index>summary::-webkit-details-marker{display:none}
772
782
  details.b270-active-readers{margin-bottom:24px}
773
783
  details.b270-active-readers>summary{margin:0 0 12px}
774
784
  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
@@ -76,6 +76,13 @@
76
76
  For the commandment is a lamp and the teaching is light;
77
77
  And reproofs for discipline are the way of life
78
78
  attribution: NASB 1995 © The Lockman Foundation.
79
+ - id: proverbs-16-20
80
+ reference: Proverbs 16:20
81
+ translation: NASB95
82
+ text: |-
83
+ He who gives attention to the word will find good,
84
+ And blessed is he who trusts in the LORD.
85
+ attribution: NASB 1995 © The Lockman Foundation.
79
86
  - id: isaiah-55-11
80
87
  reference: Isaiah 55:11
81
88
  translation: ESV
@@ -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