puerto 0.34.0

Puerto: la CLI de un framework full-stack DDD en Rust. Genera proyectos con Clean Architecture, la inyección de dependencias cableada sola y soporte de SQLx, sin cablear nada a mano. Antes, puerto-framework.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
//! `puerto nuevo --auth oidc` (ADR-0021): the `Usuario` entity every caller becomes, the provisioning
//! `Autenticador` in front of the provider, `GET /me`, and Keycloak for development. Every file
//! here is written once — the project's from then on.

use crate::generators::layout::{self, Layer};
use std::fs;
use std::path::{Path, PathBuf};

use crate::generators::naming::write_file;
use crate::generators::project::{add_compose_service, add_workspace_dependency};
use crate::generators::render::render;

/// The Keycloak a project runs in development; `make test/auth` tests Puerto against the same tag.
pub const KEYCLOAK_IMAGE: &str = "quay.io/keycloak/keycloak:26.8.0";
/// Where Keycloak listens on the host: off 8080, the API's own port.
pub const KEYCLOAK_PORT: u16 = 8180;
/// The development user's password, in the imported realm and in `.env.example`.
pub const DEV_PASSWORD: &str = "admin-dev-only";
/// The audience Keycloak's mapper adds to the `web` client's tokens, and `AUTH_AUDIENCE`.
pub const AUDIENCE: &str = "api";
/// The OpenID Connect client of the frontend, pinned like every `web/package.json` dependency.
pub const OIDC_CLIENT_TS_VERSION: &str = "3.5.0";

/// A mode `puerto nuevo --auth` knows.
pub fn check_mode(mode: &str) -> Result<(), String> {
    crate::validation::validate_auth_mode(mode)
}

/// Whether `puerto nuevo --auth <mode>` can write a project with this database choice — asked
/// before anything is written. Local accounts live in Postgres.
pub fn check_new_project(mode: &str, db: bool) -> Result<(), String> {
    check_mode(mode)?;
    if mode == "local" && !db {
        return Err("--auth local guarda las cuentas en la base de datos: añade --db".into());
    }
    Ok(())
}

/// Who may call each use case of an entity: what the templates of an auth project branch on.
/// Outside an auth project nothing is protected.
#[derive(Debug, Clone, Default)]
pub struct Access {
    auth: bool,
    public: Vec<String>,
    roles: std::collections::BTreeMap<String, Vec<String>>,
    /// 27.18: the entity has an owner (`propietario`).
    owned: bool,
    /// The use cases whose roles the use case checks, not the route — `obtener`, `listar` (36.2),
    /// `actualizar`, `borrar` and the transitions with a route (28.2) of an owned entity, which its
    /// owner reaches without them; but not those in `solo_rol`.
    owner_checked: Vec<String>,
}

impl Access {
    /// The entity `pascal`'s, as `puerto.toml` at `base` records it.
    pub fn of(base: &Path, pascal: &str) -> Self {
        crate::puerto_toml::read(base)
            .map(|config| Self::in_config(&config, pascal))
            .unwrap_or_default()
    }

    /// The entity `pascal`'s, as `config` records it.
    pub fn in_config(config: &crate::puerto_toml::PuertoConfig, pascal: &str) -> Self {
        let entity = config.entity.iter().find(|e| e.name == pascal);
        let owner_checked = entity
            .filter(|e| e.owner.is_some())
            .map(owner_checked_use_cases)
            .unwrap_or_default();
        Self {
            auth: config.project.has_auth(),
            public: entity.map(|e| e.public.clone()).unwrap_or_default(),
            roles: entity.map(|e| e.roles.clone()).unwrap_or_default(),
            owned: entity.is_some_and(|e| e.owner.is_some()),
            owner_checked,
        }
    }

    pub fn is_auth(&self) -> bool {
        self.auth
    }

    /// Its route takes `auth: BearerAuth`, its params an `actor`.
    pub fn is_protected(&self, use_case: &str) -> bool {
        self.auth && !self.public.iter().any(|p| p == use_case)
    }

    /// The roles its route requires (`#[requiere_rol]`), none when public.
    pub fn roles(&self, use_case: &str) -> Vec<String> {
        if !self.is_protected(use_case) {
            return vec![];
        }
        self.roles.get(use_case).cloned().unwrap_or_default()
    }

    /// The entity has an owner (27.18): its owner reads, edits and deletes its rows.
    pub fn is_owned(&self) -> bool {
        self.owned
    }

    /// Its use case lets the row's owner through, next to who holds its roles (27.18, 28.2).
    pub fn checks_owner(&self, use_case: &str) -> bool {
        self.auth && self.owner_checked.iter().any(|uc| uc == use_case)
    }

    /// The roles its route requires (`#[requiere_rol]`): [`Self::roles`], but none for a use case
    /// that checks them itself, next to the owner (27.18).
    pub fn route_roles(&self, use_case: &str) -> Vec<String> {
        if self.checks_owner(use_case) {
            return vec![];
        }
        self.roles(use_case)
    }

    /// Every role any of `use_cases`' routes requires, once each — what the route tests' caller
    /// holds.
    pub fn all_roles(&self, use_cases: &[String]) -> Vec<String> {
        let mut all: Vec<String> = vec![];
        for role in use_cases.iter().flat_map(|uc| self.route_roles(uc)) {
            if !all.contains(&role) {
                all.push(role);
            }
        }
        all
    }
}

/// The use cases of an owned entity that let its owner through (27.18, 28.2): `obtener`,
/// `actualizar`, `borrar` and its transitions with a route, but not its public ones nor those
/// in `solo_rol`. And `listar` (36.2): the owner's rows, or every row to who holds its roles.
pub fn owner_checked_use_cases(entity: &crate::puerto_toml::Entity) -> Vec<String> {
    let snake = crate::generators::naming::pascal_to_snake(&entity.name);
    ["get", "list", "update", "delete"]
        .iter()
        .map(|action| crate::generators::naming::crud_use_case(action, &snake))
        .chain(entity.routed_transition_use_cases())
        .filter(|uc| !entity.public.contains(uc) && !entity.role_only.contains(uc))
        .collect()
}

/// A host name has no `_`: the development user's address has to be one.
fn host(project: &str) -> String {
    project.replace('_', "-")
}

fn render_static(template: &str) -> Result<String, Box<dyn std::error::Error>> {
    Ok(render(template, &tera::Context::new())?)
}

