SPB Git

Repository Public

001_init.sql 17.3 KB 394 lines sql

1-- MacLustr SMS Gateway — schéma initial.2-- Les contenus de SMS (text_enc), les secrets de webhook et les charges utiles de webhook sont chiffrés3-- par l'application (AES-256-GCM, clé hors base). Les numéros restent en clair : le routage en dépend.45-- ── Administration ────────────────────────────────────────────────────────────6create table users (7  id            text primary key,8  handle        text not null unique,9  display_name  text not null,10  role          text not null default 'admin' check (role in ('admin')),11  created_at    timestamptz not null default now(),12  disabled_at   timestamptz13);1415create table passkeys (16  id            text primary key,                 -- credential id (base64url)17  user_id       text not null references users(id) on delete cascade,18  public_key    bytea not null,19  counter       bigint not null default 0,20  transports    text[] not null default '{}',21  label         text not null default '',22  created_at    timestamptz not null default now(),23  last_used_at  timestamptz24);2526create table admin_sessions (27  id            text primary key,                 -- sha256 du jeton de session28  user_id       text not null references users(id) on delete cascade,29  created_at    timestamptz not null default now(),30  last_seen_at  timestamptz not null default now(),31  expires_at    timestamptz not null,32  ip            text,33  user_agent    text34);35create index admin_sessions_user on admin_sessions(user_id);3637-- Liens d'enrôlement à usage unique (créés par la CLI opérateur sur le nœud).38create table enrollment_tokens (39  token_hash    text primary key,40  user_id       text not null references users(id) on delete cascade,41  created_at    timestamptz not null default now(),42  expires_at    timestamptz not null,43  used_at       timestamptz44);4546create table auth_challenges (47  id            text primary key,48  kind          text not null check (kind in ('register', 'login')),49  challenge     text not null,50  user_id       text,51  expires_at    timestamptz not null52);5354-- ── Applications clientes et clés API ─────────────────────────────────────────55create table applications (56  id                text primary key,57  name              text not null unique,58  description       text not null default '',59  kind              text not null default 'service' check (kind in ('service', 'agent')),60  enabled           boolean not null default true,61  daily_quota       integer not null default 200 check (daily_quota >= 0),62  rate_per_minute   integer not null default 20 check (rate_per_minute >= 0),63  approval_required boolean not null default false,   -- messages retenus (HELD) jusqu'à approbation humaine64  require_consent   boolean not null default false,   -- refuse les destinataires sans consentement enregistré65  allowed_sim_ids   text[],                           -- null = toutes les SIM66  created_at        timestamptz not null default now()67);6869create table api_keys (70  id              text primary key,71  application_id  text not null references applications(id) on delete cascade,72  name            text not null default '',73  prefix          text not null,                      -- début de la clé, affichable74  key_hash        text not null unique,               -- sha256 de la clé complète75  scopes          text[] not null,76  created_at      timestamptz not null default now(),77  last_used_at    timestamptz,78  expires_at      timestamptz,79  revoked_at      timestamptz,80  rotated_from    text81);82create index api_keys_app on api_keys(application_id);8384-- ── Appareils Android ─────────────────────────────────────────────────────────85create table devices (86  id                    text primary key,             -- android-01, android-02 …87  name                  text not null,88  manufacturer          text not null default '',89  model                 text not null default '',90  android_version       text not null default '',91  sdk_int               integer,92  app_version           text not null default '',93  app_build             integer,94  enabled               boolean not null default true,95  maintenance           boolean not null default false,96  min_send_interval_ms  integer not null default 3000 check (min_send_interval_ms >= 500),97  online                boolean not null default false,98  status                jsonb not null default '{}',  -- dernier device.status99  last_seen_at          timestamptz,100  last_status_at        timestamptz,101  created_at            timestamptz not null default now(),102  revoked_at            timestamptz103);104105create table device_credentials (106  id          text primary key,107  device_id   text not null references devices(id) on delete cascade,108  algorithm   text not null default 'ES256',109  public_key  text not null,                          -- SPKI DER base64110  created_at  timestamptz not null default now(),111  revoked_at  timestamptz112);113create index device_credentials_device on device_credentials(device_id);114115create table device_sessions (116  id               text primary key,117  device_id        text not null references devices(id) on delete cascade,118  connected_at     timestamptz not null default now(),119  disconnected_at  timestamptz,120  ip               text,121  app_version      text,122  close_code       integer,123  close_reason     text124);125create index device_sessions_device on device_sessions(device_id, connected_at desc);126127create table pairing_codes (128  code_hash    text primary key,129  created_by   text references users(id) on delete set null,130  name_hint    text not null default '',131  created_at   timestamptz not null default now(),132  expires_at   timestamptz not null,133  used_at      timestamptz,134  device_id    text135);136137-- Déduplication des événements d'appareil (protection contre les rejeux et les renvois).138create table device_events (139  device_id    text not null references devices(id) on delete cascade,140  event_id     text not null,141  type         text not null,142  received_at  timestamptz not null default now(),143  primary key (device_id, event_id)144);145create index device_events_received on device_events(received_at);146147create table device_incidents (148  id          bigserial primary key,149  device_id   text not null references devices(id) on delete cascade,150  kind        text not null,151  detail      jsonb not null default '{}',152  created_at  timestamptz not null default now()153);154create index device_incidents_device on device_incidents(device_id, created_at desc);155156create table device_diagnostics (157  id            text primary key,158  device_id     text not null references devices(id) on delete cascade,159  requested_at  timestamptz not null default now(),160  completed_at  timestamptz,161  checks        jsonb162);163164-- ── SIM et numéros ────────────────────────────────────────────────────────────165create table sim_profiles (166  id               text primary key,                  -- sim-1, sim-2 …167  device_id        text not null references devices(id) on delete cascade,168  subscription_id  integer not null,169  slot_index       integer,170  carrier_name     text not null default '',171  display_name     text not null default '',172  label            text not null default '',173  is_embedded      boolean,174  reported_number  text,175  manual_number    text,176  country_iso      text,177  mcc_mnc          text,178  state            text not null default 'unknown',179  signal_level     integer,180  roaming          boolean,181  is_default_sms   boolean,182  active           boolean not null default true,     -- présent dans le dernier rapport de l'appareil183  enabled          boolean not null default false,    -- autorisé à envoyer (activé par un administrateur)184  daily_limit      integer not null default 100 check (daily_limit >= 0),185  created_at       timestamptz not null default now(),186  updated_at       timestamptz not null default now(),187  unique (device_id, subscription_id)188);189190create table phone_numbers (191  number      text primary key,                       -- E.164192  sim_id      text not null unique references sim_profiles(id) on delete cascade,193  source      text not null check (source in ('reported', 'manual')),194  label       text not null default '',195  created_at  timestamptz not null default now()196);197198-- ── Messages ──────────────────────────────────────────────────────────────────199create table conversations (200  id               text primary key,201  sim_id           text not null references sim_profiles(id) on delete cascade,202  peer             text not null,203  last_message_at  timestamptz not null default now(),204  last_direction   text,205  inbound_count    integer not null default 0,206  outbound_count   integer not null default 0,207  unread           integer not null default 0,208  created_at       timestamptz not null default now(),209  unique (sim_id, peer)210);211create index conversations_recent on conversations(last_message_at desc);212213create table messages (214  id               text primary key,215  direction        text not null check (direction in ('outbound', 'inbound')),216  status           text not null check (status in217                     ('HELD','QUEUED','DISPATCHED','ACCEPTED','SUBMITTING','SUBMITTED','DELIVERED',218                      'FAILED','EXPIRED','CANCELLED','UNKNOWN','RECEIVED')),219  application_id   text references applications(id) on delete set null,220  api_key_id       text,221  created_by       text,                              -- administrateur (console) le cas échéant222  device_id        text references devices(id) on delete set null,223  sim_id           text references sim_profiles(id) on delete set null,224  conversation_id  text references conversations(id) on delete set null,225  from_number      text,226  to_number        text,227  text_enc         bytea,                             -- null après purge de rétention228  text_chars       integer not null default 0,229  encoding         text not null default 'gsm7' check (encoding in ('gsm7', 'ucs2')),230  segments         integer not null default 1,231  parts_sent       integer,232  delivery_report  boolean not null default true,233  idempotency_key  text,234  request_hash     text,235  command_id       text unique,236  device_event_id  text,                              -- SMS entrants : id de l'événement d'appareil237  error_code       text,238  error_detail     text,239  created_at       timestamptz not null default now(),240  expires_at       timestamptz,241  dispatched_at    timestamptz,242  accepted_at      timestamptz,243  submitting_at    timestamptz,244  submitted_at     timestamptz,245  delivered_at     timestamptz,246  finalized_at     timestamptz,247  received_at      timestamptz,248  unique (application_id, idempotency_key),249  unique (device_id, device_event_id)250);251create index messages_created on messages(created_at desc);252create index messages_status on messages(status) where status in ('HELD','QUEUED','DISPATCHED','ACCEPTED','SUBMITTING');253create index messages_app on messages(application_id, created_at desc);254create index messages_conv on messages(conversation_id, created_at desc);255create index messages_sim_day on messages(sim_id, created_at) where direction = 'outbound';256create index messages_inbound on messages(created_at desc) where direction = 'inbound';257258create table message_segments (259  message_id  text not null references messages(id) on delete cascade,260  part        integer not null,261  status      text not null default 'pending' check (status in ('pending', 'delivered', 'failed')),262  pdu_status  integer,263  updated_at  timestamptz not null default now(),264  primary key (message_id, part)265);266267create table message_events (268  id           bigserial primary key,269  message_id   text not null references messages(id) on delete cascade,270  type         text not null,271  from_status  text,272  to_status    text,273  source       text not null check (source in ('api', 'admin', 'device', 'system')),274  detail       jsonb not null default '{}',           -- jamais de contenu de SMS275  created_at   timestamptz not null default now()276);277create index message_events_message on message_events(message_id, id);278279-- File d'attente persistante : une ligne tant que le message n'a pas d'issue côté appareil.280create table message_queue (281  message_id     text primary key references messages(id) on delete cascade,282  device_id      text not null references devices(id) on delete cascade,283  sim_id         text not null,284  state          text not null default 'pending' check (state in ('pending', 'in_flight')),285  priority       integer not null default 0,286  enqueued_at    timestamptz not null default now(),287  dispatched_at  timestamptz,288  dispatch_count integer not null default 0289);290create index message_queue_pick on message_queue(device_id, state, priority desc, enqueued_at);291292-- ── Webhooks ──────────────────────────────────────────────────────────────────293create table webhooks (294  id              text primary key,295  application_id  text references applications(id) on delete cascade,  -- null = webhook d'administration296  url             text not null,297  description     text not null default '',298  events          text[] not null,299  secret_enc      bytea not null,300  enabled         boolean not null default true,301  failure_streak  integer not null default 0,302  disabled_reason text,303  created_at      timestamptz not null default now()304);305306create table webhook_deliveries (307  id               text primary key,308  webhook_id       text not null references webhooks(id) on delete cascade,309  event_id         text not null,310  event_type       text not null,311  payload_enc      bytea,                             -- null après purge312  status           text not null default 'pending' check (status in ('pending', 'delivered', 'failed')),313  attempts         integer not null default 0,314  next_attempt_at  timestamptz not null default now(),315  last_status_code integer,316  last_error       text,317  created_at       timestamptz not null default now(),318  delivered_at     timestamptz319);320create index webhook_deliveries_due on webhook_deliveries(next_attempt_at) where status = 'pending';321create index webhook_deliveries_hook on webhook_deliveries(webhook_id, created_at desc);322323-- ── Conformité ────────────────────────────────────────────────────────────────324create table consents (325  id              bigserial primary key,326  number          text not null,327  application_id  text references applications(id) on delete cascade,  -- null = toutes328  source          text not null default '',329  note            text not null default '',330  granted_at      timestamptz not null default now(),331  revoked_at      timestamptz332);333create unique index consents_unique on consents(number, coalesce(application_id, ''));334335create table opt_outs (336  number      text primary key,337  source      text not null check (source in ('keyword', 'manual', 'api')),338  keyword     text,339  message_id  text,340  created_at  timestamptz not null default now()341);342343create table allowed_recipients (344  number      text primary key,345  label       text not null default '',346  created_at  timestamptz not null default now()347);348349-- ── Journal, statistiques, réglages ───────────────────────────────────────────350create table audit_logs (351  id           bigserial primary key,352  actor_type   text not null,                         -- admin | api_key | device | system | cli353  actor_id     text,354  action       text not null,355  target_type  text,356  target_id    text,357  detail       jsonb not null default '{}',358  ip           text,359  created_at   timestamptz not null default now()360);361create index audit_logs_created on audit_logs(created_at desc);362363create table usage_metrics (364  day             date not null,365  application_id  text not null default '',366  sim_id          text not null default '',367  metric          text not null,368  value           bigint not null default 0,369  primary key (day, application_id, sim_id, metric)370);371372create table system_settings (373  key         text primary key,374  value       jsonb not null,375  updated_at  timestamptz not null default now()376);377378insert into system_settings(key, value) values379  ('kill_switch', 'false'),                 -- arrêt d'urgence global : plus aucun envoi380  ('send_mode', '"allowlist"'),             -- allowlist = seuls les destinataires autorisés ; open = tous (hors désinscrits)381  ('default_sim_id', 'null'),382  ('default_ttl_seconds', '3600'),383  ('retention_days_text', '90'),            -- après ce délai, le contenu des SMS est effacé (métadonnées conservées)384  ('retention_days_records', '730'),385  ('opt_out_keywords', '["STOP","ARRET","ARRÊT","UNSUBSCRIBE","DESABONNER","DÉSABONNER"]'),386  ('opt_in_keywords', '["START","DEBUT","DÉBUT"]');387388create table app_download_tokens (389  token_hash  text primary key,390  created_by  text,391  created_at  timestamptz not null default now(),392  expires_at  timestamptz not null393);394
Files main
Menu

Theme