create-expo-updates-server 0.1.4 → 0.1.6

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.
Files changed (67) hide show
  1. package/dist/template/.env.docker.example +1 -0
  2. package/dist/template/.env.example +2 -0
  3. package/dist/template/README.md +4 -1
  4. package/dist/template/app/api/admin/distribution-control/route.test.ts +153 -0
  5. package/dist/template/app/api/admin/distribution-control/route.ts +111 -0
  6. package/dist/template/app/api/admin/guard-actions/[id]/route.test.ts +60 -0
  7. package/dist/template/app/api/admin/guard-actions/[id]/route.ts +32 -0
  8. package/dist/template/app/api/admin/guard-actions/route.test.ts +123 -0
  9. package/dist/template/app/api/admin/guard-actions/route.ts +66 -0
  10. package/dist/template/app/api/admin/updates/[encodedKey]/deactivate/route.ts +4 -1
  11. package/dist/template/app/api/admin/updates/[encodedKey]/policy/route.test.ts +171 -0
  12. package/dist/template/app/api/admin/updates/[encodedKey]/policy/route.ts +75 -0
  13. package/dist/template/app/api/admin/updates/[encodedKey]/promote/route.ts +4 -1
  14. package/dist/template/app/api/admin/updates/[encodedKey]/rollback/route.ts +4 -1
  15. package/dist/template/app/api/admin/updates/[encodedKey]/route.ts +4 -1
  16. package/dist/template/app/updates/[encodedKey]/page.tsx +74 -6
  17. package/dist/template/app/updates/page.tsx +22 -1
  18. package/dist/template/docs/getting-started.md +1 -0
  19. package/dist/template/docs/getting-started.ru.md +2 -1
  20. package/dist/template/docs/migrations/2026-09-01-ota-update-policy.sql +108 -0
  21. package/dist/template/docs/migrations/2026-09-01-p1-guard-actions.sql +19 -0
  22. package/dist/template/docs/migrations/2026-09-01-p2-simplify-ota-guard-policy.sql +69 -0
  23. package/dist/template/docs/migrations/2026-09-01-policy-publication-correction.sql +44 -0
  24. package/dist/template/docs/migrations/2026-09-02-ota-distribution-control.sql +377 -0
  25. package/dist/template/docs/migrations/schema.sql +539 -2
  26. package/dist/template/docs/operations-guide.md +52 -1
  27. package/dist/template/docs/ota-emergency-recovery.md +22 -0
  28. package/dist/template/docs/ota-update-policy.md +89 -0
  29. package/dist/template/docs/supabase-setup.md +2 -1
  30. package/dist/template/package-lock.json +2 -2
  31. package/dist/template/package.json +1 -1
  32. package/dist/template/src/client/admin-api.ts +80 -1
  33. package/dist/template/src/client/admin-types.ts +50 -2
  34. package/dist/template/src/client/distribution-control.tsx +231 -0
  35. package/dist/template/src/client/guard-action-combobox.test.ts +26 -0
  36. package/dist/template/src/client/guard-action-combobox.tsx +267 -0
  37. package/dist/template/src/client/guard-action-options.test.ts +62 -0
  38. package/dist/template/src/client/guard-action-options.ts +70 -0
  39. package/dist/template/src/client/update-policy-editor.test.ts +36 -0
  40. package/dist/template/src/client/update-policy-editor.tsx +436 -0
  41. package/dist/template/src/server/controllers/assets.test.ts +87 -0
  42. package/dist/template/src/server/controllers/assets.ts +26 -0
  43. package/dist/template/src/server/controllers/manifest.test.ts +413 -2
  44. package/dist/template/src/server/controllers/manifest.ts +103 -38
  45. package/dist/template/src/server/lib/admin-distribution-guard.test.ts +61 -0
  46. package/dist/template/src/server/lib/admin-update-policy.test.ts +176 -0
  47. package/dist/template/src/server/lib/admin-updates.test.ts +72 -0
  48. package/dist/template/src/server/lib/admin-updates.ts +169 -24
  49. package/dist/template/src/server/lib/distribution-control-migration.test.ts +94 -0
  50. package/dist/template/src/server/lib/distribution-control.test.ts +181 -0
  51. package/dist/template/src/server/lib/distribution-control.ts +259 -0
  52. package/dist/template/src/server/lib/guard-actions-migration.test.ts +56 -0
  53. package/dist/template/src/server/lib/guard-actions.test.ts +142 -0
  54. package/dist/template/src/server/lib/guard-actions.ts +106 -0
  55. package/dist/template/src/server/lib/ota-policy-migrations.test.ts +64 -0
  56. package/dist/template/src/server/lib/simple-policy-migration.test.ts +97 -0
  57. package/dist/template/src/server/lib/supabase.js +95 -8
  58. package/dist/template/src/server/lib/supabase.test.ts +194 -0
  59. package/dist/template/src/server/lib/update-policy.test.ts +98 -0
  60. package/dist/template/src/server/lib/update-policy.ts +171 -0
  61. package/dist/template/src/server/manifest/manifest-repository.ts +10 -1
  62. package/dist/template/src/server/manifest/manifest-response.ts +0 -16
  63. package/dist/template/src/server/manifest/manifest-values.test.ts +54 -0
  64. package/dist/template/src/server/manifest/manifest-values.ts +145 -0
  65. package/dist/template/tsconfig.json +4 -1
  66. package/dist/template-manifest.json +239 -59
  67. package/package.json +1 -1
