Functional Weave
Code in Rust

auth.account-link

Decide whether an OAuth sign-in signs in, links to an existing account by verified email, creates one, or is refused.

1.0.0 · published 2026-10-10 by charlie · Anterra

Pinned by 16 tests, run in TypeScript, Python and Rust.

What it does

Someone has just come back from "Sign in with Google" (auth.oauth-sign-in did the OAuth part). Is this a returning user, someone who already has a password account under the same email, or someone new? `decideAccountLink` answers that from what the app already holds, without touching the database: the app looks up the rows, calls it, and carries out the decision.

const decision = decideAccountLink(
  { provider: "google", subject: claims.sub, email: claims.email, emailVerified: claims.email_verified === true },
  await db.accountsByEmail(claims.email),          // candidates; extra rows are fine
  await db.links({ provider: "google", subject: claims.sub, orAccountsOf: claims.email }),
);
switch (decision.action) {
  case "sign-in": /* start a session for decision.accountId */ break;
  case "link":    /* insert (provider, subject, decision.accountId), then sign in */ break;
  case "create":  /* create an account for decision.email, link it, sign in */ break;
  case "require-verification": /* send an email.token link to decision.email first */ break;
  case "refuse":  /* explain decision.reason; sign in another way */ break;
}

For example

  • decide_account_link(provider google, subject 1078, email new-address@Example.COM, email verified false, accounts ×1, links ×1) → action sign-in, reason existing_link, account id acc_1, email new-address@example.com a provider identity already linked signs in to its account, whatever the email now says
  • decide_account_link(provider github, subject 583231, email ada@example.com, email verified true, , links ×1) → action refuse, reason linked_account_missing, account id acc_deleted, email ada@example.com a link to an account that no longer exists is refused, naming the account
  • decide_account_link(provider google, subject 1078, email ada@EXAMPLE.com , email verified true, accounts ×2, ) → action link, reason verified_email_match, account id acc_1, email ada@example.com a verified provider email matching one verified account links to it (domain case ignored)

The function

The same function in TypeScript, Python and Rust, pinned by the same tests. Pick your language; the choice follows you around the registry.

pub fn decide_account_link(identity: &OAuthIdentity, accounts: &[LinkAccount], links: &[IdentityLink]) -> LinkDecision
identityOAuthIdentitywho the provider says signed in: provider, subject (its user id), email and whether it verified that email
accountsLinkAccount[]the app's existing accounts that might share the email (passing more is fine; they are filtered)
linksIdentityLink[]the stored provider identities: at least those for this provider and subject, and those of the matching accounts
returnsLinkDecisionwhat to do, why, and the account and normalised email it applies to

The types it declares, generated into your project

/// The identity an OAuth / OpenID Connect provider returned.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OAuthIdentity {
    /// google, github, microsoft ...: your name for the provider
    pub provider: String,
    /// the provider's stable user id (OIDC sub); never the email
    pub subject: String,
    /// the email the provider gave, or null when it gave none
    pub email: Option<String>,
    /// the provider's own email_verified claim (GitHub: the verified flag of the primary email)
    pub email_verified: bool,
}

/// An existing account in the app.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LinkAccount {
    pub id: String,
    pub email: String,
    /// whether the app itself has proved the account holder owns this address
    pub email_verified: bool,
}

/// A stored link from a provider identity to an account.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IdentityLink {
    pub provider: String,
    pub subject: String,
    pub account_id: String,
}

// LinkAction is a string in Rust, one of: "sign-in", "link", "create", "refuse", "require-verification".
// Parameters take it as &str and results hold it as String.

// LinkReason is a string in Rust, one of: "existing_link", "linked_account_missing", "verified_email_match", "new_account", "no_email", "unverified_email", "unverified_new_email", "account_email_unverified", "provider_already_linked", "ambiguous_email".
// Parameters take it as &str and results hold it as String.

/// The decision, with the account and email it applies to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LinkDecision {
    pub action: String,
    pub reason: String,
    /// the account to sign in to or link to; null for create, refuse and a new-address verification
    pub account_id: Option<String>,
    /// the identity's email after auth.normalise-email, when it has one
    pub email: Option<String>,
}