/// A template that differs between the modes: `local` adds what registering and signing in need.
fn render_for(template: &str, local: bool) -> Result<String, Box<dyn std::error::Error>> {
    let mut ctx = tera::Context::new();
    ctx.insert("local", &local);
    Ok(render(template, &ctx)?)
}

/// One crate of the `usuario` context: its files, written once, then its `Cargo.toml`, `lib.rs`
/// and workspace entry (ADR-0023: it is not an `[[entidad]]`, so no scaffold or `cableado` entity
/// block touches it).
fn write_user_crate(
    base: &Path,
    layer: Layer,
    files: &[(&str, String)],
    db: bool,
    local: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    let c = layout::USER_CONTEXT;
    let dir = layout::crate_dir(c, layer);
    for (file, content) in files {
        write_file(&base.join(&dir).join("src").join(file), content)?;
    }
    let template = match layer {
        Layer::Domain => "contexto/usuario_dominio_cargo.tera",
        Layer::Application => "contexto/usuario_aplicacion_cargo.tera",
        Layer::Infrastructure => "contexto/usuario_infra_cargo.tera",
        Layer::Rest => "contexto/usuario_rest_cargo.tera",
    };
    let mut ctx = tera::Context::new();
    ctx.insert("db", &db);
    ctx.insert("local", &local);
    write_file(
        &base.join(layout::crate_manifest(c, layer)),
        &render(template, &ctx)?,
    )?;
    crate::generators::crates::write_lib(base, &dir, "")?;
    crate::generators::crates::add_internal_dependency(base, &layout::crate_name(c, layer), &dir)?;
    crate::generators::crates::sync_workspace_dependencies(base)?;
    Ok(())
}

/// The `Usuario` entity: model, errors and repository port.
fn write_user_domain(base: &Path, db: bool, local: bool) -> Result<(), Box<dyn std::error::Error>> {
    write_user_crate(
        base,
        Layer::Domain,
        &[
            ("modelo.rs", render_for("auth/user_model.tera", local)?),
            ("errores.rs", render_for("auth/user_errors.tera", local)?),
            (
                "repositorio.rs",
                render_static("auth/user_repository.tera")?,
            ),
        ],
        db,
        local,
    )
}

/// The user repository (in memory, or Postgres with its migration) and, for OIDC, the provisioning
/// authenticator.
fn write_user_infrastructure(
    base: &Path,
    db: bool,
    local: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    let repository = if db {
        "auth/user_repository_pg.tera"
    } else {
        "auth/user_repository_inmemory.tera"
    };
    let mut files = vec![("repositorio.rs", render_static(repository)?)];
    if db {
        // What the Postgres tests of a `ref:Usuario` seed (Fase 30).
        files.push(("pruebas/siembra.rs", render_static("auth/user_seed.tera")?));
    }
    if !local {
        files.push((
            "aprovisionamiento.rs",
            render_static("auth/provisioning.tera")?,
        ));
    }
    write_user_crate(base, Layer::Infrastructure, &files, db, local)?;
    if db {
        crate::generators::migration::run_migration(
            "crear_tabla_usuarios",
            base,
            Some(&render_static("auth/users.sql")?),
        )?;
    }
    Ok(())
}

/// The local use cases: one file each, contract and implementation (ADR-0023 § 4). The account
/// cycle (Fase 39, ADR-0035) follows the three of Fase 16.
const LOCAL_USE_CASES: [&str; 9] = [
    "login",
    "logout",
    "registrar_usuario",
    "solicitar_restablecimiento",
    "restablecer_contrasena",
    "cambiar_contrasena",
    "enviar_verificacion",
    "verificar_email",
    "actualizar_perfil",
];

/// The two mails of a local account (ADR-0035 § 2): ordinary `[[correo]]`s, the user's like any
/// other, with the link they carry and their text already written.
const LOCAL_MAILS: [&str; 2] = ["restablecer_contrasena", "verificar_email"];

/// The two mails, but one the project already declares (`generar ciclo-cuenta` in a project that
/// wrote them by hand).
fn write_local_mails(base: &Path) -> Result<(), Box<dyn std::error::Error>> {
    let declared = crate::puerto_toml::read(base)?.mail;
    for mail in LOCAL_MAILS {
        if declared.iter().any(|m| m.name == mail) {
            continue;
        }
        crate::generators::mail::run_generate_mail_on(
            mail,
            &["enlace:String".to_string()],
            &[],
            None,
            base,
        )?;
        let dir = base.join(layout::mail_templates_dir(mail));
        for file in ["asunto.txt", "cuerpo.html", "cuerpo.txt"] {
            write_file(
                &dir.join(file),
                &render_static(&format!("auth/local/correos/{mail}/{file}.tera"))?,
            )?;
        }
    }
    Ok(())
}

/// The `usuario` REST crate: `GET /me` and, with local accounts, `POST /auth/*`.
fn write_user_rest(base: &Path, db: bool, local: bool) -> Result<(), Box<dyn std::error::Error>> {
    let mut files = vec![
        ("me.rs", render_static("auth/me.tera")?),
        ("me/dto.rs", render_for("auth/me_dto.tera", local)?),
        ("me/rutas.rs", render_for("auth/me_routes.tera", local)?),
        // `GET /usuarios`, what a `ref:Usuario`'s select lists (Fase 30).
        ("dto.rs", render_static("auth/usuarios_dto.tera")?),
        ("rutas.rs", render_static("auth/usuarios_routes.tera")?),
    ];
    if local {
        for (file, template) in [
            ("auth.rs", "auth_api"),
            ("auth/dto.rs", "auth_dto"),
            ("auth/errores.rs", "auth_error_mapper"),
            ("auth/respuestas.rs", "auth_responses"),
            ("auth/rutas.rs", "auth_routes"),
        ] {
            files.push((file, render_static(&format!("auth/local/{template}.tera"))?));
        }
    }
    write_user_crate(base, Layer::Rest, &files, db, local)
}

/// The `usuario` use cases, one file each, contract and implementation (ADR-0023 § 4):
/// `listar_usuarios` (Fase 30) and, with local accounts, [`LOCAL_USE_CASES`].
fn write_user_application(
    base: &Path,
    db: bool,
    local: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut files = vec![(
        "listar_usuarios.rs".to_string(),
        crate::generators::merge::merge_use_case(
            &render_static("auth/listar_usuarios_trait.tera")?,
            &render_static("auth/listar_usuarios.tera")?,
        ),
    )];
    if local {
        for uc in LOCAL_USE_CASES {
            files.push((
                format!("{uc}.rs"),
                crate::generators::merge::merge_use_case(
                    &render_static(&format!("auth/local/{uc}_trait.tera"))?,
                    &render_static(&format!("auth/local/{uc}.tera"))?,
                ),
            ));
        }
    }
    let files: Vec<(&str, String)> = files.iter().map(|(f, c)| (f.as_str(), c.clone())).collect();
    write_user_crate(base, Layer::Application, &files, db, local)
}