@@ -18,14 +18,60 @@ create table if not exists public.ota_updates (
18
18
  launch_asset_path text null,
19
19
  comment text null,
20
20
  rolled_back_from_update_id uuid null,
21
+ delivery_mode text not null default 'manual',
22
+ guard_action text null,
23
+ guard_payload jsonb null,
24
+ policy_version integer not null default 1,
25
+ policy_published_at timestamptz null,
21
26
  manifest jsonb not null,
22
27
  inserted_at timestamptz not null default now(),
23
28
  modified_at timestamptz not null default now(),
24
29
  constraint ota_updates_active_dates_chk check (
25
30
  not is_active or disabled_at is null
26
- )
31
+ ),
32
+ constraint ota_updates_delivery_mode_chk check (
33
+ delivery_mode in ('manual', 'background')
34
+ ),
35
+ constraint ota_updates_guard_action_chk check (
36
+ guard_action is null
37
+ or (
38
+ guard_action = btrim(guard_action)
39
+ and char_length(guard_action) between 1 and 100
40
+ and guard_action !~ '[[:cntrl:]]'
41
+ )
42
+ ),
43
+ constraint ota_updates_guard_payload_requires_action_chk check (
44
+ guard_payload is null or guard_action is not null
45
+ ),
46
+ constraint ota_updates_policy_version_chk check (policy_version > 0)
27
47
  );
28
48
 
49
+ -- Keep schema.sql safe as an upgrade path from the removed rule-builder
50
+ -- model. Old rules are intentionally discarded rather than converted.
51
+ drop trigger if exists trg_ota_updates_lock_published_policy
52
+ on public.ota_updates;
53
+
54
+ alter table public.ota_updates
55
+ add column if not exists guard_action text null,
56
+ add column if not exists guard_payload jsonb null;
57
+
58
+ alter table public.ota_updates
59
+ drop constraint if exists ota_updates_guard_rules_array_chk,
60
+ drop constraint if exists ota_updates_guard_action_chk,
61
+ drop constraint if exists ota_updates_guard_payload_requires_action_chk,
62
+ drop column if exists guard_rules,
63
+ add constraint ota_updates_guard_action_chk check (
64
+ guard_action is null
65
+ or (
66
+ guard_action = btrim(guard_action)
67
+ and char_length(guard_action) between 1 and 100
68
+ and guard_action !~ '[[:cntrl:]]'
69
+ )
70
+ ),
71
+ add constraint ota_updates_guard_payload_requires_action_chk check (
72
+ guard_payload is null or guard_action is not null
73
+ );
74
+
29
75
  create index if not exists idx_ota_updates_lookup
30
76
  on public.ota_updates (runtime_version, channel, platform, created_at desc);
31
77
 
@@ -33,6 +79,11 @@ create unique index if not exists idx_ota_updates_one_active_per_scope
33
79
  on public.ota_updates (runtime_version, channel, platform)
34
80
  where is_active;
35
81
 
