DEV Community

Trkfpn392751
Trkfpn392751

Posted on

Passwordless Tenant Sign-In — Retiring Magic Links Without Replaying Phone Codes

A delivery retry must never become another successful authentication. For a property management app moving away from a managed provider, that constraint should decide the design before the choice of a passwordless API. TL;DR: keep account identity stable, make phone-code redemption atomic, and separate message delivery from session creation. An existing Node.js app can keep its application boundary while those responsibilities move behind it. No password storage is required for that design, but verification records and sessions still need protection.

Consider a production-readiness exercise, not an account of an actual outage. A tenant requests a phone code for an existing property portal account. The delivery worker retries a message; the tenant submits the code twice while an old email magic link is still available. The exercise passes only if the code can authorize one session issuance, the repeated request cannot authorize another, and the email flow cannot attach a different account to the same tenant. Those are proposed acceptance conditions, not measured results.

Stop duplicate grants.

The lesson is about security state during a cutover. A queue acknowledgement describes work delivery. It doesn't establish that a person has authenticated.

What should a passwordless magic link API preserve when moving to phone codes?

Start with the application account identifier. In this design, a tenant account named tenant_demo_42 belongs to a synthetic property record named building_demo_7. Neither identifier is a phone number. Both are example data. Changing the authentication mechanism should not silently change the account or its property permissions. Require an authenticated enrollment or a separately reviewed recovery process before binding a new phone number to that account; possession of an arbitrary number is insufficient evidence of an existing tenancy.

This is also where the apparent simplicity of a magic-link sign-in API needs qualification. Removing passwords removes the application's password database from the design. It doesn't remove account recovery, session management, automated abuse, or the need to verify that a contact method belongs to the intended account. OWASP's Authentication Cheat Sheet treats authentication, sensitive account changes, and session handling as related security concerns. Use those concerns as the review boundary.

Keep authorization separate. A successful phone challenge should identify the account; the property application must still decide which lease or maintenance request that account may access. Otherwise a migration intended to replace login can quietly rewrite access rules.

The invariant belongs at redemption

Model a challenge as a record with an account binding, a purpose, an expiry, an attempt budget, and a consumed state. The proposed invariant is narrow: one valid challenge may authorize at most one session issuance. Check all of those conditions in the same atomic operation that consumes the challenge and records the session grant. Two concurrent requests must not both observe an unused record and proceed independently.

A particularly awkward trap is the interval between marking a code consumed and committing the session. If the process exits in that interval, the tenant may lose a valid attempt without receiving access. Reversing the order creates a different problem: a session can exist while the code remains redeemable. The proposed design puts both durable changes in one transaction. That's a storage requirement, not something a retry wrapper can supply.

Delivery has a different contract. A worker retry should refer to the same delivery intent and challenge. If the product supports resending or replacing a code, specify whether the old challenge remains valid; don't let that policy emerge accidentally from queue behavior. An explicit replacement policy is easier to test than two independently valid challenges whose relationship exists only in the interface.

For code handling, use a cryptographically secure generator and protect stored verification material. A short numeric code has a small search space, so a plain fast hash is not an adequate defense against offline guessing of leaked records. A keyed verifier with its key held separately is one possible design; online attempt limits remain necessary. Never put a raw code in an application log.

Choose the boundary by the security work it leaves behind

There are three useful implementation boundaries to compare. Retaining managed verification leaves more of the challenge lifecycle with an external service, while the application still owns its account mapping and authorization. Buying message transport while owning verification moves expiry, attempt counting, concurrency control, and redemption into the application. Operating both verification and transport adds delivery operations to that workload. These are responsibility choices, not product rankings.

For this migration, write down who owns each durable state transition before selecting an API. An attractive send-and-check interface can conceal a difficult cutover if its identifiers become the application's account identifiers. Conversely, owning the verifier makes the transaction boundary explicit but gives the team more security-sensitive code to maintain. The right comparison includes recovery support, abuse response, deployment procedures, and who can investigate a failed login without seeing a code.