/// Local accounts (`PLAN.md` § 16.6): the credentials and sessions migration after `users'`.
fn write_local_accounts(base: &Path) -> Result<(), Box<dyn std::error::Error>> {
    crate::generators::migration::run_migration(
        "crear_tablas_auth",
        base,
        Some(&render_static("auth/local/auth.sql")?),
    )?;
    Ok(())
}

/// `puerto-auth` and the `usuario` crates for the `api` binary: `bootstrap.rs` builds the
/// authenticator, the user repository and, with local accounts, the use cases and the hasher.
fn add_dependencies(base: &Path, local: bool) -> Result<(), Box<dyn std::error::Error>> {
    use crate::generators::bootstrap::add_crate_dependency;
    add_workspace_dependency(base, "puerto-auth")?;
    let feature = if local { "local" } else { "oidc" };
    add_crate_dependency(
        base,
        layout::API_MANIFEST,
        "dependencies",
        "puerto-auth",
        &format!("{{ workspace = true, features = [\"{feature}\"] }}"),
    )?;
    add_crate_dependency(
        base,
        layout::API_MANIFEST,
        "dependencies",
        "puerto-nucleo",
        "{ workspace = true }",
    )?;
    let c = layout::USER_CONTEXT;
    for layer in [
        Layer::Domain,
        Layer::Infrastructure,
        Layer::Rest,
        Layer::Application,
    ] {
        add_crate_dependency(
            base,
            layout::API_MANIFEST,
            "dependencies",
            &layout::crate_name(c, layer),
            "{ workspace = true }",
        )?;
    }
    if local {
        // `bootstrap.rs` builds the account mails' SMTP sender and template mailers (ADR-0035).
        let infra_correo = layout::crate_name(layout::MAIL_CONTEXT, Layer::Infrastructure);
        for name in ["puerto-correo", infra_correo.as_str()] {
            add_crate_dependency(
                base,
                layout::API_MANIFEST,
                "dependencies",
                name,
                "{ workspace = true }",
            )?;
        }
    }
    // The spec export test builds `ApiUsuario` (and `ApiAuth`) from the use cases' doubles.
    add_crate_dependency(
        base,
        layout::API_MANIFEST,
        "dev-dependencies",
        &layout::crate_name(c, Layer::Application),
        "{ workspace = true, features = [\"pruebas\"] }",
    )?;
    Ok(())
}

/// Inserts `line` after the first line of `manifest` that is exactly `after`.
fn insert_after_line(manifest: &str, after: &str, line: &str) -> Option<String> {
    let at = manifest.find(&format!("{after}\n"))? + after.len() + 1;
    Some(format!("{}{line}\n{}", &manifest[..at], &manifest[at..]))
}

fn keycloak_service(project: &str) -> String {
    format!(
        r#"  keycloak:
    image: {KEYCLOAK_IMAGE}
    container_name: {project}-keycloak
    # Importa keycloak/realm.json en el primer arranque: el cliente `web`, el
    # rol `admin` y un usuario que lo tiene (`task auth:ui`).
    command: start-dev --import-realm
    ports:
      - "{KEYCLOAK_PORT}:8080"
    environment:
      KC_BOOTSTRAP_ADMIN_USERNAME: admin
      KC_BOOTSTRAP_ADMIN_PASSWORD: admin
      KC_HEALTH_ENABLED: "true"
    volumes:
      - ./keycloak:/opt/keycloak/data/import:ro
    restart: unless-stopped
    healthcheck:
      # La imagen no trae curl: el /dev/tcp de bash pregunta al puerto de gestión.
      test: ["CMD-SHELL", "exec 3<>/dev/tcp/localhost/9000 && printf 'GET /health/ready HTTP/1.0\r\n\r\n' >&3 && grep -q UP <&3"]
      interval: 5s
      timeout: 5s
      retries: 30
"#
    )
}

fn write_keycloak(base: &Path, project: &str) -> Result<(), Box<dyn std::error::Error>> {
    let mut ctx = tera::Context::new();
    ctx.insert("realm", project);
    ctx.insert("project", project);
    ctx.insert("host", &host(project));
    ctx.insert("password", DEV_PASSWORD);
    write_file(
        &base.join(layout::KEYCLOAK_REALM),
        &render("auth/realm.json.tera", &ctx)?,
    )?;
    add_compose_service(base, "keycloak", &keycloak_service(project))
}

fn add_env(base: &Path, project: &str) -> Result<(), Box<dyn std::error::Error>> {
    let vars = format!(
        "\n# Auth — el proveedor OpenID Connect (ADR-0021). Keycloak (docker-compose.yml) en\n\
         # desarrollo: `task auth:ui`; inicia sesión como admin@{host}.localhost / {DEV_PASSWORD}.\n\
         # Auth0: AUTH_ISSUER=https://<tenant>.auth0.com/, AUTH_AUDIENCE=<el identificador de la API>,\n\
         # AUTH_ROLES_CLAIM=<el claim que añade una Action, p. ej. https://example.com/roles>\n\
         AUTH_ISSUER=http://localhost:{KEYCLOAK_PORT}/realms/{project}\n\
         AUTH_AUDIENCE={AUDIENCE}\nAUTH_ROLES_CLAIM=realm_access.roles\n",
        host = host(project)
    );
    for file in [".env", ".env.example"] {
        let path = base.join(file);
        let mut content = fs::read_to_string(&path).unwrap_or_default();
        if content.contains("AUTH_ISSUER") {
            continue;
        }
        if !content.is_empty() && !content.ends_with('\n') {
            content.push('\n');
        }
        content.push_str(&vars);
        fs::write(&path, content)?;
    }
    Ok(())
}