82
+ comment on column public.ota_updates.disabled_at is
83
+ 'Inactive-state timestamp; disabled_at = created_at is the initial draft marker, not publication.';
84
+ comment on column public.ota_updates.policy_published_at is
85
+ 'First activation/publication timestamp. A null value identifies an editable draft policy.';
86
+
36
87
  create table if not exists public.ota_update_channels (
37
88
  id bigserial primary key,
38
89
  runtime_version text not null,
@@ -48,6 +99,9 @@ create table if not exists public.ota_update_channels (
48
99
  unique (runtime_version, channel, platform)
49
100
  );
50
101
 
102
+ comment on column public.ota_update_channels.latest_update_id is
103
+ 'Newest uploaded update; may reference an inactive draft and is not publication evidence.';
104
+
51
105
  create or replace function public.set_modified_at()
52
106
  returns trigger
53
107
  language plpgsql
@@ -63,6 +117,50 @@ create trigger trg_ota_updates_modified_at
63
117
  before update on public.ota_updates
64
118
  for each row execute function public.set_modified_at();
65
119
 
120
+ create or replace function public.ota_updates_lock_published_policy()
121
+ returns trigger
122
+ language plpgsql
123
+ as $$
124
+ begin
125
+ if tg_op = 'INSERT' then
126
+ if new.is_active and new.policy_published_at is null then
127
+ new.policy_published_at := coalesce(
128
+ new.updated_at,
129
+ new.created_at,
130
+ now()
131
+ );
132
+ end if;
133
+ return new;
134
+ end if;
135
+
136
+ if new.is_active and not old.is_active
137
+ and new.policy_published_at is null then
138
+ new.policy_published_at := coalesce(
139
+ new.updated_at,
140
+ new.created_at,
141
+ now()
142
+ );
143
+ end if;
144
+
145
+ if old.policy_published_at is not null and (
146
+ new.delivery_mode is distinct from old.delivery_mode
147
+ or new.guard_action is distinct from old.guard_action
148
+ or new.guard_payload is distinct from old.guard_payload
149
+ or new.policy_version is distinct from old.policy_version
150
+ or new.policy_published_at is distinct from old.policy_published_at
151
+ ) then
152
+ raise exception 'OTA update policy is immutable after publication';
153
+ end if;
154
+ return new;
155
+ end;
156
+ $$;
157
+
158
+ drop trigger if exists trg_ota_updates_lock_published_policy
159
+ on public.ota_updates;
160
+ create trigger trg_ota_updates_lock_published_policy
161
+ before insert or update on public.ota_updates
162
+ for each row execute function public.ota_updates_lock_published_policy();
163
+
66
164
  drop trigger if exists trg_ota_update_channels_modified_at on public.ota_update_channels;
67
165
  create trigger trg_ota_update_channels_modified_at
68
166
  before update on public.ota_update_channels
@@ -240,6 +338,49 @@ create index if not exists idx_ota_served_manifest_log_scope
240
338
  created_at desc
241
339
  );
242
340
 
