From d6c96fe1a16ec62df3908ab18cdc2c40b28968e1 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Fri, 6 Nov 2026 15:54:56 +0000 Subject: [PATCH 001/146] Estate-rule sim: contribution-credit arm (E7) Linear per-person credit with a per-person cap, one standard for all including a Meta-sized contributor, measured against the existing tally and half-influence cap across contributor-share levels and splitting k=2/10/100. Credit is not vote weight; analysis only. Co-Authored-By: Claude Sonnet 5.5 --- .../2026-11-05-estate-rule-sim/REPORT.md | 11 +++ .../2026-11-05-estate-rule-sim/SPEC.md | 17 +++++ .../2026-11-05-estate-rule-sim/estatesim.py | 48 +++++++++++++ .../2026-11-05-estate-rule-sim/results.md | 68 +++++++++++++++++++ .../2026-11-05-estate-rule-sim/run.py | 68 +++++++++++++++++++ .../test_estatesim.py | 61 +++++++++++++++++ 6 files changed, 273 insertions(+) diff --git a/docs/research/2026-11-05-estate-rule-sim/REPORT.md b/docs/research/2026-11-05-estate-rule-sim/REPORT.md index 1813dcb..d773d4a 100644 --- a/docs/research/2026-11-05-estate-rule-sim/REPORT.md +++ b/docs/research/2026-11-05-estate-rule-sim/REPORT.md @@ -54,6 +54,17 @@ Static weight analysis, not a motion simulation: it measures weight share, not P Limits specific to E6: the roll, the Pareto scale, b and unit are assumptions; the buyer joins as an additional patron and buys once (no repeated purchase or liquidation); decisiveness is estate-level only, not council-level (prior section 10 shows weight share is not decisiveness); the best split is a grid maximum, a lower bound; hours play no part in a purchase scenario because estate weights are fixed and the buyer sits in Patrons, so an hours buyer (a Member who is paid or who farms hours) is untested and the conversion of hours into weight is just a per-estate parameter whose gaming is not modeled. +## E7: contribution-weighted arm (SPEC section 5d) + +Static weight analysis, not a motion simulation, and not a proposal: credit does not become vote weight here. Credit is linear in receipts (hours or credited changes), tallied per person, weight = min(credit, per-person cap), one function for a Meta-sized contributor and an ordinary member alike. Tally and half cap are E6's. Contributor share phi is the fraction of the Members estate's total raw credit; roll 15 and 150 ordinary members, 40 seeds, both estate-weight sets. + +- **The half cap binds only when Members are the only live estate, and then it is a step at phi = .5.** All four estates live: 0 binding in every cell. Members + Minds live: 0 (the Members estate carries at most half the council, so the strict cap is never reached). Members alone: 0 for phi <= .4, and for phi >= .5 with no credit cap 1.000, because a contributor at exactly half of the credit has exactly half the estate (the cap is "strictly below"). The rate does not rise past phi = .5 because the cap binds as a yes/no, not by degree. +- **A per-person credit cap moves that step, it does not remove it.** Members alone, phi >= .5, rate of binding at 100x / 20x / 5x the ordinary median credit: 0.438 / 0.075 / 0.000 (pooled over both rolls and weights, 320 trials each). The bound is the cap against the size of the ordinary roll: 5x the median holds a contributor under half of a 15-member estate, which says the cap is doing the work the half cap would do, at the price of flattening every member above 5x median. +- **Splitting evades the half cap in every case it needed to act.** Members alone, over the whole sweep, k = 2, 10, 100: the joint share reaches .5 in 5,942 cases and in 5,942 no single identity binds (1.000). Uncapped linear credit makes splitting weight-neutral (multiplier 1.00) but still evades the per-identity half cap. With a per-person credit cap splitting also multiplies weight: at phi .9, k = 10, the multiplier is 3.58 at 100x, 9.66 at 20x, 10.00 at 5x (cap bites hardest on the single identity); k = 100: 6.50 / 21.58 / 59.10. +- **Falsifiers (SPEC 5d).** (1) A credit cap contains phi .9 with half cap never binding: only at 5x median; false at 100x and 20x. (2) Credit cap survives splitting at multiplier <= 1.1 at k = 10: false in every capped row (1.23 at phi .25 with a 100x cap up to 10.00). (3) Half cap evaded under splitting: true in all 5,942. + +Limits: Pareto credit curve and its scale, the multiples of median, the Members placement, and the rolls are placeholders. A person-level cap needs an identity oracle (as E6); credit tied to merged receipts could provide one, which this sim does not test. Receipts are not audited for farming or purchase (hours-farming is the E6 hours gap, still unanalysed). Ordinary members' own credit is capped too, which matters only at 5x. + ## Robustness (E5, E5b) The sign of the PS effect holds across Users appeal 0.4/0.9/1.4, Users turnout .05/.10/.30 and Minds shared taste .3/.9/1.5. Its size scales with Users appeal loading (-0.025 at .4, -0.067 at 1.4): the rule helps in proportion to how appeal-driven the Users estate is, while its merit loss does not go away (MT gap -0.101 at .4 vs -0.063 at 1.4). If Users are not appeal-driven the rule is nearly all cost. diff --git a/docs/research/2026-11-05-estate-rule-sim/SPEC.md b/docs/research/2026-11-05-estate-rule-sim/SPEC.md index 687a6db..bb39cd8 100644 --- a/docs/research/2026-11-05-estate-rule-sim/SPEC.md +++ b/docs/research/2026-11-05-estate-rule-sim/SPEC.md @@ -111,6 +111,22 @@ Serves the purchased-stake brief (operator relayed: Patron vote power is logarit **Falsifiers fixed in advance.** (1) Working hypothesis "logarithmic weight bounds buyout power": refuted if a one-million-euro buyer's within-estate share s exceeds 1/2 at the harness's own roll, or if splitting multiplies weight by more than 2 at any k. (2) The half-influence cap is "binding" in a (cell, seed) iff x >= .5; the rate over the sweep is reported per live-estate scenario. (3) The cap is "evaded" by splitting iff the joint share is >= .5 while no single identity's share is. +## 5d. Contribution credit (revision 6, written before its results) + +Serves `heimdall-body:follow_up:chat-mind-20261106T134754647Z-t14`. A static weight analysis like 5c, for a contribution-weighted arm. It informs Meta's later call and decides nothing: credit does not become vote weight, here or in any rule above. + +**Credit.** A person's credit is the sum of their receipts (hours, or credited changes counted in the same linear unit), tallied per person. Weight is `min(credit, cap)`: linear, one function for every person, so a Meta-sized contributor is the same row of the same table as an ordinary member, with no exemption and no separate schedule. The per-person cap is a multiple of the ordinary members' median credit, swept over none, 100x, 20x, 5x (assumptions, not rulings). + +**Contributor share.** The contributor holds a fraction phi of the estate's total raw credit (before capping), swept over .05 to .9. This is the "Meta-sized" axis. Placement is the Members estate (where 5c's hours channel lives), a PLACEHOLDER. + +**Electorate.** 15 (the harness roll) and 150 ordinary members with Pareto(1.16) credit from 10 (prior section 4's contribution curve; the scale is mine), 40 seeds each, estate weights and live-estate scenarios as 5c. + +**Same tally, same half cap.** `council_share` and `influence_cap` of 5c, unchanged: binds iff council weight share x >= .5. + +**Splitting.** The contributor's credit split evenly over k = 2, 10, 100 identities. Reported per identity (binds), jointly (joint share >= .5) and as evasion (joint >= .5 with no identity binding), plus the weight multiplier against k = 1. With no credit cap, linear credit makes splitting weight-neutral; with a per-person cap it is not. + +**Falsifiers fixed in advance.** (1) Per-person credit cap "contains" a large contributor if the half cap never binds at phi .9 with a cap in force in the Members-alone scenario. (2) Credit cap "survives splitting" if the weight multiplier at k = 10 is at most 1.1 with a cap in force. (3) The half cap is evaded under splitting if joint x >= .5 with no identity binding. + ## 6. Strategic and adaptive agents A fraction ρ = .25 of ballot holders and of absent undelegated roll members are strategic. Each is myopic about the motion at hand and best-responds to everyone else's current ballots over three rounds in random order: @@ -136,6 +152,7 @@ Paired across rules: one set of random draws per motion feeds all rules (common - **E3f copy-the-ballot:** section 5b. - **E4 appeal attraction:** β sweep at α = 1.5, c = .2. - **E6 purchased stake:** section 5c. b x unit x Patrons roll x amount x estate weights x live-estate scenario, 40 seeds; splitting k sweep; candidate defences. +- **E7 contribution credit:** section 5d. phi x credit cap x roll x weights x live set x seeds; splitting k. - **E5 robustness:** Users appeal loading b ∈ {.4, .9, 1.4}; Users base turnout {.05, .10, .30}; Minds ICC (s_Minds ∈ {.3, .9, 1.5}). This is the check on the assumed parameters in section 4. ## 8. Pre-registered falsifiers diff --git a/docs/research/2026-11-05-estate-rule-sim/estatesim.py b/docs/research/2026-11-05-estate-rule-sim/estatesim.py index d4693bc..f0e5946 100644 --- a/docs/research/2026-11-05-estate-rule-sim/estatesim.py +++ b/docs/research/2026-11-05-estate-rule-sim/estatesim.py @@ -580,3 +580,51 @@ def buyer_runs(amount, n, seeds, W, live, overrides=()): wb = stake_weight("Patrons", euros=amount, overrides=overrides) return [influence_cap(wb, sum(stake_weight("Patrons", euros=x, overrides=overrides) for x in stake_ladder(n, s)), W, ESTATES.index("Patrons"), live) for s in range(seeds)] + + +# ---------------------------------------------------------------- contribution credit (SPEC section 5d) +# +# Credit is tallied per person from receipts (hours or credited changes, one linear unit each) and capped per +# person. The tally and the half-influence cap are the ones above (council_share, influence_cap). Credit is +# measured here as a candidate weight source only; this module never turns it into a vote. + +CREDIT_SEED = 20261106 +CREDIT_ESTATE = "Members" # PLACEHOLDER: where contribution credit would weigh; the hours channel above lives here + + +def credit_weight(credit, cap=None): + """One person's weight from credit: linear in receipts, min(credit, cap). One function for every person, + a Meta-sized contributor included; there is no per-person exemption or schedule.""" + return credit if cap is None else min(credit, cap) + + +def credit_ladder(n, s): + """Seed s's n ordinary members' credit (hours): Pareto(PARETO_ALPHA) from PARETO_XM (prior section 4's + contribution curve; the scale is PLACEHOLDER).""" + return pareto_ladder(n, random.Random(CREDIT_SEED + 1000 * n + s)) + + +def credit_cap_value(ladder, mult): + """Per-person cap as a multiple of the ordinary members' median credit (None = no cap).""" + if mult is None: + return None + xs = sorted(ladder) + return mult * xs[len(xs) // 2] + + +def credit_run(phi, n, s, W, live, cap_mult=None, k=1): + """Half-cap result for a contributor holding fraction `phi` of the estate's TOTAL raw credit, against n + ordinary members (seed s), the credit split evenly over k identities. Returns dict: the usual + influence_cap fields for ONE identity (`one`), the joint share (`joint_x`), `evaded` iff the joint + council share is >= HALF while no identity's is, and `w_total`.""" + e = ESTATES.index(CREDIT_ESTATE) + lad = credit_ladder(n, s) + cap = credit_cap_value(lad, cap_mult) + rest = sum(credit_weight(x, cap) for x in lad) + big = phi / (1 - phi) * sum(lad) + wi = credit_weight(big / k, cap) + tot = k * wi + one = influence_cap(wi, rest + tot - wi, W, e, live) + joint = council_share(tot, rest, W, e, live)[1] + return dict(one=one, joint_x=joint, binds=one["binds"], joint_binds=joint >= HALF - EPS, + evaded=joint >= HALF - EPS and not one["binds"], w_total=tot, rest=rest, cap=cap) diff --git a/docs/research/2026-11-05-estate-rule-sim/results.md b/docs/research/2026-11-05-estate-rule-sim/results.md index cd14773..67e1039 100644 --- a/docs/research/2026-11-05-estate-rule-sim/results.md +++ b/docs/research/2026-11-05-estate-rule-sim/results.md @@ -879,6 +879,74 @@ Best multiplier at 1,000,000 EUR by log base and unit (b rows, unit columns): |---|---|---|---|---|---| | weight | 0.70 | 1.00 | 2.00 | 3.00 | 4.00 | +## E7 contribution-weighted arm: linear credit, per-person cap, the half-influence cap (SPEC section 5d) + +Static weight analysis. One contributor holds a fraction phi of the Members estate's total raw credit (receipts: hours or credited changes, one linear unit); 15 and 150 ordinary members hold Pareto(1.16) credit from 10, 40 seeds each. Weight = min(credit, per-person cap), the same function for the contributor and everyone else. The tally and the half cap are E6's: council share x = W x s over the live estates; the cap binds iff x >= .5. Credit is not vote weight anywhere in this module; this table only says how often the half cap would have to act. + +**Half cap binds, all four estates: fraction of (weights x roll x seed) by contributor share phi (rows) and per-person credit cap (columns); one identity, k = 1** + +| phi | none | 100x median | 20x median | 5x median | +|---|---|---|---|---| +| 0.05 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.1 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.25 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.4 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.5 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.6 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.75 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.9 | 0.000 | 0.000 | 0.000 | 0.000 | + +**Half cap binds, Members + Minds: fraction of (weights x roll x seed) by contributor share phi (rows) and per-person credit cap (columns); one identity, k = 1** + +| phi | none | 100x median | 20x median | 5x median | +|---|---|---|---|---| +| 0.05 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.1 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.25 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.4 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.5 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.6 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.75 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.9 | 0.000 | 0.000 | 0.000 | 0.000 | + +**Half cap binds, Members alone: fraction of (weights x roll x seed) by contributor share phi (rows) and per-person credit cap (columns); one identity, k = 1** + +| phi | none | 100x median | 20x median | 5x median | +|---|---|---|---|---| +| 0.05 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.1 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.25 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.4 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.5 | 1.000 | 0.438 | 0.075 | 0.000 | +| 0.6 | 1.000 | 0.438 | 0.075 | 0.000 | +| 0.75 | 1.000 | 0.438 | 0.075 | 0.000 | +| 0.9 | 1.000 | 0.438 | 0.075 | 0.000 | + +**Splitting: the contributor's credit split evenly over k identities. Members alone, equal weights, roll 15, mean over seeds. binds = the half cap acts on an identity; joint >= .5 = the combined share would have needed cutting; evaded = joint >= .5 and no identity binds; weight x = total weight / weight at k = 1** + +| phi | cap | k=1: binds / joint>=.5 / evaded / weight x | k=2: binds / joint>=.5 / evaded / weight x | k=10: binds / joint>=.5 / evaded / weight x | k=100: binds / joint>=.5 / evaded / weight x | +|---|---|---|---|---|---| +| 0.25 | none | 0.00 / 0.00 / 0.00 / 1.00 | 0.00 / 0.00 / 0.00 / 1.00 | 0.00 / 0.00 / 0.00 / 1.00 | 0.00 / 0.00 / 0.00 / 1.00 | +| 0.25 | 100x median | 0.00 / 0.00 / 0.00 / 1.00 | 0.00 / 0.03 / 0.03 / 1.03 | 0.00 / 0.03 / 0.03 / 1.23 | 0.00 / 0.03 / 0.03 / 1.25 | +| 0.25 | 20x median | 0.00 / 0.00 / 0.00 / 1.00 | 0.00 / 0.03 / 0.03 / 1.12 | 0.00 / 0.07 / 0.07 / 1.43 | 0.00 / 0.07 / 0.07 / 2.55 | +| 0.25 | 5x median | 0.00 / 0.00 / 0.00 / 1.00 | 0.00 / 0.00 / 0.00 / 1.75 | 0.00 / 0.12 / 0.12 / 2.87 | 0.00 / 0.12 / 0.12 / 5.46 | +| 0.5 | none | 1.00 / 1.00 / 0.00 / 1.00 | 0.00 / 1.00 / 1.00 / 1.00 | 0.00 / 1.00 / 1.00 / 1.00 | 0.00 / 1.00 / 1.00 / 1.00 | +| 0.5 | 100x median | 0.88 / 0.88 / 0.00 / 1.00 | 0.00 / 1.00 / 1.00 / 1.08 | 0.00 / 1.00 / 1.00 / 1.31 | 0.00 / 1.00 / 1.00 / 1.88 | +| 0.5 | 20x median | 0.15 / 0.15 / 0.00 / 1.00 | 0.00 / 0.80 / 0.80 / 1.50 | 0.00 / 1.00 / 1.00 / 2.35 | 0.00 / 1.00 / 1.00 / 4.73 | +| 0.5 | 5x median | 0.00 / 0.00 / 0.00 / 1.00 | 0.00 / 0.00 / 0.00 / 2.00 | 0.00 / 1.00 / 1.00 / 6.41 | 0.00 / 1.00 / 1.00 / 11.38 | +| 0.9 | none | 1.00 / 1.00 / 0.00 / 1.00 | 0.00 / 1.00 / 1.00 / 1.00 | 0.00 / 1.00 / 1.00 / 1.00 | 0.00 / 1.00 / 1.00 / 1.00 | +| 0.9 | 100x median | 0.88 / 0.88 / 0.00 / 1.00 | 0.00 / 1.00 / 1.00 / 1.93 | 0.00 / 1.00 / 1.00 / 3.58 | 0.00 / 1.00 / 1.00 / 6.50 | +| 0.9 | 20x median | 0.15 / 0.15 / 0.00 / 1.00 | 0.00 / 0.80 / 0.80 / 2.00 | 0.00 / 1.00 / 1.00 / 9.66 | 0.00 / 1.00 / 1.00 / 21.58 | +| 0.9 | 5x median | 0.00 / 0.00 / 0.00 / 1.00 | 0.00 / 0.00 / 0.00 / 2.00 | 0.00 / 1.00 / 1.00 / 10.00 | 0.00 / 1.00 / 1.00 / 59.10 | + +Evasion rate over the sweep (phi x cap x k in 2, 10, 100 x live set x weights x roll x seed), cases where the joint share needed cutting: + +| live estates | joint share >= .5 (k > 1) | of which no identity binds (evaded) | +|---|---|---| +| all four estates | 0 | 0 | +| Members + Minds | 0 | 0 | +| Members alone | 5942 | 5942 (1.000) | + ## Claim tally over all cells (SPEC section 8) supported 0, fails 2, undecided 233, n/a 0 diff --git a/docs/research/2026-11-05-estate-rule-sim/run.py b/docs/research/2026-11-05-estate-rule-sim/run.py index cc3755f..e0162c9 100644 --- a/docs/research/2026-11-05-estate-rule-sim/run.py +++ b/docs/research/2026-11-05-estate-rule-sim/run.py @@ -353,6 +353,73 @@ def stake_section(quick): return L +MEMBERS = E.ESTATES.index(E.CREDIT_ESTATE) +CLIVE = {"all four estates": (0, 1, 2, 3), "Members + Minds": (0, MEMBERS), "Members alone": (MEMBERS,)} +CREDIT_CAPS = (None, 100.0, 20.0, 5.0) # per-person credit cap, multiples of the ordinary members' median credit + + +def _capname(m): + return "none" if m is None else f"{m:g}x median" + + +def credit_section(quick): + """E7 contribution-weighted arm (SPEC section 5d). Pure functions of fixed seeds; no wall clock.""" + seeds = 4 if quick else 40 + phis = (.1, .5, .9) if quick else (.05, .1, .25, .4, .5, .6, .75, .9) + rolls = (E.ROLL["Members"],) if quick else (E.ROLL["Members"], 150) + ks = (1, 2, 10, 100) + L = ["## E7 contribution-weighted arm: linear credit, per-person cap, the half-influence cap (SPEC section 5d)", "", + f"Static weight analysis. One contributor holds a fraction phi of the {E.CREDIT_ESTATE} estate's total raw credit (receipts: hours or credited " + f"changes, one linear unit); {rolls[0]}" + (f" and {rolls[1]}" if len(rolls) > 1 else "") + + f" ordinary members hold Pareto({E.PARETO_ALPHA}) credit from {E.PARETO_XM:.0f}, {seeds} seeds each. Weight = min(credit, per-person cap), the same function " + "for the contributor and everyone else. The tally and the half cap are E6's: council share x = W x s over the live estates; the cap binds iff x >= .5. " + "Credit is not vote weight anywhere in this module; this table only says how often the half cap would have to act.", ""] + for ln, live in CLIVE.items(): + L += [f"**Half cap binds, {ln}: fraction of (weights x roll x seed) by contributor share phi (rows) and per-person credit cap (columns); one identity, k = 1**", "", + "| phi | " + " | ".join(_capname(m) for m in CREDIT_CAPS) + " |", "|---|" + "---|" * len(CREDIT_CAPS)] + for phi in phis: + cols = [] + for m in CREDIT_CAPS: + hit = tot = 0 + for W in E.WEIGHTS.values(): + for n in rolls: + for s in range(seeds): + hit += E.credit_run(phi, n, s, W, live, m)["binds"] + tot += 1 + cols.append(f"{hit / tot:.3f}") + L.append(f"| {phi:g} | " + " | ".join(cols) + " |") + L.append("") + L += ["**Splitting: the contributor's credit split evenly over k identities. Members alone, equal weights, roll " + f"{rolls[0]}, mean over seeds. binds = the half cap acts on an identity; joint >= .5 = the combined share would have needed cutting; " + "evaded = joint >= .5 and no identity binds; weight x = total weight / weight at k = 1**", "", + "| phi | cap | " + " | ".join(f"k={k}: binds / joint>=.5 / evaded / weight x" for k in ks) + " |", "|---|---|" + "---|" * len(ks)] + W = E.WEIGHTS["equal"] + for phi in (.25, .5, .9): + for m in CREDIT_CAPS: + cols = [] + for k in ks: + rs = [E.credit_run(phi, rolls[0], s, W, (MEMBERS,), m, k) for s in range(seeds)] + base = [E.credit_run(phi, rolls[0], s, W, (MEMBERS,), m, 1)["w_total"] for s in range(seeds)] + cols.append(f"{sum(r['binds'] for r in rs) / seeds:.2f} / {sum(r['joint_binds'] for r in rs) / seeds:.2f} / " + f"{sum(r['evaded'] for r in rs) / seeds:.2f} / {sum(r['w_total'] / b for r, b in zip(rs, base)) / seeds:.2f}") + L.append(f"| {phi:g} | {_capname(m)} | " + " | ".join(cols) + " |") + L += ["", "Evasion rate over the sweep (phi x cap x k in 2, 10, 100 x live set x weights x roll x seed), cases where the joint share needed cutting:", "", + "| live estates | joint share >= .5 (k > 1) | of which no identity binds (evaded) |", "|---|---|---|"] + for ln, live in CLIVE.items(): + j = ev = 0 + for phi in phis: + for m in CREDIT_CAPS: + for k in ks[1:]: + for Wt in E.WEIGHTS.values(): + for n in rolls: + for s in range(seeds): + r = E.credit_run(phi, n, s, Wt, live, m, k) + j += r["joint_binds"] + ev += r["evaded"] + L.append(f"| {ln} | {j} | {ev} ({ev / j:.3f}) |" if j else f"| {ln} | 0 | 0 |") + return L + [""] + + def main(argv=None): ap = argparse.ArgumentParser() ap.add_argument("--quick", action="store_true") @@ -388,6 +455,7 @@ def main(argv=None): L += [f"### {title.split(' ')[0]} / {name}", ""] + rule_table(r) + [""] L += [pair_line(r), "", "PS by category threshold:", ""] + percat_table(r) + [""] L += stake_section(a.quick) + L += credit_section(a.quick) L += ["## Claim tally over all cells (SPEC section 8)", "", f"supported {tally['supported']}, fails {tally['fails']}, undecided {tally['undecided']}, n/a {tally['n/a']}", ""] if failing: diff --git a/docs/research/2026-11-05-estate-rule-sim/test_estatesim.py b/docs/research/2026-11-05-estate-rule-sim/test_estatesim.py index c4e9dd0..de9defb 100644 --- a/docs/research/2026-11-05-estate-rule-sim/test_estatesim.py +++ b/docs/research/2026-11-05-estate-rule-sim/test_estatesim.py @@ -420,6 +420,67 @@ class StakeTests(unittest.TestCase): self.assertTrue(all(x >= E.PARETO_XM for x in a)) +PINNED_CREDIT_BINDS = {None: 320, 100.0: 140, 20.0: 24, 5.0: 0} # of 320 (phi .5, .9 x roll 15, 150 x 40 seeds x 2 weights) + + +class CreditTests(unittest.TestCase): + """SPEC section 5d: contribution credit, per-person cap, the half-influence cap.""" + M = E.ESTATES.index("Members") + W = E.WEIGHTS["equal"] + ALONE = (1,) + + def test_one_standard_for_everyone(self): + for c in (3.0, 40.0, 1e6): # a Meta-sized credit gets no schedule of its own + self.assertEqual(E.credit_weight(c), c) + self.assertEqual(E.credit_weight(c, 25.0), min(c, 25.0)) + + def test_cap_is_per_person_and_a_multiple_of_the_ordinary_median(self): + lad = E.credit_ladder(15, 0) + self.assertIsNone(E.credit_cap_value(lad, None)) + self.assertEqual(E.credit_cap_value(lad, 20.0), 20.0 * sorted(lad)[7]) + + def test_contributor_holds_phi_of_raw_credit(self): + r = E.credit_run(.5, 15, 3, self.W, self.ALONE) + self.assertAlmostEqual(r["w_total"], r["rest"]) # uncapped: phi .5 means equal to everyone else + self.assertAlmostEqual(r["one"]["s"], .5) + + def test_half_cap_binds_at_half_of_credit_in_a_lone_estate_not_below(self): + self.assertTrue(E.credit_run(.5, 15, 0, self.W, self.ALONE)["binds"]) + self.assertFalse(E.credit_run(.49, 15, 0, self.W, self.ALONE)["binds"]) + + def test_other_estates_dilute_the_contributor_below_the_half_cap(self): + self.assertFalse(E.credit_run(.9, 15, 0, self.W, (0, 1, 2, 3))["binds"]) + + def test_credit_cap_reduces_weight_and_can_release_the_half_cap(self): + un = E.credit_run(.9, 15, 0, self.W, self.ALONE) + cp = E.credit_run(.9, 15, 0, self.W, self.ALONE, cap_mult=5.0) + self.assertTrue(un["binds"]) + self.assertFalse(cp["binds"]) + self.assertLess(cp["w_total"], un["w_total"]) + + def test_splitting_is_weight_neutral_without_a_cap_and_gains_with_one(self): + base = E.credit_run(.9, 15, 0, self.W, self.ALONE)["w_total"] + self.assertAlmostEqual(E.credit_run(.9, 15, 0, self.W, self.ALONE, k=10)["w_total"], base) + c1 = E.credit_run(.9, 15, 0, self.W, self.ALONE, cap_mult=20.0)["w_total"] + self.assertGreater(E.credit_run(.9, 15, 0, self.W, self.ALONE, cap_mult=20.0, k=10)["w_total"], c1) + + def test_per_identity_half_cap_is_evaded_by_splitting_credit(self): + r1 = E.credit_run(.9, 15, 0, self.W, self.ALONE, k=1) + r2 = E.credit_run(.9, 15, 0, self.W, self.ALONE, k=2) + self.assertTrue(r1["binds"] and not r1["evaded"]) + self.assertFalse(r2["binds"]) + self.assertTrue(r2["joint_binds"] and r2["evaded"]) + + def test_headline_numbers_are_pinned(self): + hit = {m: sum(E.credit_run(phi, n, s, w, self.ALONE, m)["binds"] for phi in (.5, .9) for n in (15, 150) + for s in range(40) for w in E.WEIGHTS.values()) for m in (None, 100.0, 20.0, 5.0)} + self.assertEqual(hit, PINNED_CREDIT_BINDS) + + def test_deterministic(self): + a, b = E.credit_run(.5, 15, 2, self.W, self.ALONE, 20.0, 10), E.credit_run(.5, 15, 2, self.W, self.ALONE, 20.0, 10) + self.assertEqual(a, b) + + class StrategyTests(unittest.TestCase): def test_deviation_never_makes_agent_worse_off(self): rng = random.Random(3) From 8abd9129176dda3c2dc29701a5737bf39caa6c22 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Fri, 6 Nov 2026 21:26:13 +0000 Subject: [PATCH 002/146] docs: guest accounts design (role field, invite, grants, leave and erase) Co-Authored-By: Claude Sonnet 5.5 --- docs/guest-accounts.md | 255 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 255 insertions(+) create mode 100644 docs/guest-accounts.md diff --git a/docs/guest-accounts.md b/docs/guest-accounts.md new file mode 100644 index 0000000..3044056 --- /dev/null +++ b/docs/guest-accounts.md @@ -0,0 +1,255 @@ +# Guest accounts + +Status: **design, nothing implemented.** Written for `eureka-body:follow_up:bifrost-guest-accounts` under +`eureka-body:ruling:guest-arrival-bifrost` (Meta: guests need no Matrix account of their own; they get a GameCult +account through Bifrost with a guest role, and move to member, user or patron on the same account seamlessly), +building on `eureka-body:ruling:bifrost-owns-accounts-invite-only`. I could not `view` either ruling from the +Heimdall mind, so their text here is the follow-up brief's wording; check it against the rulings. First guest: +sletz (Faust developer). Aqua decides on `#aquasynth` access, so the first grant list is hers to name. + +Read at Bifrost `bf8ff62` (`src/Bifrost.Web/Domain/BifrostModels.cs`, `Features/Membership`, `Features/Heimdall`, +`Features/Oidc`, `Features/Motions`, `Features/ConceptVotes`, `Pages/App/Members`) and Heimdall `575be9c` +(`src/app-profiles.ts`, `docs/app-profiles/bifrost.md`). + +## The shape in one paragraph + +A guest is a `UserAccount` like any other: same `Id` (the OIDC `sub`), same `NormalizedBifrostIdentity` (the Matrix +localpart, minted once). What is new is one field, `Membership.Role`, with four values: `guest`, `user`, `patron`, +`member`. Role is the single place that says what an account may do. A role change rewrites that field and writes a +receipt; it never creates a second account, never re-mints the identity, so chat history, grants and the Matrix +user stay attached. + +## What exists today + +- `UserAccount.Id` is the OIDC subject; `NormalizedBifrostIdentity` is `preferred_username` and, through MAS, the + Matrix localpart (`docs/oidc-issuer.md`). `HeimdallAccountId` is only an authenticator handle. +- `Membership.Status` is `Authenticated | PendingApproval | Active | Suspended`. `CurrentBifrostActor.IsActiveMember` + (`Status == Active`) is the one test behind `/App`, bridge transport (`BridgeActionService` l.492), motion votes + (`EffectiveVotingWeight`, `MotionGovernanceService` l.72), concept votes (`VoterIdentity.For`, member versus + account class) and the OIDC authorize, token and userinfo endpoints (`OidcEndpoints` l.50, l.131) and the + back-channel logout reconciler. +- `MemberRole` (`StandardMember`, `Producer`, `Maintainer`, `LedgerReviewer`, `PlatformAdmin`) are capability + roles a member holds in addition. They are not the new field. +- Invites are `MembershipInvitation`, keyed by GitHub login (`MembershipSynchronizationService` l.37, + `Members/Index.cshtml.cs` l.34). A guest may have no GitHub login at all. +- Heimdall sign-in (`HeimdallAuthService.StartAsync`) with `requireMemberAccess = false` already creates an + identity-only account at `Authenticated`; with member access it creates `Active`. +- Nothing exists for room grants, leaving, erasing, or any "estate" in code (estates are rulings and research + only, `docs/charter-amendment-proposal.md`). + +## Decision: one role field, status stays lifecycle + +Two authorities cannot both say "may this account vote". Today `Status == Active` says it. The cut: + +- `Membership.Status` keeps its meaning as lifecycle of the account: may it hold a session. Add `Left` and + `Erased` (see Leave and erase). `Active` means admitted and in good standing, for any role. +- `Membership.Role` (new, non-null, enum `AccountRole`) decides rights. `IsActiveMember` becomes + `Status == Active && Role == Member`, and is the only place that expression exists. Every current + `IsActiveMember` caller keeps working unchanged and a guest fails all of them without a per-site edit. +- OIDC authorize, token, userinfo and the logout reconciler change their test from "Active member" to + "`Status == Active`" (any role), so a guest, user or patron can hold a chat session and a member demoted to + `Suspended` still loses it. This is the one behavioural change outside new code, and it is the line to review. +- Backfill: `Active` becomes `member`; `Authenticated` and `PendingApproval` become `user`; an account with a + current `Patron` tier snapshot and not `Active` becomes `patron`. Nobody starts as `guest`. + +Naming risk: `MemberRole` already exists for capability roles. If the collision bites, call the new field +`Class`; the published field below follows whichever name is chosen. I use `Role` because that is the ruling's word. + +Alternative considered and not recommended: a boolean `IsGuest` on `Membership` with guests kept at `Active`. +Smaller to land, but `user` and `patron` stay implicit in status and tier snapshots, so "the role field Personas +read" would have to be derived in three places. One stored field is one reading. + +## Invite shape + +New table `GuestInvitation`, separate from `MembershipInvitation` (which is GitHub-login-keyed and leads to +approval, not to a guest). Fields: + +| field | rule | +|---|---| +| `Id` | Guid. | +| `TokenHash` | SHA-256 of a 256-bit random token. The token itself is shown to the issuer once, as a link, and never stored. | +| `IntendedIdentity` | the localpart the issuer picks (for example `sletz`), validated by `BifrostIdentityService.NormalizeIdentity`, reserved while the invite is open. Minted once on accept; a collision gets the usual `-2` suffix. | +| `Label` | free note for the issuer ("sletz, Faust developer"). | +| `RoomGrants` | the rooms to grant on accept (below), as a list of grant requests. | +| `IssuedByUserAccountId`, `IssuedAtUtc` | issuer must be a platform admin (`CanManageMembership`), as for member invites. | +| `ExpiresAtUtc` | default seven days. | +| `AcceptedByUserAccountId`, `AcceptedAtUtc`, `RevokedAtUtc` | one use; revoke before accept ends it. | + +The link is a bearer: whoever signs in first with it is the guest. That is the cost of not needing sletz's +provider handle in advance, and it is why the token is single-use and short-lived and why the accept is shown +to the issuer. Recommended over binding the invite to a provider handle (which needs a Discord or Google id the +issuer may not have). The issuer may still restrict `ExpectedProvider`; open fork, see Questions. + +## Sign-in via Heimdall + +1. Guest opens `/invite/guest/`. Bifrost checks hash, expiry, unused, unrevoked, and stores the invite id in + the existing Heimdall attempt (`HeimdallAuthService` protects attempt state with the data protector). +2. Bifrost starts Heimdall sign-in with `requireMemberAccess = false` (identity only, no entitlement policy). + Heimdall authenticates; it does not issue the identity (`docs/jurisdiction-map.md`). +3. On the callback, in one transaction: resolve `HeimdallAccountId`. + - No account: create `UserAccount` with `IntendedIdentity`, `Membership { Status = Active, Role = Guest }`, write + the room grants, mark the invite accepted, write the receipt. + - Account exists: the invite never lowers an account. A `member`, `patron` or `user` keeps their role; the grants + are added and the invite is spent. If the existing account is `Left` or `Erased`, refuse. +4. Bifrost issues its own cookie as for any account. From there the guest reaches chat through the one OIDC client. + +Gap, drift found while reading: Bifrost's `AllowedProviders` is `discord, patreon, twitch` +(`HeimdallAuthService.AllowedProviders`), but Heimdall's `bifrost` app profile allows `discord, patreon, google` +(`app-profiles.ts`, `bifrostProfile`). Twitch cannot start in Heimdall and Google is refused by Bifrost. A guest with +neither Discord, Patreon nor a Google account cannot sign in, and GitHub is not a Heimdall sign-in provider for +this app. Which provider sletz uses is unknown to me; align the two lists before the first invite. + +## Guest rights + +A guest may: sign in, hold a Bifrost cookie, hold a chat session through OIDC, see and edit their own profile +(`MemberProfile`), be in the rooms granted to them, and leave or erase (below). A guest may not: + +- vote on motions: `EffectiveVotingWeight` is `0` for any role but `member` (today it is `Max(1, ...)` for + `Active`, which would give every guest weight 1; that line must read the role); +- cast concept-mill appraisals: `VoterIdentity.For` returns no voter for a guest (not even `VoterClass.Account`); +- appear on any estate roll or in any tally. The charter proposal snapshots each estate's roll at notice (A6); + `guest` is on no roll, so a guest cannot be counted, cannot make a quorum, and reclassifying a guest after a + snapshot changes nothing for that snapshot; +- use bridge transport, claim or log work, earn points or ledger credit, or hold tier snapshots (those make them + a patron or member by changing role, not by decorating a guest); +- hold a `MemberRole` or any of the `CanManage*` flags; +- invite anyone. + +This list is enforced by role in one place (`CurrentBifrostActor`), not by a check at each use. + +## Per-room grants + +Rooms are Matrix rooms in chat, not Bifrost objects. Bifrost owns the decision, so a grant is Bifrost state: + +`GuestRoomGrant { Id, UserAccountId, RoomRef, GrantedByUserAccountId, GrantedAtUtc, ExpiresAtUtc?, RevokedAtUtc? }` + +`RoomRef` is a room id or alias as chat names it. Aqua's `#aquasynth` is the first one if she says yes. + +The grant has to reach Matrix to mean anything. Today Bifrost's only Matrix writer is the Persona mouth, with +per-Persona access tokens (`docs/bridge.md`), and it holds no admin or invite right. + +Gap (largest in this doc): something must perform "invite this Matrix user to that room" on a grant and "remove +them" on revoke or expiry. Candidates: a Bifrost-owned bot user that is a member with invite power in the granted +rooms (reuses the Matrix client API, no Synapse admin credential), or the Synapse admin API. I recommend the bot +user: narrower credential, and the room's power levels remain the real gate. Until it exists, the grant is a +record, a human invites the guest by hand, and the receipt says `delivered_by: manual`. Rooms for guests must be +invite-only; a guest who can reach a public room needs no grant, and that is a chat configuration fact I have not +verified. + +Second gap: a guest has a full Matrix account once MAS provisions the localpart, so Matrix itself will let them +create rooms or DM unless Synapse's room-creation and invite settings (`room_list_publication_rules`, +`allow_public_rooms_*`, a spam-checker or module) say otherwise. These are global in Synapse, not per user, so a +guest limit may have to be power levels in every room they are in. I did not find a per-user switch. + +## Role change on the same account id, with a receipt + +`ChangeRole(accountId, to, actor, reason)` is the only writer of `Membership.Role`. It runs in one transaction: + +1. refuse `Erased` and `Left`; refuse a no-op; +2. write `Role`, and for `member` also set `Status = Active`, `ApprovedAtUtc`, and the default `StandardMember` + capability role (the same effects as `OnPostApproveAsync`); for `patron`, nothing beyond the role (tier + snapshots come from support events as before); +3. write `AccountRoleReceipt { Id, UserAccountId, From, To, ChangedAtUtc, ChangedByUserAccountId, Reason }`; +4. leave `UserAccount.Id`, `NormalizedBifrostIdentity`, `HeimdallAccountId`, grants and profile untouched. + +Who may change: a platform admin (`CanManageMembership`). Promoting to `member` is the existing approve path; +this design routes it through `ChangeRole` so one writer exists. Promoting to `member` also applies whatever the +charter says about joining an estate (not decided; see Questions). Demotion (member to guest) is allowed and +receipted; it also removes the `MemberRole`s and capability flags in the same transaction. + +The receipt is a Postgres row today, like `AuditEvent`. Bifrost's rule is that durable state has a CultCache `.cc` +witness (`docs/jurisdiction-map.md`, Design Rules); the witness is owed (Gaps). + +Seamless means: the guest's session cookie, OIDC subject, Matrix id, display name and room memberships do not +change on promotion. A cookie issued before promotion carries identity claims only, never the role, so it needs +no refresh; the actor is read from the database each request (`CurrentBifrostActorAccessor`). + +## Leave and erase + +Neither exists in Bifrost today. Two different acts: + +**Leave** (guest or any role, self-service): sets `Status = Left`, revokes every grant, and expels the account +from granted rooms through the same effector as grants. The OIDC reconciler already notices a non-`Active` +subject within 30 seconds and logs MAS out, and the token and userinfo endpoints refuse. The account row and +`Id` stay, so a later invite can restore it (a `Left` account re-accepting is a role change from itself, receipted). +Nothing else about the person is deleted by leaving. + +**Erase** (self-service, or admin on request): irreversible. In one transaction: blank `DisplayName`, `AvatarUrl`, +`MemberProfile`, `GitHubLogin`/`GitHubUserId`, clear `HeimdallAccountId` (the authenticator link), set +`Status = Erased`, keep `Id` and `NormalizedBifrostIdentity` as a tombstone so the localpart is never reissued to +someone else (OIDC says it is minted once), keep receipts but with names stripped. The reason to keep a tombstone +row is that receipts and audit events point at the id. + +An erasing guest has no votes, ledger entries or points, because guests cannot create them. A member or patron +who erases does, and those are accounting records: their erase is a separate question (Questions). Guest erase +is the case this design covers. + +Outside Bifrost, erase is incomplete without two effectors: + +- Matrix: Synapse's deactivate-with-erase admin call and MAS deactivation for the user. Federation is disabled in + the chat map (`gamecult-ops/docs/gamecult-chat-map.md`: federation paths 404), which helps: messages are + not copied to other servers. Other members' clients, and any export or training copy, are not reached by an + erase. Whether chat content is training data is `heimdall-body`'s consent rulings (Heimdall PR #6), which already + define exit by redaction; a guest's messages follow whatever that doc says, not this one. +- Heimdall: I found no account-delete or unlink path in Heimdall `src`. Clearing `HeimdallAccountId` on the Bifrost + side leaves the Heimdall account and its provider link alive. Heimdall needs an erase call keyed by the account id + before "erased" is true end to end. + +## What Eureka reads + +Personas read the role, not the account. Do not put it in OIDC: the issuer promises "no membership detail leaves +Bifrost" (`docs/oidc-issuer.md`) and chat does not need it. Publish a typed CultMesh document under the +`gamecult.bifrost.governance` family (the nearest existing schema namespace, `verse-service-contract.md` l.60), id +`gamecult.bifrost.account.v1`, key = account id: + +| field | type | note | +|---|---|---| +| `account_id` | uuid | OIDC `sub`; never changes. | +| `identity` | string | `NormalizedBifrostIdentity`; the Matrix localpart, so Matrix user id is `@:` (server name per MAS config, not verified here). | +| `display_name` | string | blank once erased. | +| `role` | `guest` \| `user` \| `patron` \| `member` | the field Personas read. | +| `status` | `authenticated` \| `pending_approval` \| `active` \| `suspended` \| `left` \| `erased` | | +| `role_since` | UTC ms | from the latest `AccountRoleReceipt`. | +| `rooms` | list of room refs | only for `guest`: the live grants. Others get rooms by estate. | + +A Persona deciding how to treat someone looks up `identity` from the Matrix sender and reads `role`. A sender with +no document is not a Bifrost account (a bridge ghost or an unlinked user) and is `unknown`, never defaulted to +`guest` or `user`. Bifrost does not decide Persona behavior; it states the role. + +No such publisher or witness exists; Bifrost has no `.cc` export for accounts today. + +## Cut sequence (not specs) + +1. `Membership.Role`, backfill, `IsActiveMember` and the OIDC tests moved to the new reading, vote and concept-vote + exclusions, with tests that fail if a guest gets weight or a voter key. +2. `GuestInvitation`, the accept path, the Heimdall provider list aligned. +3. `AccountRoleReceipt` and `ChangeRole`, with `OnPostApproveAsync` routed through it. +4. `GuestRoomGrant` and the Matrix effector. +5. Leave, then erase (Bifrost side), then the Matrix and Heimdall effectors. +6. The account document and its `.cc` witness. + +## Gaps, plainly + +- The Matrix effector for grants, leave and erase does not exist, and no credential for it is provisioned. +- Synapse cannot cap what a guest does per user; room-creation and invite limits are global (unverified: I did not + read the live Synapse config). +- Heimdall has no erase path. Bifrost and Heimdall disagree on provider lists today. +- No `.cc` witness or CultMesh publisher for accounts or receipts. Bifrost's account state is Postgres only. +- Matrix id shape (`@:`) depends on MAS importing `preferred_username` as localpart; the OIDC doc + says so, I did not check the deployed MAS. +- Tie to the answer-collector consent doc (Heimdall PR #6): a guest posting in a room may be posting to a sample + collector. That doc keys on `member_id`, and says a sender with no linked member is dropped. Whether a guest has a + `member_id`, and so whether their answers are collected at all, is not decided here. Default: not collected. +- Erase for member and patron roles (ledger and vote records) is unmapped. + +## Questions for the deciders + +1. **Is `Role` the right name** given `MemberRole`, and is one stored role (this doc) preferred over a boolean + `IsGuest`? Recommendation: stored role. Confidence: medium; the boolean is cheaper if user and patron are not + yet needed. +2. **Bearer link or provider-bound invite?** Recommendation: bearer, single use, seven days, optional + `ExpectedProvider`. Confidence: medium; this is a trust call about how sletz will be sent the link. +3. **Which Heimdall provider will sletz sign in with?** Needed before the lists are aligned. +4. **Do guests get a `member_id` for the answer collector?** Default no. +5. **Does promotion to member join the Members estate immediately**, or does the charter's notice and snapshot + rule apply to the roll? The charter text is a proposal, not in force. From c757acf525da1d60406ba0386f22c36a9f75ba85 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Sat, 7 Nov 2026 18:42:43 +0000 Subject: [PATCH 003/146] Make every cookie host-only: __Host- names, Secure, Path=/, no Domain Session, OAuth correlation, antiforgery, voter and Heimdall attempt cookies all take the __Host- prefix. The prefix forbids a narrower Path, so the voter (was /mill) and attempt (was /auth/heimdall) cookies move to Path=/. Co-Authored-By: Claude Sonnet 5.5 --- .../Features/ConceptVotes/VoterKeyResolver.cs | 5 +- .../Features/Heimdall/HeimdallAuthService.cs | 8 +- .../Features/Shared/BifrostCookies.cs | 17 +++ src/Bifrost.Web/Program.cs | 14 +++ .../Bifrost.Web.Tests/ConceptVotePageTests.cs | 5 +- .../ConceptVoteRateLimitTests.cs | 3 +- .../Bifrost.Web.Tests/CookieHardeningTests.cs | 101 ++++++++++++++++++ .../HeimdallCompletionTests.cs | 18 ++-- .../Support/HeimdallTestKit.cs | 3 +- 9 files changed, 155 insertions(+), 19 deletions(-) create mode 100644 src/Bifrost.Web/Features/Shared/BifrostCookies.cs create mode 100644 tests/Bifrost.Web.Tests/CookieHardeningTests.cs diff --git a/src/Bifrost.Web/Features/ConceptVotes/VoterKeyResolver.cs b/src/Bifrost.Web/Features/ConceptVotes/VoterKeyResolver.cs index ce9fbec..2948700 100644 --- a/src/Bifrost.Web/Features/ConceptVotes/VoterKeyResolver.cs +++ b/src/Bifrost.Web/Features/ConceptVotes/VoterKeyResolver.cs @@ -1,4 +1,5 @@ using System.Security.Cryptography; +using Bifrost.Web.Features.Shared; using Microsoft.AspNetCore.DataProtection; namespace Bifrost.Web.Features.ConceptVotes; @@ -7,8 +8,8 @@ namespace Bifrost.Web.Features.ConceptVotes; // decides the voter key and class. The cookie holds a protected random id, never a count, class or account. public sealed class VoterKeyResolver(IDataProtectionProvider dataProtection) { - public const string CookieName = "bifrost_voter"; - public const string CookiePath = "/mill"; + public const string CookieName = BifrostCookies.Voter; + public const string CookiePath = BifrostCookies.Path; public static readonly TimeSpan CookieLifetime = TimeSpan.FromDays(365); private const string Purpose = "Bifrost.ConceptVotes.DeviceToken.v1"; diff --git a/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs b/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs index 3e0b3a1..7749402 100644 --- a/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs +++ b/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs @@ -446,13 +446,13 @@ public sealed record HeimdallAccount( /// /// The attempt cookies: a ring of fixed names, so the Cookie header a browser sends to -/// /auth/heimdall is bounded by construction (a worst-case attempt is about 2.4 KB; nginx's line limit is 8 KB). +/// every path is bounded by construction (the __Host- prefix forces Path=/; a worst-case attempt is about 2.4 KB, nginx's line limit is 8 KB). /// A start takes a free slot or overwrites the one expiring first; an overwritten attempt finds no cookie and /// is refused. The attempt's nonce lives inside the protected value, never in the cookie name. /// public static class HeimdallAttemptCookie { - public const string Prefix = "bifrost_heimdall_"; + public const string Prefix = BifrostCookies.HeimdallAttemptPrefix; public const int SlotCount = 2; public static readonly TimeSpan Lifetime = TimeSpan.FromMinutes(10); @@ -465,7 +465,7 @@ public static class HeimdallAttemptCookie HttpOnly = true, Secure = true, SameSite = SameSiteMode.Lax, - Path = "/auth/heimdall", + Path = BifrostCookies.Path, MaxAge = Lifetime }; @@ -473,5 +473,5 @@ public static class HeimdallAttemptCookie /// The options a deletion carries: only the attempt cookie's Path, which a cookie is matched on. It carries no /// Max-Age, which would take precedence over the expiry Delete writes and leave the emptied cookie alive. /// - public static CookieOptions DeleteOptions() => new() { Path = "/auth/heimdall" }; + public static CookieOptions DeleteOptions() => new() { Path = BifrostCookies.Path }; } diff --git a/src/Bifrost.Web/Features/Shared/BifrostCookies.cs b/src/Bifrost.Web/Features/Shared/BifrostCookies.cs new file mode 100644 index 0000000..1c099e8 --- /dev/null +++ b/src/Bifrost.Web/Features/Shared/BifrostCookies.cs @@ -0,0 +1,17 @@ +namespace Bifrost.Web.Features.Shared; + +// Every cookie Bifrost sets carries the __Host- prefix: the browser then accepts it only with Secure, Path=/ and no +// Domain, so no sibling subdomain of gamecult.org (the preview host is same-site) can plant or shadow one by setting +// a Domain=gamecult.org cookie of the same name. The prefix forbids a narrower Path, so these all live at Path=/. +public static class BifrostCookies +{ + public const string HostPrefix = "__Host-"; + + public const string Session = HostPrefix + "bifrost_session"; + public const string OAuthCorrelation = HostPrefix + "bifrost_oauth_correlation"; + public const string Antiforgery = HostPrefix + "bifrost_antiforgery"; + public const string Voter = HostPrefix + "bifrost_voter"; + public const string HeimdallAttemptPrefix = HostPrefix + "bifrost_heimdall_"; + + public const string Path = "/"; +} diff --git a/src/Bifrost.Web/Program.cs b/src/Bifrost.Web/Program.cs index d0656d3..c8a524a 100644 --- a/src/Bifrost.Web/Program.cs +++ b/src/Bifrost.Web/Program.cs @@ -76,6 +76,13 @@ builder.Services .AddOptions() .BindConfiguration(ConceptVoteOptions.SectionName); +builder.Services.AddAntiforgery(options => +{ + options.Cookie.Name = BifrostCookies.Antiforgery; + options.Cookie.SecurePolicy = CookieSecurePolicy.Always; + options.Cookie.Path = BifrostCookies.Path; +}); + builder.Services.AddRazorPages(options => { options.Conventions.AuthorizePage("/Membership/Status"); @@ -167,6 +174,10 @@ var authenticationBuilder = builder.Services .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { + options.Cookie.Name = BifrostCookies.Session; + options.Cookie.SecurePolicy = CookieSecurePolicy.Always; + options.Cookie.Path = BifrostCookies.Path; + options.Cookie.Domain = null; options.LoginPath = "/auth/sign-in"; options.AccessDeniedPath = "/Membership/Status"; options.SlidingExpiration = true; @@ -183,6 +194,9 @@ if (configuredGitHubOAuthOptions.IsConfigured) options.TokenEndpoint = "https://github.com/login/oauth/access_token"; options.UserInformationEndpoint = "https://api.github.com/user"; options.SaveTokens = true; + options.CorrelationCookie.Name = BifrostCookies.OAuthCorrelation; + options.CorrelationCookie.SecurePolicy = CookieSecurePolicy.Always; + options.CorrelationCookie.Path = BifrostCookies.Path; options.Scope.Add("read:user"); options.Scope.Add("user:email"); options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id"); diff --git a/tests/Bifrost.Web.Tests/ConceptVotePageTests.cs b/tests/Bifrost.Web.Tests/ConceptVotePageTests.cs index 5434e8d..d0675d7 100644 --- a/tests/Bifrost.Web.Tests/ConceptVotePageTests.cs +++ b/tests/Bifrost.Web.Tests/ConceptVotePageTests.cs @@ -1,3 +1,4 @@ +using Bifrost.Web.Features.Shared; using System.Net; using System.Text.RegularExpressions; using Bifrost.Web.Data; @@ -14,7 +15,7 @@ namespace Bifrost.Web.Tests; public sealed partial class ConceptVotePageTests : IClassFixture { - private const string CookieName = "bifrost_voter"; + private const string CookieName = BifrostCookies.Voter; private const string Purpose = "Bifrost.ConceptVotes.DeviceToken.v1"; private readonly TestWebApplicationFactory _factory; @@ -40,7 +41,7 @@ public sealed partial class ConceptVotePageTests : IClassFixture { private const string Site = "https://localhost"; - private const string CookieName = "bifrost_voter"; + private const string CookieName = BifrostCookies.Voter; private readonly LimitedFactory _factory; diff --git a/tests/Bifrost.Web.Tests/CookieHardeningTests.cs b/tests/Bifrost.Web.Tests/CookieHardeningTests.cs new file mode 100644 index 0000000..3a43ebc --- /dev/null +++ b/tests/Bifrost.Web.Tests/CookieHardeningTests.cs @@ -0,0 +1,101 @@ +using Bifrost.Web.Features.ConceptVotes; +using Bifrost.Web.Features.Heimdall; +using Bifrost.Web.Features.Shared; +using Bifrost.Web.Tests.Support; +using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Authentication.OAuth; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; + +namespace Bifrost.Web.Tests; + +// Every cookie is host-only: __Host- name, Secure, Path=/, no Domain. These pin the literals on purpose, so removing +// the prefix, Secure or Path=/ from any of them fails here and not only in a test that reads the same constant. +public sealed class CookieHardeningTests(CookieHardeningTests.OAuthConfiguredFactory factory) + : IClassFixture +{ + // Program reads GitHubOAuth at startup, before the base factory's in-memory settings land, so the GitHub scheme + // is only registered when the settings arrive as host settings. + public sealed class OAuthConfiguredFactory : TestWebApplicationFactory + { + protected override void ConfigureWebHost(Microsoft.AspNetCore.Hosting.IWebHostBuilder builder) + { + builder.UseSetting("GitHubOAuth:ClientId", "configured-for-tests"); + builder.UseSetting("GitHubOAuth:ClientSecret", "configured-for-tests"); + base.ConfigureWebHost(builder); + } + } + + [Fact] + public void Cookie_names_carry_the_host_prefix_and_live_at_the_root() + { + Assert.Equal("__Host-bifrost_session", BifrostCookies.Session); + Assert.Equal("__Host-bifrost_oauth_correlation", BifrostCookies.OAuthCorrelation); + Assert.Equal("__Host-bifrost_antiforgery", BifrostCookies.Antiforgery); + Assert.Equal("__Host-bifrost_voter", VoterKeyResolver.CookieName); + Assert.Equal("__Host-bifrost_heimdall_", HeimdallAttemptCookie.Prefix); + Assert.All(HeimdallAttemptCookie.SlotNames, x => Assert.StartsWith("__Host-", x, StringComparison.Ordinal)); + Assert.Equal("/", BifrostCookies.Path); + Assert.Equal("/", VoterKeyResolver.CookiePath); + } + + [Fact] + public void Session_cookie_is_host_only() + { + var cookie = factory.Services.GetRequiredService>() + .Get(CookieAuthenticationDefaults.AuthenticationScheme).Cookie; + AssertHostOnly(cookie.Name, cookie.SecurePolicy, cookie.Path, cookie.Domain); + Assert.True(cookie.HttpOnly); + } + + [Fact] + public void Oauth_correlation_cookie_is_host_only() + { + var cookie = factory.Services.GetRequiredService>().Get("GitHub").CorrelationCookie; + AssertHostOnly(cookie.Name, cookie.SecurePolicy, cookie.Path, cookie.Domain); + Assert.True(cookie.HttpOnly); + } + + [Fact] + public void Antiforgery_cookie_is_host_only() + { + var cookie = factory.Services.GetRequiredService>().Value.Cookie; + AssertHostOnly(cookie.Name, cookie.SecurePolicy, cookie.Path, cookie.Domain); + } + + [Fact] + public void Voter_and_attempt_cookies_set_secure_root_path_and_no_domain() + { + var context = new DefaultHttpContext(); + new VoterKeyResolver(new Microsoft.AspNetCore.DataProtection.EphemeralDataProtectionProvider()).Mint(context); + context.Response.Cookies.Append("__Host-bifrost_heimdall_0", "v", HeimdallAttemptCookie.Options()); + var deletion = new DefaultHttpContext(); + deletion.Response.Cookies.Delete("__Host-bifrost_heimdall_0", HeimdallAttemptCookie.DeleteOptions()); + + var headers = context.Response.Headers.SetCookie.Concat(deletion.Response.Headers.SetCookie).ToArray(); + Assert.Equal(3, headers.Length); + foreach (var header in headers) + { + var attributes = header!.Split(';').Select(x => x.Trim().ToLowerInvariant()).ToArray(); + Assert.StartsWith("__host-", attributes[0], StringComparison.Ordinal); + Assert.Contains("path=/", attributes); + Assert.DoesNotContain(attributes, x => x.StartsWith("domain", StringComparison.Ordinal)); + } + + Assert.All(headers.Take(2), header => + { + Assert.Contains("secure", header!.Split(';').Select(x => x.Trim().ToLowerInvariant())); + Assert.Contains("httponly", header!.Split(';').Select(x => x.Trim().ToLowerInvariant())); + }); + } + + private static void AssertHostOnly(string? name, CookieSecurePolicy secure, string? path, string? domain) + { + Assert.StartsWith("__Host-", name, StringComparison.Ordinal); + Assert.Equal(CookieSecurePolicy.Always, secure); + Assert.Equal("/", path); + Assert.Null(domain); + } +} diff --git a/tests/Bifrost.Web.Tests/HeimdallCompletionTests.cs b/tests/Bifrost.Web.Tests/HeimdallCompletionTests.cs index 3439b43..68f0a94 100644 --- a/tests/Bifrost.Web.Tests/HeimdallCompletionTests.cs +++ b/tests/Bifrost.Web.Tests/HeimdallCompletionTests.cs @@ -526,7 +526,7 @@ public sealed class HeimdallCompletionTests Assert.Contains("httponly", attributes); Assert.Contains("secure", attributes); Assert.Contains("samesite=lax", attributes); - Assert.Contains("path=/auth/heimdall", attributes); + Assert.Contains("path=/", attributes); Assert.Contains("max-age=600", attributes); Assert.NotEqual(first.Cookie, second.Cookie); Assert.DoesNotContain(first.Nonce, first.Cookie!); @@ -564,7 +564,7 @@ public sealed class HeimdallCompletionTests Assert.Contains("