Skip to main content

vgi_forge/
model.rs

1//! The data an adapter is handed and hands back.
2//!
3//! Everything here is forge-neutral and serialisable: these are the payloads
4//! of the VTC ↔ bridge jobs (`git-ns/bridge/*`), so a third-party bridge in
5//! another language sees the same shapes. Types that are expected to grow are
6//! `#[non_exhaustive]`; construct them with their constructors or
7//! `Default` and field assignment.
8
9use std::collections::BTreeMap;
10use std::fmt;
11
12use serde::{Deserialize, Serialize};
13
14use crate::bootstrap::MergeMethod;
15use crate::event::ProtectionGap;
16use crate::resource::Resource;
17use crate::rights::ForgeRole;
18
19/// Which forge software an adapter speaks.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
21#[serde(rename_all = "lowercase")]
22#[non_exhaustive]
23pub enum ForgeKind {
24    /// github.com or GitHub Enterprise Server.
25    GitHub,
26    /// Forgejo (and Gitea, best effort).
27    Forgejo,
28}
29
30impl ForgeKind {
31    /// Stable lowercase name: `github`, `forgejo`.
32    pub fn as_str(self) -> &'static str {
33        match self {
34            ForgeKind::GitHub => "github",
35            ForgeKind::Forgejo => "forgejo",
36        }
37    }
38}
39
40impl fmt::Display for ForgeKind {
41    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42        f.write_str(self.as_str())
43    }
44}
45
46/// Whether a namespace is an organisation or a personal account (§3, §8).
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
48#[serde(rename_all = "lowercase")]
49#[non_exhaustive]
50pub enum NamespaceKind {
51    /// An organisation: real roles, bot repo creation.
52    Organization,
53    /// A personal account: the reduced capability set of §8.
54    User,
55}
56
57/// A bound namespace, as the adapter needs it (§4.1). The VTC's record has
58/// more (`id`, `boundBy`, `boundAt`); the adapter needs only what locates the
59/// owner on the forge and the credential that acts on it.
60#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
61#[serde(rename_all = "camelCase")]
62#[non_exhaustive]
63pub struct Namespace {
64    /// `host/owner`, e.g. `github.com/acme`.
65    pub resource: Resource,
66    /// The forge's numeric id for the owner — survives renames.
67    pub owner_id: Option<u64>,
68    /// Organisation or personal account.
69    pub kind: NamespaceKind,
70    /// The automation credential's handle on this namespace (a GitHub App
71    /// installation id). `None` is manual mode: the VTC governs rights and
72    /// the registry, but nothing acts on the forge.
73    pub installation_id: Option<u64>,
74}
75
76impl Namespace {
77    /// A namespace with no owner id and no installation (manual mode).
78    pub fn new(resource: Resource, kind: NamespaceKind) -> Self {
79        Namespace {
80            resource,
81            owner_id: None,
82            kind,
83            installation_id: None,
84        }
85    }
86
87    /// Set the owner's numeric id.
88    pub fn with_owner_id(mut self, id: u64) -> Self {
89        self.owner_id = Some(id);
90        self
91    }
92
93    /// Set the installation id.
94    pub fn with_installation(mut self, id: u64) -> Self {
95        self.installation_id = Some(id);
96        self
97    }
98}
99
100/// How a forge makes a status check required (§5.8 table).
101#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
102#[serde(rename_all = "camelCase")]
103#[non_exhaustive]
104pub enum RequiredCheckKind {
105    /// The forge cannot require a check: repos are flagged *unprotected*.
106    #[default]
107    None,
108    /// A repository ruleset with a required status check (GitHub).
109    Ruleset,
110    /// Branch protection `status_check_contexts` (Forgejo).
111    BranchProtection,
112}
113
114/// How a member links their forge account (§4.4).
115#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
116#[serde(rename_all = "camelCase")]
117#[non_exhaustive]
118pub enum LinkMethod {
119    /// No automated link; the core records a binding some other way.
120    #[default]
121    None,
122    /// OAuth device flow — works from a terminal (GitHub).
123    DeviceFlow,
124    /// OAuth2 authorisation code with PKCE, through a browser (Forgejo).
125    AuthorizationCodePkce,
126}
127
128/// What a forge — and one namespace on it — can do (§5.8).
129///
130/// The core and the UX branch on this, never on [`ForgeKind`]. A personal
131/// GitHub account is not a special case: it is the GitHub adapter returning
132/// a smaller set here.
133#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
134#[serde(rename_all = "camelCase")]
135#[non_exhaustive]
136pub struct Capabilities {
137    /// The adapter holds a credential for this namespace and can act on it
138    /// at all. `false` is manual mode: every forge-side step is a human's.
139    pub automation: bool,
140    /// The bridge can create repositories here. Without it, `repo/create`
141    /// reserves the name and returns manual steps.
142    pub bot_can_create_repos: bool,
143    /// The forge roles available on repositories here, lowest first.
144    /// [`crate::collapse_to_ladder`] fits a requested role onto it.
145    pub role_levels: Vec<ForgeRole>,
146    /// How the verify-trust check is made required.
147    pub required_checks: RequiredCheckKind,
148    /// Whether the forge pushes change events. Without them, drift is found
149    /// by a scheduled `inspect` sweep.
150    pub webhooks: bool,
151    /// How members link their forge accounts.
152    pub account_link: LinkMethod,
153    /// Whether the credential can be narrowed to one repository per job.
154    pub per_repo_tokens: bool,
155    /// The check runs from a namespace-level workflow pinned to a revision
156    /// (a GitHub org ruleset's required workflow), so a pull request cannot
157    /// change what checks it. Without it the repository's own workflow is
158    /// guarded by owner review instead (§9).
159    #[serde(default)]
160    pub required_workflow: bool,
161    /// Without a namespace workflow, a repository with a single owner gets
162    /// no review requirement on its workflow (there is nobody else to
163    /// review), so its owner could weaken their own check. The UI shows
164    /// "solo: workflow edits not review-protected" for such repositories;
165    /// [`ProtectionState::check_source_guard`] says which applies to each.
166    #[serde(default)]
167    pub single_owner_repos_unreviewed: bool,
168    /// The bridge itself runs verify-trust against each pull request and
169    /// posts the check under its own forge identity, and the protection
170    /// requires the check *from that identity* (§9, "forged check runs").
171    /// Nothing in the repository decides what runs, and no CI workflow can
172    /// post a check that counts. The bridge becomes a merge dependency, as
173    /// the registry already is.
174    #[serde(default)]
175    pub bridge_posted_check: bool,
176}
177
178/// What keeps a repository's check out of reach of the pull request it
179/// checks (§9), as observed.
180#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
181#[serde(rename_all = "camelCase", tag = "type")]
182#[non_exhaustive]
183pub enum CheckSourceGuard {
184    /// Not observed (manual mode, or not inspected).
185    #[default]
186    Unknown,
187    /// A namespace-level workflow pinned to a commit. Its shortfalls are in
188    /// [`ProtectionState::other_gaps`].
189    RequiredWorkflow,
190    /// Workflow changes need an owner's approving review.
191    OwnerReview {
192        /// The accounts the managed owner rule names (ids resolved from the
193        /// forge's current logins).
194        reviewers: Vec<ForgeAccount>,
195        /// What is wrong with it; empty when it holds.
196        issues: Vec<String>,
197    },
198    /// No review guard: the repository's own workflow can be changed by a
199    /// pull request its owner merges. Accepted for a single-owner
200    /// repository.
201    Unreviewed,
202    /// The bridge runs the check itself and the protection accepts it only
203    /// from the bridge's own forge identity
204    /// ([`Capabilities::bridge_posted_check`]): nothing in the repository
205    /// is on the check's path.
206    BridgePosted,
207}
208
209/// A person's account on a forge. The numeric id is authoritative; the login
210/// is for display and can be renamed and re-registered (§4.4).
211#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
212#[serde(rename_all = "camelCase")]
213pub struct ForgeAccount {
214    /// Numeric account id.
215    pub id: u64,
216    /// Login at the time it was read. Display only.
217    pub login: String,
218}
219
220impl ForgeAccount {
221    /// An account from its id and current login.
222    pub fn new(id: u64, login: impl Into<String>) -> Self {
223        ForgeAccount {
224            id,
225            login: login.into(),
226        }
227    }
228}
229
230/// One person's desired role on one repository.
231#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
232#[serde(rename_all = "camelCase")]
233pub struct RoleAssignment {
234    /// Who.
235    pub account: ForgeAccount,
236    /// The role they should hold.
237    pub role: ForgeRole,
238}
239
240impl RoleAssignment {
241    /// Assign `role` to `account`.
242    pub fn new(account: ForgeAccount, role: ForgeRole) -> Self {
243        RoleAssignment { account, role }
244    }
245}
246
247/// What to do with direct collaborators the desired set does not mention.
248#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
249#[serde(rename_all = "camelCase")]
250#[non_exhaustive]
251pub enum Unlisted {
252    /// Leave them. Drift mode `report` (the default for roles, §5.6): the
253    /// core reports them and a human adopts or reverts.
254    #[default]
255    Keep,
256    /// Remove them. Drift mode `enforce`.
257    Remove,
258}
259
260/// Repository visibility.
261#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
262#[serde(rename_all = "lowercase")]
263#[non_exhaustive]
264pub enum Visibility {
265    /// Anyone can read.
266    #[default]
267    Public,
268    /// Only collaborators and org members with access.
269    Private,
270    /// Enterprise members (GitHub Enterprise).
271    Internal,
272}
273
274/// A repository to create (§5.2 `git-ns/repo/create`).
275#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
276#[serde(rename_all = "camelCase")]
277#[non_exhaustive]
278pub struct RepoSpec {
279    /// The full resource, `host/owner/name`.
280    pub resource: Resource,
281    /// Visibility.
282    pub visibility: Visibility,
283    /// Optional description.
284    #[serde(default, skip_serializing_if = "Option::is_none")]
285    pub description: Option<String>,
286    /// The repository's owners (`git.repo.own` holders) with linked forge
287    /// accounts — who may approve changes to its workflows where the forge
288    /// guards them with owner review (§9).
289    #[serde(default, skip_serializing_if = "Vec::is_empty")]
290    pub owners: Vec<ForgeAccount>,
291}
292
293impl RepoSpec {
294    /// A public repository with no description.
295    pub fn new(resource: Resource) -> Self {
296        RepoSpec {
297            resource,
298            visibility: Visibility::Public,
299            description: None,
300            owners: Vec::new(),
301        }
302    }
303
304    /// Add an owner.
305    pub fn with_owner(mut self, owner: ForgeAccount) -> Self {
306        self.owners.push(owner);
307        self
308    }
309
310    /// Set the visibility.
311    pub fn with_visibility(mut self, visibility: Visibility) -> Self {
312        self.visibility = visibility;
313        self
314    }
315
316    /// Set the description.
317    pub fn with_description(mut self, description: impl Into<String>) -> Self {
318        self.description = Some(description.into());
319        self
320    }
321}
322
323/// A collaborator as observed on the forge.
324#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
325#[serde(rename_all = "camelCase")]
326#[non_exhaustive]
327pub struct Collaborator {
328    /// Who.
329    pub account: ForgeAccount,
330    /// Their role (the base role, for a forge with custom roles).
331    pub role: ForgeRole,
332    /// An invitation not yet accepted. Counts as present for drift: the
333    /// adapter has done its part.
334    pub pending: bool,
335}
336
337impl Collaborator {
338    /// An accepted collaborator.
339    pub fn new(account: ForgeAccount, role: ForgeRole) -> Self {
340        Collaborator {
341            account,
342            role,
343            pending: false,
344        }
345    }
346
347    /// A pending invitation.
348    pub fn invited(account: ForgeAccount, role: ForgeRole) -> Self {
349        Collaborator {
350            account,
351            role,
352            pending: true,
353        }
354    }
355}
356
357/// The default-branch protection that makes the check mean something, as
358/// observed. Each flag is the *protective* state, so `Default` is "nothing
359/// protected".
360#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
361#[serde(rename_all = "camelCase")]
362#[non_exhaustive]
363pub struct ProtectionState {
364    /// The managed rule (ruleset, branch protection) exists.
365    pub present: bool,
366    /// It is enforced, not disabled or in evaluate-only mode.
367    pub enforced: bool,
368    /// It covers the default branch.
369    pub covers_default_branch: bool,
370    /// Changes must come through a pull request.
371    pub requires_pull_request: bool,
372    /// Status checks the rule requires (by context name).
373    pub required_checks: Vec<String>,
374    /// Force-pushes are blocked.
375    pub blocks_force_push: bool,
376    /// Branch deletion is blocked.
377    pub blocks_deletion: bool,
378    /// Actors allowed to bypass it. Must be empty (§5.3).
379    pub bypass_actors: Vec<String>,
380    /// Shortfalls in what keeps the check's own workflow out of the change
381    /// under test's reach (a namespace required workflow, owner review),
382    /// which the fields above cannot express. The adapter fills this in.
383    #[serde(default, skip_serializing_if = "Vec::is_empty")]
384    pub other_gaps: Vec<ProtectionGap>,
385    /// Which guard keeps the check out of the pull request's reach.
386    #[serde(default)]
387    pub check_source_guard: CheckSourceGuard,
388    /// Paths a pull request may not change (forge glob syntax), for a forge
389    /// that protects the workflow this way. Empty when not read.
390    #[serde(default, skip_serializing_if = "Vec::is_empty")]
391    pub protected_paths: Vec<String>,
392    /// The merge methods the repository allows, for an adapter that reads
393    /// them. `None`: not observed.
394    #[serde(default, skip_serializing_if = "Option::is_none")]
395    pub merge_methods: Option<Vec<MergeMethod>>,
396    /// Whether the forge's CI is enabled on the repository, for an adapter
397    /// that reads it. `None`: not observed.
398    #[serde(default, skip_serializing_if = "Option::is_none")]
399    pub ci_enabled: Option<bool>,
400}
401
402/// A repository as observed on the forge.
403#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
404#[serde(rename_all = "camelCase")]
405#[non_exhaustive]
406pub struct RepoState {
407    /// Where it is now (after any rename or transfer).
408    pub resource: Resource,
409    /// The forge's numeric repo id — rights are keyed on this (§9).
410    pub forge_id: u64,
411    /// Visibility.
412    pub visibility: Visibility,
413    /// Archived (read-only).
414    pub archived: bool,
415    /// The default branch, if the repository has any commits.
416    pub default_branch: Option<String>,
417    /// Direct collaborators and pending invitations.
418    pub collaborators: Vec<Collaborator>,
419    /// The managed default-branch protection.
420    pub protection: ProtectionState,
421}
422
423impl RepoState {
424    /// A state with no collaborators and no protection.
425    pub fn new(resource: Resource, forge_id: u64) -> Self {
426        RepoState {
427            resource,
428            forge_id,
429            visibility: Visibility::Public,
430            archived: false,
431            default_branch: None,
432            collaborators: Vec::new(),
433            protection: ProtectionState::default(),
434        }
435    }
436}
437
438/// What the VTC says a repository should look like on the forge: the
439/// enforced projection of §2.
440#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
441#[serde(rename_all = "camelCase")]
442#[non_exhaustive]
443pub struct Projection {
444    /// The resource the VTC holds for the repository.
445    pub resource: Resource,
446    /// The forge id the VTC recorded, if it has one. When set, a state with
447    /// the same id at a different resource is a rename, not a new repo.
448    pub forge_id: Option<u64>,
449    /// Desired roles for people with linked accounts. Nobody else should
450    /// hold a direct role.
451    pub roles: Vec<RoleAssignment>,
452    /// The check that must be required on the default branch
453    /// (`Verify commit trust`). `None` for a repo not yet bootstrapped.
454    pub required_check: Option<String>,
455    /// Whether the repository should be archived.
456    pub archived: bool,
457    /// The visibility the VTC recorded, if it tracks one.
458    pub visibility: Option<Visibility>,
459    /// The repository's owners with linked forge accounts. Where the forge
460    /// guards workflows with owner review, two or more owners must all be
461    /// reviewers; one owner is a solo repository with no review guard.
462    #[serde(default, skip_serializing_if = "Vec::is_empty")]
463    pub owners: Vec<ForgeAccount>,
464}
465
466impl Projection {
467    /// A projection with no roles and no required check.
468    pub fn new(resource: Resource) -> Self {
469        Projection {
470            resource,
471            forge_id: None,
472            roles: Vec::new(),
473            required_check: None,
474            archived: false,
475            visibility: None,
476            owners: Vec::new(),
477        }
478    }
479}
480
481/// What happened to one person in [`crate::Forge::apply_roles`].
482#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
483#[serde(rename_all = "camelCase")]
484#[non_exhaustive]
485pub struct RoleChange {
486    /// Who.
487    pub account: ForgeAccount,
488    /// Role before.
489    pub from: ForgeRole,
490    /// Role requested.
491    pub to: ForgeRole,
492    /// What the forge did.
493    pub outcome: RoleOutcome,
494}
495
496impl RoleChange {
497    /// A change of `account` from `from` to `to`, with its outcome.
498    pub fn new(
499        account: ForgeAccount,
500        from: ForgeRole,
501        to: ForgeRole,
502        outcome: RoleOutcome,
503    ) -> Self {
504        RoleChange {
505            account,
506            from,
507            to,
508            outcome,
509        }
510    }
511}
512
513/// Outcome of one role change.
514#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
515#[serde(rename_all = "camelCase", tag = "status", content = "detail")]
516#[non_exhaustive]
517pub enum RoleOutcome {
518    /// Applied directly.
519    Applied,
520    /// An invitation was sent (or updated); the person must accept.
521    Invited,
522    /// The forge refused; the message says why.
523    Failed(String),
524}
525
526/// Result of converging a repository's roles.
527#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
528#[serde(rename_all = "camelCase")]
529#[non_exhaustive]
530pub struct ApplyReport {
531    /// Every change attempted, in order.
532    pub changes: Vec<RoleChange>,
533    /// People already at their desired role.
534    pub unchanged: Vec<ForgeAccount>,
535    /// Direct collaborators not in the desired set that were left alone
536    /// because the call said [`Unlisted::Keep`].
537    pub kept_unlisted: Vec<Collaborator>,
538}
539
540impl ApplyReport {
541    /// Whether every attempted change went through.
542    pub fn is_complete(&self) -> bool {
543        !self
544            .changes
545            .iter()
546            .any(|c| matches!(c.outcome, RoleOutcome::Failed(_)))
547    }
548}
549
550/// Start binding a namespace (§4.1 step 1).
551#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
552#[serde(rename_all = "camelCase")]
553#[non_exhaustive]
554pub struct BindRequest {
555    /// The namespace to bind, `host/owner`.
556    pub namespace: Resource,
557    /// Single-use nonce the caller generated and stored (with its 15-minute
558    /// expiry); the forge will hand it back on the callback.
559    pub state: String,
560}
561
562impl BindRequest {
563    /// Bind `namespace`, with `state` as the nonce.
564    pub fn new(namespace: Resource, state: impl Into<String>) -> Self {
565        BindRequest {
566            namespace,
567            state: state.into(),
568        }
569    }
570}
571
572/// Where to send the admin next.
573#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
574#[serde(rename_all = "camelCase", tag = "type")]
575#[non_exhaustive]
576pub enum BindStep {
577    /// Open this URL in the admin's browser (App install, OAuth consent).
578    Redirect {
579        /// The URL.
580        url: String,
581    },
582}
583
584/// The forge's redirect back to the bridge after a bind.
585#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
586#[serde(rename_all = "camelCase")]
587#[non_exhaustive]
588pub struct BindCallback {
589    /// The callback's query parameters, as received.
590    pub params: BTreeMap<String, String>,
591    /// The nonce the caller issued for this bind, looked up from its store.
592    /// The adapter compares it in constant time; the caller consumes it
593    /// whatever the outcome, so it is single-use.
594    pub expected_state: String,
595    /// The namespace the bind was started for. An install on any other owner
596    /// is refused.
597    pub expected_namespace: Resource,
598}
599
600impl BindCallback {
601    /// A callback for `expected_namespace`, with the issued nonce.
602    pub fn new(
603        params: BTreeMap<String, String>,
604        expected_state: impl Into<String>,
605        expected_namespace: Resource,
606    ) -> Self {
607        BindCallback {
608            params,
609            expected_state: expected_state.into(),
610            expected_namespace,
611        }
612    }
613}
614
615/// A completed bind.
616#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
617#[serde(rename_all = "camelCase")]
618#[non_exhaustive]
619pub struct NamespaceBinding {
620    /// The namespace, with owner id, kind and installation filled in.
621    pub namespace: Namespace,
622    /// Permissions the adapter needs that the installation does not grant
623    /// (an owner who declined an upgrade). Empty when fully capable.
624    pub missing_permissions: Vec<String>,
625    /// What the namespace can do, as found while binding (a probe of the
626    /// forge's plan, say). Persist it: the adapter's copy is in memory.
627    #[serde(default, skip_serializing_if = "Option::is_none")]
628    pub capabilities: Option<Capabilities>,
629}
630
631impl NamespaceBinding {
632    /// A binding, with the permissions the installation lacks.
633    pub fn new(namespace: Namespace, missing_permissions: Vec<String>) -> Self {
634        NamespaceBinding {
635            namespace,
636            missing_permissions,
637            capabilities: None,
638        }
639    }
640
641    /// Attach the capabilities found while binding.
642    pub fn with_capabilities(mut self, capabilities: Capabilities) -> Self {
643        self.capabilities = Some(capabilities);
644        self
645    }
646}
647
648/// Where a member goes to link their account.
649///
650/// `Debug` is hand-written: `device_code` redeems the member's authorisation
651/// once they approve, so it must not reach a log.
652#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
653#[serde(rename_all = "camelCase", tag = "type")]
654#[non_exhaustive]
655pub enum LinkStep {
656    /// OAuth device flow: show `user_code` and `verification_uri`; the
657    /// bridge polls with `device_code`.
658    DeviceCode {
659        /// Opaque handle the bridge polls with. Keep it server-side: it is
660        /// what redeems the member's authorisation.
661        device_code: String,
662        /// Short code the member types in.
663        user_code: String,
664        /// Where they type it.
665        verification_uri: String,
666        /// Seconds until the codes expire.
667        expires_in: u64,
668        /// Minimum seconds between polls.
669        interval: u64,
670    },
671    /// Open this URL (authorisation-code flows).
672    Redirect {
673        /// The URL.
674        url: String,
675    },
676}
677
678impl fmt::Debug for LinkStep {
679    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
680        match self {
681            LinkStep::DeviceCode {
682                user_code,
683                verification_uri,
684                expires_in,
685                interval,
686                ..
687            } => f
688                .debug_struct("DeviceCode")
689                .field("device_code", &"<redacted>")
690                .field("user_code", user_code)
691                .field("verification_uri", verification_uri)
692                .field("expires_in", expires_in)
693                .field("interval", interval)
694                .finish(),
695            LinkStep::Redirect { url } => f.debug_struct("Redirect").field("url", url).finish(),
696        }
697    }
698}
699
700/// Completion input for a link. `Debug` redacts the device code, as for
701/// [`LinkStep`].
702#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
703#[serde(rename_all = "camelCase", tag = "type")]
704#[non_exhaustive]
705pub enum LinkCallback {
706    /// Poll a device flow to completion.
707    DeviceCode {
708        /// From [`LinkStep::DeviceCode`].
709        device_code: String,
710        /// From [`LinkStep::DeviceCode`].
711        interval: u64,
712        /// From [`LinkStep::DeviceCode`]; polling stops at this deadline.
713        expires_in: u64,
714    },
715    /// An authorisation-code redirect. Build it with
716    /// [`LinkCallback::redirect`].
717    #[non_exhaustive]
718    Redirect {
719        /// Query parameters received.
720        params: BTreeMap<String, String>,
721        /// The member (DID) the caller started this link for, from its own
722        /// session — never from the redirect. An adapter whose `state` is
723        /// bound to the member checks it, so a link started by one person
724        /// cannot be completed into another's session (login CSRF).
725        #[serde(default, skip_serializing_if = "Option::is_none")]
726        member: Option<String>,
727    },
728}
729
730impl fmt::Debug for LinkCallback {
731    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
732        match self {
733            LinkCallback::DeviceCode {
734                interval,
735                expires_in,
736                ..
737            } => f
738                .debug_struct("DeviceCode")
739                .field("device_code", &"<redacted>")
740                .field("interval", interval)
741                .field("expires_in", expires_in)
742                .finish(),
743            LinkCallback::Redirect { params, member } => f
744                .debug_struct("Redirect")
745                .field("params", &params.keys().collect::<Vec<_>>())
746                .field("member", member)
747                .finish(),
748        }
749    }
750}
751
752impl LinkCallback {
753    /// An authorisation-code redirect for `member`, the DID the caller
754    /// passed to [`crate::Forge::begin_account_link`].
755    pub fn redirect(params: BTreeMap<String, String>, member: impl Into<String>) -> LinkCallback {
756        LinkCallback::Redirect {
757            params,
758            member: Some(member.into()),
759        }
760    }
761
762    /// The callback that polls the device flow `step` started. `None` for a
763    /// step that is not a device flow.
764    pub fn from_device_step(step: &LinkStep) -> Option<LinkCallback> {
765        match step {
766            LinkStep::DeviceCode {
767                device_code,
768                interval,
769                expires_in,
770                ..
771            } => Some(LinkCallback::DeviceCode {
772                device_code: device_code.clone(),
773                interval: *interval,
774                expires_in: *expires_in,
775            }),
776            LinkStep::Redirect { .. } => None,
777        }
778    }
779}