341
+ -- Repair policy markers incorrectly backfilled onto untouched, never-served
342
+ -- drafts. This block intentionally follows ota_served_manifest_log creation so
343
+ -- schema.sql is also a safe upgrade path for already-running installations.
344
+ begin;
345
+
346
+ drop trigger if exists trg_ota_updates_lock_published_policy
347
+ on public.ota_updates;
348
+
349
+ update public.ota_updates u
350
+ set policy_published_at = null
351
+ where u.policy_published_at is not null
352
+ and u.policy_published_at = coalesce(
353
+ u.updated_at,
354
+ u.disabled_at,
355
+ u.created_at
356
+ )
357
+ and not u.is_active
358
+ and u.disabled_at is not null
359
+ and u.disabled_at = u.created_at
360
+ and u.delivery_mode = 'manual'
361
+ and u.guard_action is null
362
+ and u.guard_payload is null
363
+ and u.policy_version = 1
364
+ and u.rolled_back_from_update_id is null
365
+ and not exists (
366
+ select 1
367
+ from public.ota_served_manifest_log sml
368
+ where sml.update_id = u.update_id
369
+ )
370
+ -- latest_update_id tracks the newest upload and may reference this inactive
371
+ -- draft. It is intentionally not treated as publication evidence.
372
+ and not exists (
373
+ select 1
374
+ from public.ota_update_channels c
375
+ where c.active_update_id = u.update_id
376
+ );
377
+
378
+ create trigger trg_ota_updates_lock_published_policy
379
+ before insert or update on public.ota_updates
380
+ for each row execute function public.ota_updates_lock_published_policy();
381
+
382
+ commit;
383
+
243
384
  create table if not exists public.ota_device_state (
244
385
  installation_id text not null,
245
386
  platform text not null check (platform in ('ios', 'android')),
@@ -309,6 +450,24 @@ create index if not exists idx_ota_access_tokens_active_hash
309
450
  on public.ota_access_tokens (token_hash)
310
451
  where revoked_at is null;
311
452
 
453
+ create table if not exists public.ota_guard_actions (
454
+ id uuid primary key default gen_random_uuid(),
455
+ action_key text not null,
456
+ created_at timestamptz not null default now(),
457
+ constraint ota_guard_actions_action_key_chk check (
458
+ action_key = btrim(action_key)
459
+ and char_length(action_key) between 1 and 100
460
+ and action_key !~ '[[:cntrl:]]'
461
+ )
462
+ );
463
+
464
+ create unique index if not exists idx_ota_guard_actions_action_key
465
+ on public.ota_guard_actions (action_key);
466
+
467
+ insert into public.ota_guard_actions (action_key)
468
+ values ('ota-force-store-update')
469
+ on conflict (action_key) do nothing;
470
+
312
471
  create table if not exists public.ota_emergency_redirects (
313
472
  id uuid primary key default gen_random_uuid(),
314
473
  name text not null unique check (char_length(name) between 1 and 120),
@@ -382,4 +541,382 @@ drop trigger if exists trg_ota_admin_users_modified_at
382
541
  on public.ota_admin_users;
383
542
  create trigger trg_ota_admin_users_modified_at
384
543
  before update on public.ota_admin_users
385
- for each row execute function public.set_modified_at();
544
+ for each row execute function public.set_modified_at();
545
+
546
+ create table if not exists public.ota_distribution_control (
547
+ singleton_id smallint primary key default 1,
548
+ blocked boolean not null default false,
549
+ version bigint not null default 1,
550
+ reason text null,
551
+ changed_at timestamptz not null default now(),
552
+ changed_by jsonb not null default
553
+ '{"type":"system","id":"migration","label":"Database migration"}'::jsonb,
554
+ constraint ota_distribution_control_singleton_chk check (singleton_id = 1),
555
+ constraint ota_distribution_control_version_chk check (version > 0),
556
+ constraint ota_distribution_control_reason_chk check (
557
+ (not blocked and reason is null)
558
+ or (
559
+ blocked
560
+ and reason = btrim(reason)
561
+ and char_length(reason) between 1 and 500
562
+ and reason !~ '[[:cntrl:]]'
563
+ )
564
+ )
565
+ );
566
+
567
+ insert into public.ota_distribution_control (
568
+ singleton_id,
569
+ blocked,
570
+ version,
571
+ reason,
572
+ changed_by
573
+ )
574
+ values (
575
+ 1,
576
+ false,
577
+ 1,
578
+ null,
579
+ '{"type":"system","id":"migration","label":"Database migration"}'::jsonb
580
+ )
581
+ on conflict (singleton_id) do nothing;
582
+
583
+ create table if not exists public.ota_distribution_control_events (
584
+ id bigserial primary key,
585
+ previous_blocked boolean not null,
586
+ blocked boolean not null,
587
+ previous_version bigint not null,
588
+ version bigint not null,
589
+ reason text null,
590
+ changed_at timestamptz not null,
591
+ changed_by jsonb not null,
592
+ constraint ota_distribution_control_events_versions_chk check (
593
+ previous_version > 0 and version = previous_version + 1
594
+ )
595
+ );
596
+
597
+ create index if not exists idx_ota_distribution_control_events_changed_at
598
+ on public.ota_distribution_control_events (changed_at desc);
599
+
600
+ -- Serialize the emergency switch with every mutation that can start or
601
+ -- redirect OTA distribution. A transaction that gets this lock first is the
602
+ -- operation that takes effect first; the other transaction observes its
603
+ -- committed result after waiting. Keep this lock first in every code path
604
+ -- before taking row locks to avoid lock-order inversions.
605
+ create or replace function public.lock_ota_distribution_control()
606
+ returns void
607
+ language sql
608
+ set search_path = pg_catalog
609
+ as $$
610
+ select pg_catalog.pg_advisory_xact_lock(20260902, 1);
611
+ $$;
612
+
613
+ revoke all on function public.lock_ota_distribution_control() from public;
614
+
615
+ create or replace function public.serialize_ota_distribution_statement()
616
+ returns trigger
617
+ language plpgsql
618
+ security definer
619
+ set search_path = public, pg_temp
620
+ as $$
621
+ begin
622
+ perform public.lock_ota_distribution_control();
623
+ return null;
624
+ end;
625
+ $$;
626
+
627
+ -- This statement-level trigger also serializes ordinary direct SQL updates
628
+ -- of the singleton. The RPC explicitly takes the same lock before touching
629
+ -- the row.
630
+ drop trigger if exists trg_ota_distribution_control_serialize_write
631
+ on public.ota_distribution_control;
632
+ create trigger trg_ota_distribution_control_serialize_write
633
+ before insert or update or delete on public.ota_distribution_control
634
+ for each statement
635
+ execute function public.serialize_ota_distribution_statement();
636
+
637
+ -- Acquire the lock before PostgreSQL starts locking affected update/channel
638
+ -- rows. The row triggers below take it again (reentrantly) only when they need
639
+ -- to check BLOCKED, but the statement triggers establish a consistent global
640
+ -- lock order for multi-row and direct-SQL mutations.
641
+ drop trigger if exists trg_ota_distribution_serialize_update_insert
642
+ on public.ota_updates;
643
+ create trigger trg_ota_distribution_serialize_update_insert
644
+ before insert on public.ota_updates
645
+ for each statement
646
+ execute function public.serialize_ota_distribution_statement();
647
+
648
+ drop trigger if exists trg_ota_distribution_serialize_update_activation
649
+ on public.ota_updates;
650
+ create trigger trg_ota_distribution_serialize_update_activation
651
+ before update of is_active on public.ota_updates
652
+ for each statement
653
+ execute function public.serialize_ota_distribution_statement();
654
+
655
+ drop trigger if exists trg_ota_distribution_serialize_channel_insert
656
+ on public.ota_update_channels;
657
+ create trigger trg_ota_distribution_serialize_channel_insert
658
+ before insert on public.ota_update_channels
659
+ for each statement
660
+ execute function public.serialize_ota_distribution_statement();
661
+
662
+ drop trigger if exists trg_ota_distribution_serialize_channel_change
663
+ on public.ota_update_channels;
664
+ create trigger trg_ota_distribution_serialize_channel_change
665
+ before update of
666
+ runtime_version,
667
+ channel,
668
+ platform,
669
+ latest_update_id,
670
+ latest_created_at,
671
+ latest_created_at_path,
672
+ active_update_id,
673
+ active_changed_at,
674
+ served_manifest_id,
675
+ served_manifest_changed_at
676
+ on public.ota_update_channels
677
+ for each statement
678
+ execute function public.serialize_ota_distribution_statement();
679
+
680
+ create or replace function public.assert_ota_distribution_mutation_allowed(
681
+ p_operation text
682
+ )
683
+ returns void
684
+ language plpgsql
685
+ security definer
686
+ set search_path = public, pg_temp
687
+ as $$
688
+ declare
689
+ distribution_blocked boolean;
690
+ begin
691
+ perform public.lock_ota_distribution_control();
692
+
693
+ select blocked
694
+ into distribution_blocked
695
+ from public.ota_distribution_control
696
+ where singleton_id = 1
697
+ for share;
698
+
699
+ if not found then
700
+ raise exception
701
+ 'OTA_DISTRIBUTION_CONTROL_MISSING: singleton row is required'
702
+ using errcode = '55000';
703
+ end if;
704
+
705
+ if distribution_blocked then
706
+ raise exception
707
+ 'OTA_DISTRIBUTION_BLOCKED: % is not allowed while global OTA distribution is blocked',
708
+ p_operation
709
+ using
710
+ errcode = 'P0OTA',
711
+ hint = 'Deactivate updates or resume OTA distribution first.';
712
+ end if;
713
+ end;
714
+ $$;
715
+
716
+ revoke all on function public.assert_ota_distribution_mutation_allowed(text)
717
+ from public;
718
+
719
+ create or replace function public.guard_ota_update_distribution()
720
+ returns trigger
721
+ language plpgsql
722
+ security definer
723
+ set search_path = public, pg_temp
724
+ as $$
725
+ begin
726
+ -- Inactive inserts and all edits that do not activate a row stay available.
727
+ -- In particular, true -> false is deliberately allowed for incident repair.
728
+ if (tg_op = 'INSERT' and not new.is_active)
729
+ or (
730
+ tg_op = 'UPDATE'
731
+ and not (new.is_active and not old.is_active)
732
+ ) then
733
+ return new;
734
+ end if;
735
+
736
+ perform public.assert_ota_distribution_mutation_allowed(
737
+ case
738
+ when tg_op = 'INSERT' then 'inserting an active OTA update'
739
+ else 'activating an OTA update'
740
+ end
741
+ );
742
+ return new;
743
+ end;
744
+ $$;
745
+
746
+ drop trigger if exists trg_ota_distribution_guard_updates
747
+ on public.ota_updates;
748
+ create trigger trg_ota_distribution_guard_updates
749
+ before insert or update on public.ota_updates
750
+ for each row
751
+ execute function public.guard_ota_update_distribution();
752
+
753
+ create or replace function public.guard_ota_channel_distribution()
754
+ returns trigger
755
+ language plpgsql
756
+ security definer
757
+ set search_path = public, pg_temp
758
+ as $$
759
+ declare
760
+ changes_distribution_state boolean;
761
+ begin
762
+ if tg_op = 'INSERT' then
763
+ -- Empty channel rows do not distribute an update.
764
+ changes_distribution_state :=
765
+ new.latest_update_id is not null
766
+ or new.active_update_id is not null;
767
+ else
768
+ changes_distribution_state :=
769
+ new.runtime_version is distinct from old.runtime_version
770
+ or new.channel is distinct from old.channel
771
+ or new.platform is distinct from old.platform
772
+ or new.latest_update_id is distinct from old.latest_update_id
773
+ or new.latest_created_at is distinct from old.latest_created_at
774
+ or new.latest_created_at_path is distinct from old.latest_created_at_path
775
+ or new.active_update_id is distinct from old.active_update_id
776
+ or new.active_changed_at is distinct from old.active_changed_at
777
+ or new.served_manifest_id is distinct from old.served_manifest_id
778
+ or new.served_manifest_changed_at
779
+ is distinct from old.served_manifest_changed_at;
780
+ end if;
781
+
782
+ if not changes_distribution_state then
783
+ return new;
784
+ end if;
785
+
786
+ -- Clearing every serving pointer only removes distribution and is the
787
+ -- channel-side part of deactivation. Clearing a rollback pointer while a
788
+ -- latest pointer remains would promote latest, so it is still guarded.
789
+ if new.latest_update_id is null and new.active_update_id is null then
790
+ return new;
791
+ end if;
792
+
793
+ perform public.assert_ota_distribution_mutation_allowed(
794
+ 'changing OTA channel distribution state'
795
+ );
796
+ return new;
797
+ end;
798
+ $$;
799
+
800
+ drop trigger if exists trg_ota_distribution_guard_channels
801
+ on public.ota_update_channels;
802
+ create trigger trg_ota_distribution_guard_channels
803
+ before insert or update on public.ota_update_channels
804
+ for each row
805
+ execute function public.guard_ota_channel_distribution();
806
+
807
+ create or replace function public.set_ota_distribution_control(
808
+ p_blocked boolean,
809
+ p_reason text,
810
+ p_expected_version bigint,
811
+ p_changed_by jsonb
812
+ )
813
+ returns setof public.ota_distribution_control
814
+ language plpgsql
815
+ security definer
816
+ set search_path = public, pg_temp
817
+ as $$
818
+ declare
819
+ previous_row public.ota_distribution_control%rowtype;
820
+ updated_row public.ota_distribution_control%rowtype;
821
+ normalized_reason text;
822
+ begin
823
+ if p_expected_version is null or p_expected_version < 1 then
824
+ raise exception 'expectedVersion must be a positive integer'
825
+ using errcode = '22023';
826
+ end if;
827
+
828
+ if p_changed_by is null
829
+ or jsonb_typeof(p_changed_by) <> 'object'
830
+ or nullif(btrim(p_changed_by->>'type'), '') is null
831
+ or nullif(btrim(p_changed_by->>'id'), '') is null
832
+ or nullif(btrim(p_changed_by->>'label'), '') is null then
833
+ raise exception 'changedBy principal metadata is invalid'
834
+ using errcode = '22023';
835
+ end if;
836
+
837
+ normalized_reason := nullif(btrim(coalesce(p_reason, '')), '');
838
+ if p_blocked and normalized_reason is null then
839
+ raise exception 'reason is required when OTA distribution is blocked'
840
+ using errcode = '22023';
841
+ end if;
842
+ if p_blocked and (
843
+ char_length(normalized_reason) > 500
844
+ or normalized_reason ~ '[[:cntrl:]]'
845
+ ) then
846
+ raise exception 'reason must contain at most 500 characters and no control characters'
847
+ using errcode = '22023';
848
+ end if;
849
+ if not p_blocked then
850
+ normalized_reason := null;
851
+ end if;
852
+
853
+ perform public.lock_ota_distribution_control();
854
+
855
+ select *
856
+ into previous_row
857
+ from public.ota_distribution_control
858
+ where singleton_id = 1
859
+ for update;
860
+
861
+ if not found then
862
+ raise exception 'OTA distribution control singleton is missing'
863
+ using errcode = '55000';
864
+ end if;
865
+
866
+ update public.ota_distribution_control
867
+ set blocked = p_blocked,
868
+ version = version + 1,
869
+ reason = normalized_reason,
870
+ changed_at = now(),
871
+ changed_by = p_changed_by
872
+ where singleton_id = 1
873
+ and version = p_expected_version
874
+ returning * into updated_row;
875
+
876
+ if not found then
877
+ raise exception 'OTA distribution control version conflict'
878
+ using errcode = '40001';
879
+ end if;
880
+
881
+ insert into public.ota_distribution_control_events (
882
+ previous_blocked,
883
+ blocked,
884
+ previous_version,
885
+ version,
886
+ reason,
887
+ changed_at,
888
+ changed_by
889
+ )
890
+ values (
891
+ previous_row.blocked,
892
+ updated_row.blocked,
893
+ previous_row.version,
894
+ updated_row.version,
895
+ updated_row.reason,
896
+ updated_row.changed_at,
897
+ updated_row.changed_by
898
+ );
899
+
900
+ return next updated_row;
901
+ end;
902
+ $$;
903
+
904
+ revoke all on function public.set_ota_distribution_control(
905
+ boolean,
906
+ text,
907
+ bigint,
908
+ jsonb
909
+ ) from public;
910
+
911
+ do $$
912
+ begin
913
+ if exists (select 1 from pg_roles where rolname = 'service_role') then
914
+ grant execute on function public.set_ota_distribution_control(
915
+ boolean,
916
+ text,
917
+ bigint,
918
+ jsonb
919
+ ) to service_role;
920
+ end if;
921
+ end;
922
+ $$;
@@ -9,7 +9,8 @@ recovery, backups and upgrades for the OTA update server.
9
9
  - PostgreSQL 15 or newer;
10
10
  - S3-compatible object storage such as Cloudflare R2 or MinIO;
11
11
  - HTTPS public URL for production;
12
- - optional CDN for immutable OTA assets.
12
+ - optional CDN in front of the whole OTA server (it must respect
13
+ `Cache-Control: no-store` on blocked asset responses).
13
14
 
14
15
  ## 2. Environment
15
16
 
@@ -224,6 +225,56 @@ npm run emergency:import
224
225
 
225
226
  The manifest runtime reads only `ota_emergency_redirects` after migration.
226
227
 
228
+ ## 9.1 Global OTA emergency switch
229
+
230
+ The prominent control at `/updates` is the highest-priority incident switch.
231
+ When it is **BLOCKED**:
232
+
233
+ - every manifest request receives Expo's signed `noUpdateAvailable`
234
+ directive;
235
+ - every `/api/assets` request fails closed with `503` and
236
+ `Cache-Control: no-store`;
237
+ - activation, rollback, promote, and distributing `channel-latest.json` /
238
+ `update-meta.json` mutations return `409`;
239
+ - update activation and channel distribution changes are also rejected in
240
+ PostgreSQL with SQLSTATE `P0OTA` and an `OTA_DISTRIBUTION_BLOCKED` message,
241
+ including ordinary direct SQL writes;
242
+ - deactivation, inactive draft inserts, safe metadata edits, and channel
243
+ pointer cleanup that leaves no served update remain available. Deleting an
244
+ update remains available only when foreign-key pointer cleanup would not
245
+ promote or redirect another update.
246
+
247
+ Enabling the switch requires a reason and confirmation. Disabling it also
248
+ requires confirmation. Viewers can inspect the status but cannot change it.
249
+ State changes use an optimistic version and are audited with actor and time.
250
+ The switch RPC and distribution triggers share a transaction-scoped database
251
+ lock, so a concurrent mutation either completes before BLOCKED takes effect or
252
+ waits and is rejected; there is no check/mutation window. Do not disable these
253
+ triggers during an incident.
254
+
255
+ Incident procedure:
256
+
257
+ 1. Open `/updates`, enter the incident/ticket and impact as the reason, then
258
+ choose **Stop all OTA**.
259
+ 2. Confirm both a manifest check (`noUpdateAvailable`) and a previously issued
260
+ `/api/assets` URL (`503`, no-store).
261
+ 3. Investigate or deactivate the bad updates while distribution stays blocked.
262
+ 4. Before resuming, verify channel pointers and both platforms.
263
+ 5. Choose **Resume OTA**, confirm, then repeat manifest checks.
264
+
265
+ The switch requires migration
266
+ `docs/migrations/2026-09-02-ota-distribution-control.sql`. A missing table or
267
+ database read failure is deliberately not interpreted as ACTIVE: manifests
268
+ and assets fail closed.
269
+
270
+ `OTA_CDN_BASE_URL` is retained only as a deprecated configuration value. New
271
+ manifests always use the server's gated `/api/assets` URLs. If an external CDN
272
+ is used, place it in front of the OTA server rather than exposing the storage
273
+ bucket URL, and make sure it honors the asset endpoint's `private, no-store`
274
+ response. The switch cannot revoke immutable legacy storage/CDN URLs that were
275
+ already issued by an older server version; purge or disable that legacy CDN
276
+ before relying on the switch for those manifests.
277
+
227
278
  ## 10. Backups
228
279
 
229
280
  PostgreSQL:
@@ -1,5 +1,27 @@
1
1
  # Аварийное восстановление OTA
2
2
 
3
+ ## Глобальная аварийная остановка
4
+
5
+ Если необходимо немедленно прекратить **любую** OTA-раздачу, используйте
6
+ глобальный переключатель `ACTIVE/BLOCKED` на `/updates`. Он имеет приоритет над
7
+ всеми emergency redirects: manifest вернёт `noUpdateAvailable`, а уже выданные
8
+ ссылки `/api/assets` перестанут отдавать bytes и ответят `503 no-store`.
9
+
10
+ Укажите причину/номер инцидента, подтвердите включение и проверьте manifest и
11
+ asset URL. После исправления проверьте pointers каналов, подтвердите выключение
12
+ блокировки и повторите проверки для iOS и Android.
13
+
14
+ RPC переключателя и DB-триггеры mutations используют одну transaction advisory
15
+ lock. Поэтому конкурентная activation/channel mutation либо завершится до
16
+ включения `BLOCKED`, либо дождётся его и будет отклонена PostgreSQL с SQLSTATE
17
+ `P0OTA` и сообщением `OTA_DISTRIBUTION_BLOCKED`. Deactivation, inactive draft
18
+ insert и безопасные metadata edits остаются доступны. Не отключайте guard
19
+ triggers во время инцидента.
20
+
21
+ Новые manifest используют gated server-proxy URL `/api/assets`. Уже выданные
22
+ старыми версиями сервера immutable storage/CDN URL отозвать этим switch
23
+ невозможно; это ограничение legacy URL должно учитываться в incident response.
24
+
3
25
  Emergency redirect используется, когда опубликованный binary build запрашивает
4
26
  неправильный нативный Expo channel. JavaScript OTA не может изменить channel,
5
27
  записанный в Android Manifest или iOS Expo.plist, поэтому сервер точечно