Your code names it in one line, in the file that uses it

fune!(auth.account-link@^1);  // then call decide_account_link(…)
impl/rust.rs · 133 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

use super::auth_normalise_email::normalise_email;  ← from auth.normalise-email ^1.0.0 · built alongside by fune
use super::funejson::Value;  ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one

fn decision(action: &str, reason: &str, account_id: Option<&str>, email: Option<&str>) -> LinkDecision {
    LinkDecision {
        action: action.to_string(),
        reason: reason.to_string(),
        account_id: account_id.map(|s| s.to_string()),
        email: email.map(|s| s.to_string()),
    }
}

/// What to do with an OAuth sign-in, given the accounts and links the app
/// already has. The rules run in a fixed order, so the same inputs always get
/// the same answer; see the README for the attack each rule stops.
///
/// # Panics
/// Panics when the identity's provider or subject is empty.
pub fn decide_account_link(identity: &OAuthIdentity, accounts: &[LinkAccount], links: &[IdentityLink]) -> LinkDecision {
    if identity.provider.is_empty() {
        panic!("identity.provider must be a non-empty string");
    }
    if identity.subject.is_empty() {
        panic!("identity.subject must be a non-empty string");
    }
    let email = identity.email.as_deref().and_then(normalise_email);
    let email_ref = email.as_deref();

    // The provider's subject is the identity; once linked, the email no longer matters.
    if let Some(existing) = links.iter().find(|l| l.provider == identity.provider && l.subject == identity.subject) {
        if accounts.iter().any(|a| a.id == existing.account_id) {
            return decision("sign-in", "existing_link", Some(&existing.account_id), email_ref);
        }
        return decision("refuse", "linked_account_missing", Some(&existing.account_id), email_ref);
    }

    let wanted = match email_ref {
        Some(e) => e,
        None => return decision("refuse", "no_email", None, None),
    };

    let matches: Vec<&LinkAccount> = accounts
        .iter()
        .filter(|a| normalise_email(&a.email).as_deref() == Some(wanted))
        .collect();
    if matches.is_empty() {
        if identity.email_verified {
            return decision("create", "new_account", None, email_ref);
        }
        return decision("require-verification", "unverified_new_email", None, email_ref);
    }
    if matches.len() > 1 {
        return decision("refuse", "ambiguous_email", None, email_ref);
    }
    let account = matches[0];
    if !identity.email_verified {
        return decision("refuse", "unverified_email", Some(&account.id), email_ref);
    }
    if links
        .iter()
        .any(|l| l.account_id == account.id && l.provider == identity.provider && l.subject != identity.subject)
    {
        return decision("refuse", "provider_already_linked", Some(&account.id), email_ref);
    }
    if !account.email_verified {
        return decision("require-verification", "account_email_unverified", Some(&account.id), email_ref);
    }
    decision("link", "verified_email_match", Some(&account.id), email_ref)
}

fn text(value: &Value, what: &str) -> String {
    match value {
        Value::Str(s) => s.clone(),
        _ => panic!("{} must be a string", what),
    }
}

fn flag(value: &Value, what: &str) -> bool {
    match value {
        Value::Bool(b) => *b,
        _ => panic!("{} must be true or false", what),
    }
}

fn list<'a>(value: &'a Value, what: &str) -> &'a [Value] {
    match value {
        Value::Arr(items) => items,
        _ => panic!("{} must be a list", what),
    }
}

pub fn link_decision_to_value(d: &LinkDecision) -> Value {
    let opt = |o: &Option<String>| match o {
        Some(s) => Value::str(s),
        None => Value::Null,
    };
    Value::obj(vec![
        ("action", Value::str(&d.action)),
        ("reason", Value::str(&d.reason)),
        ("accountId", opt(&d.account_id)),
        ("email", opt(&d.email)),
    ])
}