/// `AUTH_SESSION_TTL`, read by `puerto_sqlx::auth::ttl_sesion_from_env`, and `APP_URL`, where the
/// links of the account mails point (ADR-0035).
fn add_local_env(base: &Path) -> Result<(), Box<dyn std::error::Error>> {
    let vars = "\n# Auth — las cuentas, en esta base de datos (ADR-0021). Lo que dura una sesión: 30d, 12h, 90m.\n\
                AUTH_SESSION_TTL=30d\n\
                # La web a la que apuntan los enlaces de los correos de la cuenta (restablecer la contraseña,\n\
                # verificar el email): la de Vite en desarrollo.\n\
                APP_URL=http://localhost:5173\n";
    for file in [".env", ".env.example"] {
        let path = base.join(file);
        let mut content = fs::read_to_string(&path).unwrap_or_default();
        if content.contains("AUTH_SESSION_TTL") {
            continue;
        }
        if !content.is_empty() && !content.ends_with('\n') {
            content.push('\n');
        }
        content.push_str(vars);
        fs::write(&path, content)?;
    }
    Ok(())
}

/// `APP_URL` in `.env` and `.env.example` when they lack it: a local project from before the account
/// cycle has `AUTH_SESSION_TTL` without it.
fn add_app_url(base: &Path) -> Result<(), Box<dyn std::error::Error>> {
    let vars = "\n# La web a la que apuntan los enlaces de los correos de la cuenta (restablecer la contraseña,\n\
                # verificar el email): la de Vite en desarrollo.\n\
                APP_URL=http://localhost:5173\n";
    for file in [".env", ".env.example"] {
        let path = base.join(file);
        let mut content = fs::read_to_string(&path).unwrap_or_default();
        if content.contains("APP_URL=") {
            continue;
        }
        if !content.is_empty() && !content.ends_with('\n') {
            content.push('\n');
        }
        content.push_str(vars);
        fs::write(&path, content)?;
    }
    Ok(())
}

/// The OIDC tasks: Keycloak's console and a development token from the realm's `dev-cli` client
/// (password grant): `curl -H "Authorization: Bearer $(task auth:token)" …`. The account is the
/// argument after `--`, not a variable: an `EMAIL` in the shell is not one.
const OIDC_TASKS: &str = r#"
  auth:ui:
    desc: "La consola de Keycloak: usuarios, roles, sesiones"
    deps: [docker-compose:up]
    silent: true
    cmds:
      - 'echo "Keycloak: http://localhost:@KEYCLOAK_PORT@/admin/master/console/#/@PROJECT@ (admin / admin)"'
      - 'echo "Inicia sesión en la app como admin@@HOST@.localhost / @PASSWORD@ (rol admin)"'

  auth:token:
    desc: "Un token de acceso de desarrollo: task auth:token [-- user@@HOST@.localhost]"
    dotenv: [".env"]
    silent: true
    vars:
      CUENTA: '{{.CLI_ARGS | default "admin@@HOST@.localhost"}}'
    cmd: >-
      curl -sf "$AUTH_ISSUER/protocol/openid-connect/token" -d grant_type=password -d client_id=dev-cli
      --data-urlencode "username={{.CUENTA}}" --data-urlencode "password=@PASSWORD@"
      | sed -n 's/.*"access_token":"\([^"]*\)".*/\1/p' | grep .
      || { echo "sin token para {{.CUENTA}} de $AUTH_ISSUER: ¿está arrancado Keycloak? task docker-compose:up" >&2; exit 1; }
"#;

/// `task auth:conceder`: a role is a row's `roles` entry in a local project, applied from the next
/// request (no cache in between).
const LOCAL_TASKS: &str = r#"
  auth:conceder:
    desc: "Concede un rol a una cuenta: task auth:conceder EMAIL=ada@example.com ROL=admin"
    deps: [docker-compose:up]
    requires:
      vars: [EMAIL, ROL]
    cmd: >-
      docker compose exec -T postgres psql -U devuser -d @DB@ -v ON_ERROR_STOP=1 -c
      "UPDATE usuarios SET roles = array_append(roles, '{{.ROL}}'), actualizado_en = now() WHERE emisor = 'local' AND sujeto = lower(trim('{{.EMAIL}}')) AND NOT '{{.ROL}}' = ANY(roles)"
"#;

/// The auth tasks, and the containers' tasks a project without a database lacks; `run` starts
/// the containers first (the provider `bootstrap.rs` discovers, or the database).
fn add_tasks(base: &Path, project: &str, local: bool) -> Result<(), Box<dyn std::error::Error>> {
    use crate::generators::project;
    project::add_compose_tasks(base)?;
    project::add_compose_dependency(base, "run")?;
    if local {
        let tasks = LOCAL_TASKS.replace("@DB@", &project.replace('-', "_"));
        project::add_tasks(base, "auth:conceder", &tasks)
    } else {
        let tasks = OIDC_TASKS
            .replace("@KEYCLOAK_PORT@", &KEYCLOAK_PORT.to_string())
            .replace("@PROJECT@", project)
            .replace("@HOST@", &host(project))
            .replace("@PASSWORD@", DEV_PASSWORD);
        project::add_tasks(base, "auth:ui", &tasks)
    }
}

/// The frontend's auth files of both modes, written once under `web/` (their templates mirror the
/// paths). The last two replace the template's own: the frame shows the user, and
/// `renderizarPantalla` signs a caller in. `main.tsx` (the app inside `ProveedorAuth`, the access
/// pages outside the app's frame) is `project::write_main`'s, which also knows the portada.
const WEB_FILES: [&str; 15] = [
    "src/auth/sesion.ts",
    "src/auth/middleware-bearer.ts",
    "src/auth/middleware-bearer.test.ts",
    "src/auth/auth.tsx",
    "src/auth/auth.test.tsx",
    "src/compartido/ui/menu-usuario.tsx",
    "src/compartido/ui/menu-usuario.test.tsx",
    "src/compartido/ui/avatar.tsx",
    "src/compartido/ui/avatar.test.tsx",
    "src/compartido/ui/marco-acceso.tsx",
    "src/paginas/perfil.tsx",
    "src/paginas/perfil.test.tsx",
    "src/pruebas/auth.ts",
    "src/compartido/ui/marco.tsx",
    "src/pruebas/renderizar.tsx",
];

/// An OIDC project's: the provider's client and the page it sends the user back to.
const OIDC_WEB_FILES: [&str; 4] = [
    "src/auth/pasarela-oidc.ts",
    "src/auth/pasarela-oidc.test.ts",
    "src/paginas/auth-callback.tsx",
    "src/paginas/auth-callback.test.tsx",
];

