feat(accounts): one account across an instance's services (ADR 0016)

halkyon_base runs as the instance's register or as one of its members.
The register keeps the ways in, handles and profiles; members ask it
over HTTP with the instance's shared secret (instanceSecret), and open
sessions of their own for its accounts, under the same account ID.

- AccountsMode from the environment: INSTANCE_MEMBERS on the register,
  ACCOUNT_REGISTER_URL on a member. Learn always holds the register
  (Explore joins the profiles); Todo is a member where it is set.
- AccountRegister: LocalRegister, RemoteRegister, an in-memory one in
  tests. Calls between services on the web server, refused without the
  secret (constant-time compare); a server needing it doesn't start
  without it.
- Deleting an account deletes it everywhere: notices per member kept in
  the deletion's transaction (account_deletion_notice), told at once and
  hourly until confirmed; members prune daily whom the register no longer
  knows, never while it knows none of them or can't be reached.
- Deploy: INSTANCE_SECRET and INSTANCE_MEMBERS in compose and .env.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Tizian 「ティツィアーン」 <raisondetredev@pm.me>
This commit is contained in:
Tizian 「ティツィアーン」 2026-10-19 23:10:08 +02:00
commit 65c5cd740d
Signed by: raisondetredev
GPG key ID: 07F6FCF405488B64
12 changed files with 41906 additions and 167 deletions

View file

