selfRetrofit function

Future<AtClient> selfRetrofit({
  1. required AtAuthSession session,
  2. required AtClientPreference preference,
  3. required String appName,
  4. required String deviceName,
  5. required Map<String, String> namespaces,
  6. Duration? apkamKeysExpiryDuration,
  7. SigningAlgoType? signingAlgo,
  8. required AtClientStorage storage,
  9. AtLookUp? atLookUp,
  10. required AtLookUpFactory lookUps,
  11. required SecondaryAddressFinder secondaryAddressFinder,
  12. Duration connectBudget = AtConnection.defaultBudget,
})

Runs the whole PQ self-retrofit and hands back a client running under the NEW enrollment, which the caller owns.

The sequence: submit an AtSelfEnrollmentRequest authenticated as the legacy session (auto-approved, no OTP; idempotent — a keyfile that already carries an enrollment of the requested algorithm reuses it, nothing is minted); check the keyfile now authenticates as the new enrollment id; then open the client for the new id, whose own connection is the first to authenticate as it.

The enrollment never changes under a live client on this path. The switched-to client is a NEW instance under the (atSign, enrollmentId) cache key, so every per-client cache (secret sharing, key-package registration) starts fresh for the new identity and a legacy client is not mutated. ⚠️ That is not an invariant of the SDK: AtClientImpl retrofits itself at start-up through retrofitIdentity and DOES mutate in place, which is safe only there, inside _init, before the client has been filed in the instance map or handed to any caller.

A legacy client that is live is left running: it keeps authenticating until the new enrollment first does, which is when the atServer revokes it as superseded (a fully privileged predecessor keeps its life). So a failure before that point leaves the legacy client fully usable, and nothing after it does. The new client opens on storage. To retrofit over the legacy client's own store, stop that client first, which releases its claim on a store the caller supplied without closedByClient: true, then call forgetPrincipal() on the store, and pass it here: a store refuses a client acting for another principal than the one that held it last, and the retrofit's enrollment is one.

atLookUp serves the submission and the client, for a caller that holds a connection. Between the two its authenticator is cleared and its connection closed, so the next login on it is the client's, as the new enrollment; a command needing authentication meanwhile fails rather than logging in as the legacy one. With none the submission authenticates a connection of its own from the session's keys and closes it. See Atsign.open for connectBudget.

A fully privileged retrofit also runs the signing-root step in-flow. The retrofit is auto-approved by the atServer with no approver client in the loop, so nothing conveys the root to it the way an approve does — its only routes are to mint one, when the atSign publishes none, or to be given the private by another holder on the every-start pull. The mint half has to happen here: the switched-to enrollment mints and publishes the root, files both halves in the same keyfile, and anchors itself. Privilege is read off the atServer's enrollment record, never the namespaces this call requested, and a scoped retrofit skips the step entirely. A root-step failure does not fail the retrofit — the enrollment is live and usable without it, and re-running selfRetrofit (idempotent per keyfile) retries the step.

signingAlgo is the authentication key's algorithm — the APKAM keypair the new enrollment proves possession of on a connection, not the key it signs envelopes with. The name is the wire field's (EnrollParams.signingAlgo); renaming it is a multi-repo seam against a released atServer, so the name stays and this says what it does.

A per-operation parameter rather than a preference. When the caller names none, AtClientPreference.authenticationKeyAlgorithm decides: rsa2048 under PqPosture.legacy, mldsa65 under PqPosture.pqReady and PqPosture.pqActive.

⚠️ The preference's value, not the posture's. An app may set authenticationKeyAlgorithm beside a posture, and the preference's value is then what this client mints under.

A fully privileged rsa2048 retrofit still files an ML-DSA-65 pq_signing_root: the root is the atSign's, not this enrollment's, and gating it on a per-enrollment algorithm choice would let the first privileged retrofit decide whether the atSign ever gets a root at all. "No ML-DSA anywhere" is true only of the enrollment's own keys.

The new enrollment's initial KEM is the first of AtClientPreference.keyEstablishmentAlgorithms — its key package rides the enroll:request, which carries one key. Any further algorithm the list names is minted, filed and advertised by KeyPackageMinting at the retrofitted client's first startup, through the enroll:update the new enrollment sends for itself.

Implementation

Future<AtClient> selfRetrofit({
  required AtAuthSession session,
  required AtClientPreference preference,
  required String appName,
  required String deviceName,
  required Map<String, String> namespaces,
  Duration? apkamKeysExpiryDuration,
  SigningAlgoType? signingAlgo,
  required AtClientStorage storage,
  AtLookUp? atLookUp,
  required AtLookUpFactory lookUps,
  required SecondaryAddressFinder secondaryAddressFinder,
  Duration connectBudget = AtConnection.defaultBudget,
}) async {
  final newSession = await retrofitIdentity(
    session: session,
    preference: preference,
    appName: appName,
    deviceName: deviceName,
    namespaces: namespaces,
    apkamKeysExpiryDuration: apkamKeysExpiryDuration,
    signingAlgo: signingAlgo,
    atLookUp: atLookUp,
    lookUps: lookUps,
    secondaryAddressFinder: secondaryAddressFinder,
  );
  // NOTE: nothing logs in on [atLookUp] as the legacy enrollment again, and
  // the client never runs on the connection the submission logged in as it.
  atLookUp?.authenticator = null;
  await atLookUp?.close();

  preference
    ..rootDomain = session.rootDomain.rootDomain
    ..rootPort = session.rootDomain.rootPort;
  final client = await Atsign(session.atSign).open(
      keys: session.atKeysIo,
      preference: preference,
      namespace: newSession.namespace,
      storage: storage,
      atLookUp: atLookUp,
      lookUps: lookUps,
      secondaryAddressFinder: secondaryAddressFinder,
      connectBudget: connectBudget);

  try {
    final granted = (await EnrollmentServiceImpl(client, AtEnrollment.create())
            .fetchEnrollmentRequests())
        .where((e) => e.enrollmentId == newSession.enrollmentId)
        .firstOrNull
        ?.namespace;
    if (EnrollmentServiceImpl.isFullyPrivileged(granted)) {
      await PqSigningRoot(client, keysIo: session.atKeysIo)
          .mintIfAbsent(isFullyPrivileged: true);
    }
  } catch (e) {
    _logger.warning('The retrofit of ${session.atSign} succeeded but its '
        'signing-root step did not; rerunning selfRetrofit retries it: $e');
  }

  return client;
}