pub fn fune_vector(args: &[Value]) -> Value {
    let id = &args[0];
    let identity = OAuthIdentity {
        provider: text(id.get("provider"), "identity.provider"),
        subject: text(id.get("subject"), "identity.subject"),
        email: match id.get("email") {
            Value::Null => None,
            other => Some(text(other, "identity.email")),
        },
        email_verified: flag(id.get("emailVerified"), "identity.emailVerified"),
    };
    let accounts: Vec<LinkAccount> = list(&args[1], "accounts")
        .iter()
        .map(|a| LinkAccount {
            id: text(a.get("id"), "account.id"),
            email: text(a.get("email"), "account.email"),
            email_verified: flag(a.get("emailVerified"), "account.emailVerified"),
        })
        .collect();
    let links: Vec<IdentityLink> = list(&args[2], "links")
        .iter()
        .map(|l| IdentityLink {
            provider: text(l.get("provider"), "link.provider"),
            subject: text(l.get("subject"), "link.subject"),
            account_id: text(l.get("accountId"), "link.accountId"),
        })
        .collect();
    link_decision_to_value(&decide_account_link(&identity, &accounts, &links))
}

Install

fune build

With that line in your source, in a Rust project (language rust in fune.project), fune build resolves it and its 1 dependency, pins them in fune.lock, downloads only the Rust package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. A crate’s build.rs runs it before every compile. Or pin a range in fune.project and build in one step:

fune add auth.account-link
Download for Rust auth.account-link-1.0.0-rust.fune · 21,251 bytes sha256 241735c0a04c3fc1bf2c87d316c63a09063c9b9271ffe2d58781580f0116003d

The manifest, vectors and README with only the Rust implementation. Install it without the registry with fune add ./auth.account-link-1.0.0-rust.fune, or fetch it from a terminal with fune pull auth.account-link@1.0.0:rust.

The whole function, every language, is one file too: auth.account-link-1.0.0.fune, 26,957 bytes, sha256 73063e2a2e9507671d7f756e520ea2980ae297d3132bc314fcfd47fd3df172e6. It installs into a project of any language.

Customise it in your app

The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.

before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.

// fune: before auth.account-link

after — your function gets the result and the arguments, and returns the final result.

// fune: after auth.account-link

replace — inside this capability’s code only, calls to a dependency go to your function, with the same signature. Other capabilities that use it are unaffected; write in * to replace it everywhere.

// fune: replace auth.normalise-email in auth.account-link

step — your function runs at a numbered point inside the function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show auth.account-link --steps.

// fune: step auth.account-link after <n|label>

Tests

A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.

CaseArgumentsExpected
a provider identity already linked signs in to its account, whatever the email now says provider google, subject 1078, email new-address@Example.COM, email verified false, accounts ×1, links ×1 → action sign-in, reason existing_link, account id acc_1, email new-address@example.com
a link to an account that no longer exists is refused, naming the account provider github, subject 583231, email ada@example.com, email verified true, , links ×1 → action refuse, reason linked_account_missing, account id acc_deleted, email ada@example.com
a verified provider email matching one verified account links to it (domain case ignored) provider google, subject 1078, email ada@EXAMPLE.com , email verified true, accounts ×2, → action link, reason verified_email_match, account id acc_1, email ada@example.com
a verified email that matches no account creates one provider microsoft, subject 00000000-0000-0000-66f3-3332eca7ea81, email grace@example.org, email verified true, accounts ×1, → action create, reason new_account, account id —, email grace@example.org
an unverified email that matches no account must be verified by the app before creating provider github, subject 99, email grace@example.org, email verified false, , → action require-verification, reason unverified_new_email, account id —, email grace@example.org
an unverified provider email never links to an existing account provider github, subject 99, email ada@example.com, email verified false, accounts ×1, → action refuse, reason unverified_email, account id acc_1, email ada@example.com
no email from the provider is refused provider github, subject 99, email —, email verified false, accounts ×1, → action refuse, reason no_email, account id —, email —
an email that is not an address counts as none provider github, subject 99, email not an email, email verified true, , → action refuse, reason no_email, account id —, email —
the account already holds another identity from the same provider provider google, subject 2001, email ada@example.com, email verified true, accounts ×1, links ×2 → action refuse, reason provider_already_linked, account id acc_1, email ada@example.com
another provider already linked to the account does not stop linking this one provider google, subject 1078, email ada@example.com, email verified true, accounts ×1, links ×1 → action link, reason verified_email_match, account id acc_1, email ada@example.com
Show the other 6 tests
CaseArgumentsExpected
an account whose own email was never verified must be verified first (pre-account hijacking) provider google, subject 1078, email ada@example.com, email verified true, accounts ×1, → action require-verification, reason account_email_unverified, account id acc_1, email ada@example.com
two accounts sharing the email is ambiguous and refused provider google, subject 1078, email ada@example.com, email verified true, accounts ×2, → action refuse, reason ambiguous_email, account id —, email ada@example.com
the local part keeps its case, as auth.normalise-email stores it, so Ada@ is another address provider google, subject 1078, email Ada@example.com, email verified true, accounts ×1, → action create, reason new_account, account id —, email Ada@example.com
a link with the same subject from another provider is not this identity provider google, subject 583231, email ada@example.com, email verified true, accounts ×1, links ×1 → action link, reason verified_email_match, account id acc_1, email ada@example.com
an empty provider is an error provider , subject 1078, email ada@example.com, email verified true, , → error: identity.provider must be a non-empty string
an empty subject is an error provider google, subject , email ada@example.com, email verified true, , → error: identity.subject must be a non-empty string