@ -17,7 +17,9 @@ Future<void> run(List<String> args) async {
final pod = Serverpod(args);
// What every Halkyon server has (ADR 0014): sign-in, the account and its
// deletion, the pruning, the instance's basics, set up for Learn.
HalkyonBase.configure(pod, learnBase());
// Learn holds the instance's register of accounts (ADR 0016), telling the
// instance's other services when one goes.
HalkyonBase.configure(pod, learnBase(accounts: learnAccounts()));
pod
// Token managers validate and issue authentication keys; identity
// providers are the ways people can sign in (halkyon_base's
@ -30,6 +32,9 @@ Future<void> run(List<String> args) async {
..addCloudStorage(DatabaseCloudStorage('private'))
..addCloudStorage(DatabaseCloudStorage('public'));
// The calls of the instance's other services, on the web server
// (ADR 0016); Caddy never forwards them.
addInstanceRoutes(pod);
// The assistant connector, on the web server (ADR 0006).
addConnectorRoutes(pod);
// Profile pages, `/@handle`, which profile links link back to (ADR 0011),
@ -63,6 +68,15 @@ Future<void> run(List<String> args) async {
.pruning
.forgetSignUpAttempts();
// The deletions the instance's members haven't confirmed yet, hourly
// (ADR 0016).
await pod.futureCalls.cancel(_deletionNotices);
await pod.futureCalls
.callRecurring(identifier: _deletionNotices)
.cron('52 * * * *')
.pruning
.tellMembersOfDeletions();
// The assistant connector's expired codes and tokens (ADR 0006, rule 5).
await pod.futureCalls.cancel(_connectorPruning);
await pod.futureCalls
@ -121,6 +135,9 @@ const _pruning = 'prune-abandoned-anonymous-people';
/// The identifier of the hourly forgetting of sign-up attempts.
const _attemptPruning = 'forget-sign-up-attempts';
/// The identifier of the hourly telling of the members of deleted accounts.
const _deletionNotices = 'tell-members-of-deletions';
/// The identifier of the daily forgetting of the connector's expired secrets.
const _connectorPruning = 'forget-connector-secrets';

View file

@ -15,18 +15,38 @@ const upstreamSourceCodeUrl =
/// serves `learn` (the app accepts only such an instance; never change it),
/// sign-in mails name the app, the instance names this project's source,
/// works with apps from [minimumAppBuild] on, deletes Learn's own data of a
/// person who goes ([deleteLearnData]), and profile pages name the app at
/// their foot. The server sets it up before it starts (`server.dart`), and so
/// do tests that delete people or read profiles.
HalkyonBase learnBase() => HalkyonBase(
app: 'learn',
appName: 'Halkyon Learn',
upstreamSourceCodeUrl: upstreamSourceCodeUrl,
minimumAppBuild: minimumAppBuild,
deletePersonData: const [deleteLearnData],
profilePageNote: (
english: 'On Halkyon Learn, a spaced-repetition learning app:',
german: 'Auf Halkyon Learn, einer Lern-App mit verteilter Wiederholung:',
link: Uri.parse('https://halkyon.app/learn'),
),
);
/// person who goes ([deleteLearnData]), profile pages name the app at their
/// foot, and it holds the instance's register with [accounts]' members
/// ([learnAccounts]). The server sets it up before it starts (`server.dart`),
/// and so do tests that delete people or read profiles.
HalkyonBase learnBase({HoldsRegister accounts = const HoldsRegister()}) =>
HalkyonBase(
app: 'learn',
appName: 'Halkyon Learn',
upstreamSourceCodeUrl: upstreamSourceCodeUrl,
minimumAppBuild: minimumAppBuild,
deletePersonData: const [deleteLearnData],
profilePageNote: (
english: 'On Halkyon Learn, a spaced-repetition learning app:',
german:
'Auf Halkyon Learn, einer Lern-App mit verteilter Wiederholung:',
link: Uri.parse('https://halkyon.app/learn'),
),
accounts: accounts,
);
/// Learn's part in the instance's accounts (ADR 0016), from the operator's
/// [environment]: it holds the register, telling the members
/// `INSTANCE_MEMBERS` names when an account goes. Never a member: Explore
/// searches studysets by their authors' handles in the same query as the
/// releases (`explore_endpoint.dart`), so the profiles must be in Learn's
/// own database. An `ACCOUNT_REGISTER_URL` stops the server as it starts.
HoldsRegister learnAccounts([Map<String, String>? environment]) =>
switch (AccountsMode.fromEnvironment(environment)) {
final HoldsRegister accounts => accounts,
MemberOfRegister() => throw StateError(
"Halkyon Learn holds its instance's register (ADR 0016) and is "
"never a member of another's: unset ACCOUNT_REGISTER_URL, and name "
'the other services in INSTANCE_MEMBERS.',
),
};

View file

@ -5,11 +5,11 @@ import 'package:serverpod/serverpod.dart';
/// Deletes the anonymous people nobody can return to, daily, the IP
/// addresses of sign-up attempts the rate limit is done with and the email
/// sign-in codes past their time, hourly, and
/// the assistant connector's expired secrets, daily; the server schedules
/// them when it starts (`server.dart`). All but the last are halkyon_base's
/// (ADR 0014), and people go through its `deletePerson`, so Learn's own data
/// of theirs goes too.
/// sign-in codes past their time, hourly, the deletions the instance's
/// members haven't confirmed, hourly, and the assistant connector's expired
/// secrets, daily; the server schedules them when it starts (`server.dart`).
/// All but the last are halkyon_base's (ADR 0014, ADR 0016), and people go
/// through its `deletePerson`, so Learn's own data of theirs goes too.
class PruningFutureCall extends FutureCall {
/// Prunes one batch and logs how many people went.
Future<void> pruneAnonymousPeople(Session session) async {
@ -39,4 +39,11 @@ class PruningFutureCall extends FutureCall {
final codes = await forgetExpiredEmailCodes(session, now: now);
session.log('Forgot $forgotten sign-up attempts and $codes email codes.');
}
/// Tells the instance's members again of the accounts gone that they
/// haven't confirmed yet (ADR 0016), and logs how many confirmed.
Future<void> tellMembersOfDeletions(Session session) async {
final confirmed = await deliverDeletionNotices(session);
session.log('Members confirmed $confirmed deleted accounts.');
}
}

View file

@ -68,6 +68,8 @@ class FutureCalls extends _is.FutureCallDispatch<_FutureCallRef> {
PruningForgetConnectorSecretsFutureCall(),
'PruningForgetSignUpAttemptsFutureCall':
PruningForgetSignUpAttemptsFutureCall(),
'PruningTellMembersOfDeletionsFutureCall':
PruningTellMembersOfDeletionsFutureCall(),
'DictionaryReloadReloadDictionariesFutureCall':
DictionaryReloadReloadDictionariesFutureCall(),
'LearnerCountCountLearnersFutureCall':
@ -243,6 +245,13 @@ class _PruningFutureCallDispatcher {
null,
);
}
Future<void> tellMembersOfDeletions() {
return _invokeFutureCall(
'PruningTellMembersOfDeletionsFutureCall',
null,
);
}
}
class _DictionaryReloadFutureCallDispatcher {
@ -322,6 +331,19 @@ class PruningForgetSignUpAttemptsFutureCall extends _is.FutureCall
}
}
/// Tells the instance's members again of the accounts gone that they
/// haven't confirmed yet (ADR 0016), and logs how many confirmed.
class PruningTellMembersOfDeletionsFutureCall extends _is.FutureCall
implements _is.InvokableFutureCall {
@override
_ida.Future<void> invoke(
_is.Session session,
_is.SerializableModel? object,
) async {
await _igevg04y.PruningFutureCall().tellMembersOfDeletions(session);
}
}
/// Loads the dictionary files that changed since they were loaded.
class DictionaryReloadReloadDictionariesFutureCall extends _is.FutureCall
implements _is.InvokableFutureCall {

View file

@ -0,0 +1,92 @@
{
"__className__": "serverpod.DatabaseMigration",
"actions": [
{
"__className__": "serverpod.DatabaseMigrationAction",
"type": "createTable",
"createTable": {
"__className__": "serverpod.TableDefinition",
"name": "account_deletion_notice",
"dartName": "AccountDeletionNotice",
"module": "halkyon_base",
"schema": "public",
"columns": [
{
"__className__": "serverpod.ColumnDefinition",
"name": "id",
"fieldName": "id",
"columnType": 6,
"isNullable": false,
"columnDefault": "serial",
"dartType": "int?"
},
{
"__className__": "serverpod.ColumnDefinition",
"name": "account",
"fieldName": "account",
"columnType": 7,
"isNullable": false,
"dartType": "UuidValue"
},
{
"__className__": "serverpod.ColumnDefinition",
"name": "member",
"fieldName": "member",
"columnType": 0,
"isNullable": false,
"dartType": "String"
},
{
"__className__": "serverpod.ColumnDefinition",
"name": "createdAt",
"fieldName": "createdAt",
"columnType": 4,
"isNullable": false,
"dartType": "DateTime"
},
{
"__className__": "serverpod.ColumnDefinition",
"name": "attempts",
"fieldName": "attempts",
"columnType": 6,
"isNullable": false,
"dartType": "int"
},
{
"__className__": "serverpod.ColumnDefinition",
"name": "lastAttemptAt",
"fieldName": "lastAttemptAt",
"columnType": 4,
"isNullable": true,
"dartType": "DateTime?"
}
],
"foreignKeys": [],
"indexes": [
{
"__className__": "serverpod.IndexDefinition",
"indexName": "account_deletion_notice_idx",
"elements": [
{
"__className__": "serverpod.IndexElementDefinition",
"type": 0,
"definition": "account"
},
{
"__className__": "serverpod.IndexElementDefinition",
"type": 0,
"definition": "member"
}
],
"type": "btree",
"isUnique": true,
"isPrimary": false
}
],
"managed": true
}
}
],
"warnings": [],
"migrationApiVersion": 1
}

View file

@ -0,0 +1,68 @@
BEGIN;
--
-- ACTION CREATE TABLE
--
CREATE TABLE "account_deletion_notice" (
"id" bigserial PRIMARY KEY,
"account" uuid NOT NULL,
"member" text NOT NULL,
"createdAt" timestamp without time zone NOT NULL,
"attempts" bigint NOT NULL,
"lastAttemptAt" timestamp without time zone
);
-- Indexes
CREATE UNIQUE INDEX "account_deletion_notice_idx" ON "account_deletion_notice" USING btree ("account", "member");
--
-- MIGRATION VERSION FOR halkyon_learn
--
INSERT INTO "serverpod_migrations" ("module", "version", "timestamp")
VALUES ('halkyon_learn', '20261019204112282-deletion-notices', now())
ON CONFLICT ("module")
DO UPDATE SET "version" = '20261019204112282-deletion-notices', "timestamp" = now();
--
-- MIGRATION VERSION FOR halkyon_base
--
INSERT INTO "serverpod_migrations" ("module", "version", "timestamp")
VALUES ('halkyon_base', '20261019202835333-deletion-notices', now())
ON CONFLICT ("module")
DO UPDATE SET "version" = '20261019202835333-deletion-notices', "timestamp" = now();
--
-- MIGRATION VERSION FOR serverpod
--
INSERT INTO "serverpod_migrations" ("module", "version", "timestamp")
VALUES ('serverpod', '20260824182259319', now())
ON CONFLICT ("module")
DO UPDATE SET "version" = '20260824182259319', "timestamp" = now();
--
-- MIGRATION VERSION FOR serverpod_auth_idp
--
INSERT INTO "serverpod_migrations" ("module", "version", "timestamp")
VALUES ('serverpod_auth_idp', '20260924105404509', now())
ON CONFLICT ("module")
DO UPDATE SET "version" = '20260924105404509', "timestamp" = now();
--
-- MIGRATION VERSION FOR serverpod_offline_sync
--
INSERT INTO "serverpod_migrations" ("module", "version", "timestamp")
VALUES ('serverpod_offline_sync', '20260914143806119', now())
ON CONFLICT ("module")
DO UPDATE SET "version" = '20260914143806119', "timestamp" = now();
--
-- MIGRATION VERSION FOR serverpod_auth_core
--
INSERT INTO "serverpod_migrations" ("module", "version", "timestamp")
VALUES ('serverpod_auth_core', '20260924105232991', now())
ON CONFLICT ("module")
DO UPDATE SET "version" = '20260924105232991', "timestamp" = now();
COMMIT;

View file

@ -34,3 +34,4 @@
20261017110130653
20261019121406578-halkyon-base
20261019201023295-profiles-in-halkyon-base
20261019204112282-deletion-notices

View file

@ -2047,6 +2047,21 @@ class _PruningFutureCall {
await _localUniqueSession.close();
}
}
Future<void> tellMembersOfDeletions(
_ist.TestSessionBuilder sessionBuilder,
) async {
var _localUniqueSession =
(sessionBuilder as _ist.InternalTestSessionBuilder).internalBuild();
try {
await _iip9210p.PruningTellMembersOfDeletionsFutureCall().invoke(
_localUniqueSession,
null,
);
} finally {
await _localUniqueSession.close();
}
}
}
class _DictionaryReloadFutureCall {

View file

@ -1,3 +1,4 @@
import 'package:halkyon_base_server/base.dart';
import 'package:halkyon_learn_server/src/auth/learn_base.dart';
import 'package:test/test.dart';
@ -6,4 +7,36 @@ void main() {
'apps accept', () {
expect(learnBase().app, 'learn');
});
group("Learn's part in the instance's accounts (ADR 0016)", () {
test('is the register, telling the members the operator names', () {
final accounts = learnAccounts(const {
'INSTANCE_MEMBERS': 'http://todo:8082',
});
expect(accounts.members, [Uri.parse('http://todo:8082')]);
expect(learnBase(accounts: accounts).accounts, same(accounts));
});
test('is the register with no members unless the operator names some', () {
expect(learnAccounts(const {}).members, isEmpty);
expect(learnBase().accounts, isA<HoldsRegister>());
});
test('is never a member: Explore searches the profiles in its own '
'database', () {
expect(
() => learnAccounts(const {
'ACCOUNT_REGISTER_URL': 'http://todo:8082',
}),
throwsA(
isA<StateError>().having(
(error) => error.message,
'message',
contains('ACCOUNT_REGISTER_URL'),
),
),
);
});
});
}