/// A local project's: the `Accounts` port, the gateway over `/auth/*`, the sign-in and sign-up pages
/// and the account cycle's (Fase 39): the links of its mails and the settings `/perfil` shows.
const LOCAL_WEB_FILES: [&str; 16] = [
    "src/auth/cuentas.ts",
    "src/auth/mensajes.ts",
    "src/auth/pasarela-local.ts",
    "src/auth/pasarela-local.test.ts",
    "src/auth/ajustes-cuenta.tsx",
    "src/auth/ajustes-cuenta.test.tsx",
    "src/paginas/login.tsx",
    "src/paginas/login.test.tsx",
    "src/paginas/registro.tsx",
    "src/paginas/registro.test.tsx",
    "src/paginas/contrasena-olvidada.tsx",
    "src/paginas/contrasena-olvidada.test.tsx",
    "src/paginas/contrasena-nueva.tsx",
    "src/paginas/contrasena-nueva.test.tsx",
    "src/paginas/verificar.tsx",
    "src/paginas/verificar.test.tsx",
];

/// The dependency-cruiser rule that keeps the provider's client behind `PasarelaAuth`.
const CRUISER_RULE: &str = r#"    {
      name: "solo-la-pasarela-importa-oidc-client-ts",
      comment:
        "El cliente del proveedor se queda detrás de PasarelaAuth: las pantallas ven un UsuarioActual, nunca un token.",
      severity: "error",
      from: { pathNot: "^src/auth/pasarela-oidc" },
      to: { path: "oidc-client-ts" },
    },
"#;

/// `oidc-client-ts` in `web/package.json`, before `openapi-fetch` (dependencies stay sorted).
fn add_oidc_client(package: &str) -> Option<String> {
    if package.contains("\"oidc-client-ts\"") {
        return Some(package.to_string());
    }
    let at = package.find("    \"openapi-fetch\": ")?;
    Some(format!(
        "{}    \"oidc-client-ts\": \"{OIDC_CLIENT_TS_VERSION}\",\n{}",
        &package[..at],
        &package[at..]
    ))
}

/// The provider and client `oidc-client-ts` signs in with — read by `oidcSettingsFromEnv()`.
fn web_env(project: &str) -> String {
    format!(
        "# Auth — el proveedor OpenID Connect con el que inicia sesión el navegador (ADR-0021).\n\
         # Keycloak en desarrollo; Auth0: VITE_AUTH_ISSUER=https://<tenant>.auth0.com/,\n\
         # VITE_AUTH_CLIENT_ID=<el client id de la SPA>, VITE_AUTH_AUDIENCE=<el identificador de la\n\
         # API, el AUTH_AUDIENCE de la API>.\n\
         VITE_AUTH_ISSUER=http://localhost:{KEYCLOAK_PORT}/realms/{project}\n\
         VITE_AUTH_CLIENT_ID=web\n\
         VITE_AUTH_AUDIENCE=\n"
    )
}

/// The frontend half (`PLAN.md` § 16.5, § 16.7): sign in — with the provider, or with a password
/// — send the token, guard screens.
fn write_web(base: &Path, project: &str, local: bool) -> Result<(), Box<dyn std::error::Error>> {
    let web = base.join("web");
    let mode_files: &[&str] = if local {
        &LOCAL_WEB_FILES
    } else {
        &OIDC_WEB_FILES
    };
    for file in WEB_FILES.iter().chain(mode_files) {
        write_file(
            &web.join(file),
            &render_for(&format!("auth/web/{file}.tera"), local)?,
        )?;
    }
    if local {
        return Ok(());
    }

    let path = web.join("package.json");
    let package = fs::read_to_string(&path)?;
    let package = add_oidc_client(&package).ok_or_else(|| {
        format!(
            "{}: no tiene la dependencia `openapi-fetch`",
            path.display()
        )
    })?;
    fs::write(&path, package)?;

    let path = web.join(".dependency-cruiser.cjs");
    let cruiser = fs::read_to_string(&path)?;
    if !cruiser.contains("oidc-client-ts") {
        let cruiser = insert_after_line(&cruiser, "  forbidden: [", CRUISER_RULE.trim_end())
            .ok_or_else(|| format!("{}: no tiene `forbidden: [`", path.display()))?;
        fs::write(&path, cruiser)?;
    }

    for file in [".env", ".env.example"] {
        let path = web.join(file);
        let mut content = fs::read_to_string(&path).unwrap_or_default();
        if content.contains("VITE_AUTH_ISSUER") {
            continue;
        }
        if !content.is_empty() && !content.ends_with('\n') {
            content.push('\n');
        }
        content.push_str(&web_env(project));
        fs::write(&path, content)?;
    }
    Ok(())
}

/// The root `AGENTS.md` section an auth project gets (ADR-0010: what it names is tested).
pub const AGENTS_AUTH_SECTION: &str = r#"## Auth (`[proyecto] auth`)

La API es un servidor de recursos OAuth2 (ADR-0021 de Puerto): verifica el token bearer de cada
petición protegida contra el proveedor de `AUTH_ISSUER`: Keycloak en desarrollo
(`task docker-compose:up`, `task auth:ui`), Auth0 o cualquier proveedor OpenID Connect en
producción.

- Un handler que recibe `auth: BearerAuth` está protegido: sin token o con uno malo se responde
  `401 auth.no_autenticado` antes de ejecutarlo. Un `#[requiere_rol("admin")]` encima añade la
  comprobación `403 auth.prohibido`. Las dos cosas vienen de `puerto_web`.
- `puerto generar scaffold <Nombre>` protege todas las rutas CRUD. `--publico
  listar_productos,obtener_producto` deja rutas abiertas; `--rol borrar_producto=admin` añade
  `#[requiere_rol]` (dos roles en una ruta: quien llama necesita los dos). Las dos opciones quedan
  en `publicos` / `roles` de la entidad en `puerto.toml`, y `puerto validar` comprueba que
  `rutas.rs` sigue diciendo lo mismo: cambia los dos a la vez.
- Los params de un caso de uso protegido llevan `actor: Principal` (el handler pasa `auth.0`); los
  tests construyen uno con `puerto_nucleo::auth::dobles::MadrePrincipal`. `generar caso-de-uso`
  también lo añade.
- **Los roles salen solo del token** (`AUTH_ROLES_CLAIM`); la columna `usuarios.roles` no se lee.
- Para llamar a la API a mano: `curl -H "Authorization: Bearer $(task auth:token)" …`;
  `admin@…` tiene `admin`, y `task auth:token -- user@…` ningún rol. Lo pide al cliente
  `dev-cli` del realm de desarrollo (password grant): no crees nunca un cliente así en un proveedor
  real.