Verification

Verified by the operator, not the sandbox 16 test vectors declared; none run by the registry.

Verified locally by the registry's operator, not by the sandbox. This version was published with FUNE_VERIFY_MODE=inline-dev (the operator's import of the first-party registry, or a development server): the server validated the package - its manifest, signatures, imports, safety lint and test rules - but the registry did not run its test vectors in its sandbox. The operator runs them with `fune verify --all` before importing.

Signed by the registry with key fw-9dc887227da47575 (ed25519), over its integrity and this report's digest. The full report · JSON

More from the author

## The rules, in order

1. **An empty provider or subject throws.** They are the identity; nothing else can be decided without them. 2. **An existing link wins** (`sign-in`, `existing_link`). The provider's subject is the stable identity, so a user who changed their email at Google still lands in their account. If the linked account is not among `accounts`, the answer is `refuse` / `linked_account_missing` (with the account id, so the app can clean the link up) rather than creating a second account behind the user's back. 3. **No email, no matching** (`refuse`, `no_email`). Without an address there is nothing safe to match on. A provider that returns none (GitHub with a private email) has to be asked for the `user:email` scope. 4. Emails are compared after `auth.normalise-email` on both sides: trimmed, domain lower-cased, **local part as typed**, exactly as that capability stores them. `Ada@example.com` and `ada@example.com` are two addresses; if your app folds the local part, store and pass it folded. 5. **No account has the email**: a verified provider email creates one (`create`, `new_account`); an unverified one needs the app to prove the address first (`require-verification`, `unverified_new_email`), with its own email token (auth.email-token), so the account is never created for an address its creator does not hold. 6. **Two or more accounts have the email** (`refuse`, `ambiguous_email`). The function will not pick one: merging accounts is a support decision. 7. **One account has the email**, and then: - the provider did not verify the email: `refuse`, `unverified_email`. **Account takeover**: some providers let anyone type any address, so linking on it would hand the account to whoever typed it. - the account already has a link to the same provider with another subject: `refuse`, `provider_already_linked`. A second Google account claiming the same address is a conflict for the user to sort out, never a silent second link. - the account's own email was never verified by the app: `require-verification`, `account_email_unverified`. **Pre-account hijacking**: an attacker registers victim@example.com with a password and waits; when the victim later signs in with Google, linking would leave the attacker's password working on the victim's account. Have the account's address verified (or reset its password) before linking. - otherwise `link`, `verified_email_match`.

`accountId` is set for `sign-in`, `link` and every decision about one existing account (so the app can log or explain it), and null for `create`, `no_email`, `ambiguous_email` and a new address awaiting verification. `email` is the identity's normalised email whenever it has one.

## What it does not do

It stores nothing and sends nothing. It does not merge accounts, and it does not decide whether your app allows sign-up at all: treat `create` as "create if sign-up is open".

Files

PathBytes
README.md4,176
impl/python.py2,613
impl/rust.rs4,931
impl/typescript.ts2,845
vectors.json6,074