The trade-off is explicit: owning redemption gives the team control over the transaction boundary, but it also makes that team responsible for enforcing the invariant during every deployment. Don't make a price comparison the deciding argument. Estimate message volume, repeated requests, retained operational data, and engineering time as planning inputs. A smaller integration surface can be valuable, but it isn't evidence that account enrollment or recovery is safe.

Put the preventative path behind an atomic contract

The following Go example is an application-side contract sketch, not an SDK or a complete verifier. Its store must atomically validate the account binding, login purpose, expiry, attempt budget, and keyed code verifier; then consume the challenge and persist a unique session grant. Rejected attempts must update the appropriate counters safely as well. The interface makes that obligation visible, but an implementation must actually enforce it.

package authentication

import (
    "context"
    "errors"
    "time"
)

var ErrVerification = errors.New("verification unsuccessful")

type SessionGrant struct {
    AccountID string
    SessionID string
}

type ChallengeStore interface {
    // RedeemLogin atomically consumes a valid challenge and stores its grant.
    // It rejects expired, exhausted, consumed, or incorrectly bound challenges.
    RedeemLogin(context.Context, string, string, string, time.Time) (SessionGrant, error)
}

type Verifier struct {
    Store ChallengeStore
}

func (v Verifier) Verify(
    ctx context.Context, accountID, challengeID, code string,
) (SessionGrant, error) {
    if accountID == "" || challengeID == "" || code == "" {
        return SessionGrant{}, ErrVerification
    }
    grant, err := v.Store.RedeemLogin(
        ctx, accountID, challengeID, code, time.Now().UTC(),
    )
    if err != nil {
        return SessionGrant{}, ErrVerification
    }
    return grant, nil
}
Enter fullscreen mode Exit fullscreen mode

The account identifier must come from the server's enrollment or challenge context, not an unchecked client assertion. The returned session identifier represents a stored grant; the HTTP layer still needs to deliver the session securely. Keep internal failure categories for operations while returning a generic verification failure externally, consistent with OWASP's guidance on avoiding authentication responses that expose account information. Don't log the function arguments.

Notice the remaining trade-off: a successful commit followed by a lost response leaves the client uncertain. This sketch rejects a replay. It doesn't implement recovery of the original response. If response recovery is required, design a separate, securely bound idempotency mechanism that returns the original result without authorizing a new session. Merely accepting the code again breaks the invariant.

Rehearse the cutover before accepting tenant traffic

Use synthetic accounts and explicit acceptance tests:

  • Submit one challenge concurrently from 2 requests and require at most 1 session issuance.
  • Repeat a consumed code, then exercise expiry and an exhausted attempt budget.
  • Exercise a delayed delivery, a transaction failure, and a response lost after commit.

These are test inputs to build, not claims about an existing implementation.

For the migration itself, test the overlap between the old email flow and the new phone flow against the same internal account. Specify which outstanding challenges remain acceptable at each deployment stage. A rollback must preserve consumed states and attempt counters; restoring an older application version should not resurrect a credential. Keep the cutover scope small enough that the team can inspect its results before expanding access.

The runbook should distinguish delivery delay, verification rejection, and session issuance failure. Record counts and latency at those boundaries, with internal reason categories for expiry, replay, and attempt exhaustion. Correlate events using opaque identifiers and restrict access to authentication telemetry. Avoid raw phone numbers, codes, and session credentials in routine logs. Alert thresholds should come from the application's observed traffic and service objectives, rather than numbers copied from an unrelated system.

This advice has limits. It doesn't establish that phone possession is sufficient assurance for changing a payout destination or performing another sensitive action; those operations need their own risk review and may require reauthentication or stronger factors. If the migration keeps magic links as the primary login method, the phone enrollment work may be unnecessary, though the same replay and account-binding questions still deserve testing.

For the property portal, accept the cutover when account bindings, concurrent redemption, recovery, and rollback behave as specified. The useful definition of simple passwordless authentication is a small set of security obligations the team can explain and operate.

References

The source below supports the authentication review criteria. The transaction contract and cutover tests above are proposed engineering choices.

Sources

Top comments (0)