- Cada quien llama es un `Usuario` (`contextos/usuario/dominio/`), que crea en su primera petición
  `contextos/usuario/infraestructura/src/aprovisionamiento.rs`. Señala a una persona con un
  `IdUsuario`, nunca con el sujeto del proveedor. Estos ficheros son tuyos.
- `GET /me` responde quién llama, tal como lo resolvió la API. El frontend lo lee a él, nunca el
  token.
- `GET /usuarios` (`contextos/usuario/rest/src/rutas.rs`) lista los usuarios, **con su email**, a
  cualquiera con sesión: es lo que ofrece el `<select>` de una referencia a un usuario
  (`responsable_id:ref:Usuario`). Con OIDC, un usuario solo existe tras su primer login. Para
  cerrarla, un `#[requiere_rol(…)]` encima de `listar`.
- Una regla que depende de los datos («solo edita el propietario») va en el caso de uso, no en un
  atributo.

"#;

/// The root `AGENTS.md` section of a project that keeps its own accounts (`--auth local`).
pub const AGENTS_AUTH_LOCAL_SECTION: &str = r#"## Auth (`[proyecto] auth`)

La API guarda sus propias cuentas (ADR-0021 de Puerto): `POST /auth/registro` crea una,
`POST /auth/login` responde un token de sesión opaco y `POST /auth/logout` lo revoca. Un cliente
envía el token como `Authorization: Bearer <token>`; la base de datos solo guarda su SHA-256.

- Un handler que recibe `auth: BearerAuth` está protegido: sin sesión, o con una desconocida o
  caducada, se responde `401 auth.no_autenticado` antes de ejecutarlo. Un `#[requiere_rol("admin")]`
  encima añade la comprobación `403 auth.prohibido`. Las dos cosas vienen de `puerto_web`.
- `puerto generar scaffold <Nombre>` protege todas las rutas CRUD. `--publico
  listar_productos,obtener_producto` deja rutas abiertas; `--rol borrar_producto=admin` añade
  `#[requiere_rol]` (dos roles en una ruta: quien llama necesita los dos). Las dos opciones quedan
  en `publicos` / `roles` de la entidad en `puerto.toml`, y `puerto validar` comprueba que
  `rutas.rs` sigue diciendo lo mismo: cambia los dos a la vez.
- Los params de un caso de uso protegido llevan `actor: Principal` (el handler pasa `auth.0`); los
  tests construyen uno con `puerto_nucleo::auth::dobles::MadrePrincipal`. `generar caso-de-uso`
  también lo añade.
- **Los roles son la columna `usuarios.roles`**: `task auth:conceder EMAIL=… ROL=…`. Se aplican
  desde la petición siguiente.
- Las contraseñas son hashes argon2id en `credenciales`; `Usuario` no lleva ningún secreto. Un login
  con un email desconocido y otro con una contraseña equivocada reciben el mismo
  `401 auth.credenciales_invalidas`, en el mismo tiempo. Las sesiones duran `AUTH_SESSION_TTL`
  (`.env`); las filas caducadas se rechazan, y podarlas te toca a ti.
- `registrar_usuario`, `login`, `logout` (`contextos/usuario/aplicacion/`) y
  `contextos/usuario/rest/src/auth/` son tuyos. El registro está abierto: ciérralo, o añade reglas,
  ahí.
- El ciclo de la cuenta (ADR-0035 de Puerto), también tuyo: `POST /auth/restablecimiento` envía el
  enlace para elegir una contraseña nueva (responde 204 haya cuenta o no) y
  `/auth/restablecimiento/confirmar` la guarda; `PUT /auth/contrasena` la cambia sabiendo la actual
  y responde una sesión nueva; `POST /auth/verificacion` reenvía el enlace para verificar el email
  (el registro ya lo envía) y `/auth/verificacion/confirmar` lo marca; `PUT /auth/perfil` cambia el
  nombre. Cambiar o restablecer la contraseña cierra todas las sesiones de la cuenta.
- Los enlaces son tokens de un solo uso (`tokens`, solo su SHA-256) que apuntan a `APP_URL`
  (`.env`). Sus correos son dos `[[correo]]` normales, `restablecer_contrasena` y
  `verificar_email`: su texto, en `contextos/correo/infraestructura/plantillas/`. Salen del caso de
  uso, en la misma petición. Los tokens caducados, como las sesiones, se podan a mano.
- **Verificar el email no se exige en ningún sitio**: `actor.email_verificado` (y `GET /me`,
  `emailVerificado`) lo dice. Para exigirlo en un caso de uso, compara con `Some(true)`.
- `GET /me` responde quién llama, tal como lo resolvió la API.
- `GET /usuarios` (`contextos/usuario/rest/src/rutas.rs`) lista los usuarios, **con su email**, a
  cualquiera con sesión: es lo que ofrece el `<select>` de una referencia a un usuario
  (`responsable_id:ref:Usuario`). Con el registro abierto eso es cualquiera: ciérrala con un
  `#[requiere_rol(…)]` encima de `listar`.
- Una regla que depende de los datos («solo edita el propietario») va en el caso de uso, no en un
  atributo.

"#;

/// What follows [`AGENTS_AUTH_SECTION`] in a project with `web/`.
pub const AGENTS_AUTH_WEB_SECTION: &str = r#"### Auth en `web/`

- `useAuth()` (`auth/auth.tsx`) da `{ usuario, puede(rol), login, logout }`; `usuario` es
  `GET /me`, nunca el token. Las pantallas generadas esconden lo que `puede` niega, pero decide la
  API: su `403` llega a la alerta como `auth.prohibido`.
- `generado/rutas.tsx` envuelve cada pantalla no pública en `<RequiereAuth>`, que inicia sesión y
  vuelve. Envuelve igual tus propias rutas en `rutas.tsx`.
- `/auth/callback` va en `main.tsx`, dentro de `MarcoAcceso` (sin el menú de la app); `/perfil`
  (`paginas/perfil.tsx`) muestra lo que responde `GET /me` y se abre desde el menú de usuario.
- El token se queda en memoria y `oidc-client-ts` se queda en `auth/pasarela-oidc.ts`
  (`task web:lint` lo comprueba): al recargar se vuelve a iniciar sesión con la sesión del
  proveedor. `web/.env` guarda `VITE_AUTH_*`.
- Los tests de pantalla inician sesión con alguien que tiene todos los roles
  (`renderizarPantalla`); pasa `{ usuario }` para otro (`MadreUsuarioActual`), o
  `{ auth: pasarelaAuthFalsa(…) }` para ver los inicios de sesión que lanza.

"#;

/// What follows [`AGENTS_AUTH_LOCAL_SECTION`] in a project with `web/`.
pub const AGENTS_AUTH_LOCAL_WEB_SECTION: &str = r#"### Auth en `web/`

- `useAuth()` (`auth/auth.tsx`) da `{ usuario, puede(rol), login, logout }`; `usuario` es
  `GET /me`. Las pantallas generadas esconden lo que `puede` niega, pero decide la API: su `403`
  llega a la alerta como `auth.prohibido`.
- `generado/rutas.tsx` envuelve cada pantalla no pública en `<RequiereAuth>`, que manda a quien no
  tiene sesión iniciada a `/login?siguiente=…`, igual que un `401` de cualquier llamada. Envuelve
  igual tus propias rutas en `rutas.tsx`.
- `/login` y `/registro` (`paginas/`) inician sesión a través de `Cuentas` (`auth/cuentas.ts`);
  `auth/mensajes.ts` convierte los códigos de la API en lo que dicen los formularios, bajo el campo
  al que se refieren. `main.tsx` las monta dentro de `MarcoAcceso` (la marca a un lado, el
  formulario en una tarjeta), sin el menú de la app. Estos ficheros son tuyos.
- `/perfil` (`paginas/perfil.tsx`) muestra lo que responde `GET /me` y se abre desde el menú de
  usuario; debajo, `AjustesCuenta` (`auth/ajustes-cuenta.tsx`): el aviso «Verifica tu email» con
  «Reenviar» mientras no lo esté, el nombre y «Cambiar contraseña».
- Los enlaces de los correos llevan a `/verificar?token=` y `/contrasena/nueva?token=`, que
  `main.tsx` monta en `MarcoAcceso` junto a `/contrasena/olvidada` (enlazada desde `/login`). Si
  cambias esas rutas, cambia también el enlace en su caso de uso.
- El token de sesión está en `localStorage` (`auth/pasarela-local.ts`): al recargar se sigue con la
  sesión iniciada; «Cerrar sesión» la revoca en la API.
- Los tests de pantalla inician sesión con alguien que tiene todos los roles
  (`renderizarPantalla`); pasa `{ usuario }` para otro (`MadreUsuarioActual`),
  `{ auth: pasarelaAuthFalsa(…) }` o `{ cuentas: cuentasFalsas() }` para ver lo que pidió una
  pantalla.

"#;

fn add_agents_section(
    base: &Path,
    web: bool,
    local: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    let path = base.join("AGENTS.md");
    let Ok(agents) = fs::read_to_string(&path) else {
        return Ok(());
    };
    if agents.contains("## Auth (`[proyecto] auth`)") {
        return Ok(());
    }
    let section = if local && web {
        format!("{AGENTS_AUTH_LOCAL_SECTION}{AGENTS_AUTH_LOCAL_WEB_SECTION}")
    } else if local {
        AGENTS_AUTH_LOCAL_SECTION.to_string()
    } else if web {
        format!("{AGENTS_AUTH_SECTION}{AGENTS_AUTH_WEB_SECTION}")
    } else {
        AGENTS_AUTH_SECTION.to_string()
    };
    // Before the conventions: next to the rules about what is generated.
    let out = match agents.find("## Convenciones") {
        Some(at) => format!("{}{section}{}", &agents[..at], &agents[at..]),
        None => format!("{agents}\n{section}"),
    };
    fs::write(&path, out)?;
    Ok(())
}

/// Turns a fresh project into an auth one (`puerto nuevo --auth oidc|local`). The Saludo demo
/// stays open: it is listed `public`.
pub fn apply_auth_to_new_project(
    base: &Path,
    mode: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    check_mode(mode)?;
    let mut config = crate::puerto_toml::read(base)?;
    config.project.auth = Some(mode.to_string());
    for entity in &mut config.entity {
        if entity.name == "Saludo" && entity.public.is_empty() {
            entity.public = entity.use_cases.clone();
        }
    }
    crate::puerto_toml::write(base, &config)?;
    let project = config.project.name.clone();

    let local = mode == "local";

    if local {
        // Before the `usuario` crates: `aplicacion_usuario` depends on `dominio_correo`.
        write_local_mails(base)?;
    }
    write_user_domain(base, config.project.db, local)?;
    write_user_infrastructure(base, config.project.db, local)?;
    write_user_application(base, config.project.db, local)?;
    write_user_rest(base, config.project.db, local)?;
    add_dependencies(base, local)?;
    if local {
        write_local_accounts(base)?;
        add_local_env(base)?;
    } else {
        write_keycloak(base, &project)?;
        add_env(base, &project)?;
    }
    add_tasks(base, &project, local)?;
    if config.project.web {
        write_web(base, &project, local)?;
        crate::generators::project::write_main(base)?;
    }
    add_agents_section(base, config.project.web, local)?;

    crate::generators::bootstrap::regenerate_bootstrap(base)?;
    Ok(())
}

/// Where a local project from before the account cycle (Fase 39) lacks it: this use case.
fn account_cycle_marker() -> String {
    layout::use_case(layout::USER_CONTEXT, "solicitar_restablecimiento")
}

/// What `puerto generar ciclo-cuenta` writes: the migration that brings the tables of before up to
/// the cycle's, the two mails, the `usuario` context as a new local project has it, `APP_URL`, the
/// API's dependencies, the web of the cycle, and the wiring.
fn write_account_cycle(base: &Path) -> Result<(), Box<dyn std::error::Error>> {
    let config = crate::puerto_toml::read(base)?;
    // The guide of 0.34 has the project write this migration by hand before the runtime goes up.
    let has_tokens = fs::read_dir(base.join(layout::MIGRATIONS_DIR)).is_ok_and(|entries| {
        entries.flatten().any(|e| {
            fs::read_to_string(e.path()).is_ok_and(|sql| sql.contains("CREATE TABLE tokens"))
        })
    });
    if !has_tokens {
        crate::generators::migration::run_migration(
            "ciclo_cuenta",
            base,
            Some(&render_static("auth/local/ciclo_cuenta.sql")?),
        )?;
    }
    // Before the `usuario` crates: `aplicacion_usuario` depends on `dominio_correo`.
    write_local_mails(base)?;
    write_user_domain(base, config.project.db, true)?;
    write_user_application(base, config.project.db, true)?;
    write_user_rest(base, config.project.db, true)?;
    add_dependencies(base, true)?;
    add_app_url(base)?;
    if config.project.web {
        write_web(base, &config.project.name, true)?;
        crate::generators::project::write_main(base)?;
    }
    crate::generators::bootstrap::regenerate_bootstrap(base)
}

/// `puerto generar ciclo-cuenta [--forzar]` (Fase 42.2): the local account cycle (Fase 39,
/// ADR-0035) in a `--auth local` project from before it. It runs on a copy of the project, so the
/// files of the user it would change are known before any is written; then the copy's changes are
/// brought over. `puerto deshacer` takes them all back.
pub fn run_generate_account_cycle(
    base: &Path,
    policy: crate::generators::conflict::OverwritePolicy,
) -> Result<(), Box<dyn std::error::Error>> {
    use crate::tree::{self, Change};
    let config = crate::puerto_toml::read(base)?;
    if config.project.auth.as_deref() != Some("local") {
        return Err(
            "el ciclo de la cuenta es el de las cuentas locales: necesita un proyecto \
                    `--auth local`"
                .into(),
        );
    }
    if base.join(account_cycle_marker()).exists() {
        return Err(format!(
            "este proyecto ya tiene el ciclo de la cuenta ({})",
            account_cycle_marker()
        )
        .into());
    }

    println!("Primero, sobre una copia del proyecto:");
    let copy = tempfile::tempdir()?;
    tree::copy_project(base, copy.path())?;
    let before = tree::snapshot(copy.path())?;
    write_account_cycle(copy.path())?;
    // Formatted as the project's files are, so a file the cycle leaves as it was is not a change.
    let _ = crate::generators::format::format_project(copy.path());
    let after = tree::snapshot(copy.path())?;
    let changes = tree::changes(&before, &after);

    // The user's files it rewrites. The rest only gain lines (`.env`, `Cargo.toml`s, `lib.rs`, the
    // tasks) or are Puerto's (`puerto.toml`, what `generado/` and `cableado/` hold).
    let mine = |path: &Path| {
        (path.starts_with("contextos") || path.starts_with("web/src"))
            && !path.ends_with("lib.rs")
            && !path.starts_with("web/src/generado")
    };
    let modified: Vec<PathBuf> = changes
        .iter()
        .filter(|(path, change)| matches!(change, Change::Modified { .. }) && mine(path))
        .map(|(path, _)| path.clone())
        .collect();
    crate::generators::conflict::guard_files_overwrite(base, "ciclo-cuenta", &modified, policy)?;

    for (path, change) in &changes {
        let target = base.join(path);
        match change {
            Change::Deleted => fs::remove_file(&target)?,
            _ => {
                if let Some(parent) = target.parent() {
                    fs::create_dir_all(parent)?;
                }
                fs::write(&target, &after[path])?;
            }
        }
    }

    println!(
        "\n✓ El ciclo de la cuenta, en el proyecto: restablecer y cambiar la contraseña, verificar \
         el email y el perfil"
    );
    for (path, change) in &changes {
        let mark = match change {
            Change::Created => "+",
            Change::Modified { .. } => "~",
            Change::Deleted => "-",
        };
        println!("  {mark} {}", path.display());
    }
    println!(
        "  Lo que habías cambiado a mano en los `~`, en `git diff`; `puerto deshacer` lo revierte todo."
    );
    println!("  Aplica la migración: task sqlx:migrate");
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn should_write_local_accounts_only_with_a_database() {
        assert!(check_new_project("oidc", false).is_ok());
        assert!(check_new_project("local", true).is_ok());
        assert!(
            check_new_project("local", false)
                .unwrap_err()
                .contains("--db")
        );
        assert!(
            check_new_project("auth0", true)
                .unwrap_err()
                .contains("modo de auth desconocido")
        );
    }

    #[test]
    fn should_insert_after_the_exact_line_when_the_manifest_has_it() {
        let manifest = "[dependencies]\npuerto-nucleo = { workspace = true }\npoem = \"3\"\n";
        assert_eq!(
            insert_after_line(manifest, "puerto-nucleo = { workspace = true }", "x = 1"),
            Some(
                "[dependencies]\npuerto-nucleo = { workspace = true }\nx = 1\npoem = \"3\"\n"
                    .into()
            )
        );
        assert_eq!(
            insert_after_line(manifest, "[dev-dependencies]", "x = 1"),
            None
        );
    }

    fn access(auth: bool, public: &[&str], roles: &[(&str, &[&str])]) -> Access {
        Access {
            auth,
            public: public.iter().map(|s| s.to_string()).collect(),
            roles: roles
                .iter()
                .map(|(uc, r)| (uc.to_string(), r.iter().map(|s| s.to_string()).collect()))
                .collect(),
            owned: false,
            owner_checked: vec![],
        }
    }

    #[test]
    fn should_protect_every_use_case_but_the_public_ones_when_the_project_has_auth() {
        let access = access(true, &["listar_products"], &[]);
        assert!(access.is_protected("crear_product"));
        assert!(!access.is_protected("listar_products"));
    }

    #[test]
    fn should_protect_nothing_when_the_project_has_no_auth() {
        let access = access(false, &[], &[("crear_product", &["admin"])]);
        assert!(!access.is_protected("crear_product"));
        assert_eq!(access.roles("crear_product"), Vec::<String>::new());
    }

    #[test]
    fn should_collect_each_role_once_when_use_cases_share_it() {
        let access = access(
            true,
            &[],
            &[
                ("crear_product", &["admin"]),
                ("borrar_product", &["admin", "owner"]),
            ],
        );
        let use_cases = ["crear_product".to_string(), "borrar_product".to_string()];
        assert_eq!(access.roles("borrar_product"), vec!["admin", "owner"]);
        assert_eq!(access.all_roles(&use_cases), vec!["admin", "owner"]);
    }

    #[test]
    fn should_add_the_oidc_client_before_openapi_fetch_once() {
        let package =
            "  \"dependencies\": {\n    \"openapi-fetch\": \"0.17.0\",\n    \"react\": \"19\"\n";
        let added = add_oidc_client(package).unwrap();
        assert_eq!(
            added,
            format!(
                "  \"dependencies\": {{\n    \"oidc-client-ts\": \"{OIDC_CLIENT_TS_VERSION}\",\n    \"openapi-fetch\": \"0.17.0\",\n    \"react\": \"19\"\n"
            )
        );
        assert_eq!(add_oidc_client(&added).unwrap(), added);
        assert_eq!(add_oidc_client("{}"), None);
    }

    #[test]
    fn should_make_a_host_name_when_the_project_name_has_underscores() {
        assert_eq!(host("my_shop"), "my-shop");
    }
}