Template
1
0

feat: add functional authentication

This commit is contained in:
2025-08-12 23:11:08 +02:00
parent f0630d43b7
commit 82d7a0d9cd
74 changed files with 763 additions and 396 deletions

View File

@@ -0,0 +1,5 @@
import { register } from "@valkyr/event-store/mongo";
import { eventStore } from "../event-store.ts";
await register(eventStore.db.db, console.info);

View File

@@ -0,0 +1,209 @@
import { toAccountDocument } from "@spec/schemas/account/account.ts";
import { Strategy } from "@spec/schemas/account/strategies.ts";
import { Avatar } from "@spec/schemas/avatar.ts";
import { Contact } from "@spec/schemas/contact.ts";
import { Email } from "@spec/schemas/email.ts";
import { Name } from "@spec/schemas/name.ts";
import { AggregateRoot, getDate } from "@valkyr/event-store";
import { db } from "~stores/read-store/database.ts";
import { eventStore } from "../event-store.ts";
import { Auditor, systemAuditor } from "../events/auditor.ts";
import { EventStoreFactory } from "../events/mod.ts";
import { projector } from "../projector.ts";
export class Account extends AggregateRoot<EventStoreFactory> {
static override readonly name = "account";
avatar?: Avatar;
name?: Name;
contact: Contact = {
emails: [],
};
strategies: Strategy[] = [];
createdAt!: Date;
updatedAt!: Date;
// -------------------------------------------------------------------------
// Reducer
// -------------------------------------------------------------------------
with(event: EventStoreFactory["$events"][number]["$record"]): void {
switch (event.type) {
case "account:created": {
this.id = event.stream;
this.createdAt = getDate(event.created);
}
case "account:avatar:added": {
this.avatar = { url: event.data };
this.updatedAt = getDate(event.created);
break;
}
case "account:name:added": {
this.name = event.data;
this.updatedAt = getDate(event.created);
break;
}
case "account:email:added": {
this.contact.emails.push(event.data);
this.updatedAt = getDate(event.created);
break;
}
case "strategy:email:added": {
this.strategies.push({ type: "email", value: event.data });
this.updatedAt = getDate(event.created);
break;
}
case "strategy:password:added": {
this.strategies.push({ type: "password", ...event.data });
this.updatedAt = getDate(event.created);
break;
}
}
}
// -------------------------------------------------------------------------
// Actions
// -------------------------------------------------------------------------
create(meta: Auditor = systemAuditor) {
return this.push({
stream: this.id,
type: "account:created",
meta,
});
}
addAvatar(url: string, meta: Auditor = systemAuditor): this {
return this.push({
stream: this.id,
type: "account:avatar:added",
data: url,
meta,
});
}
addName(name: Name, meta: Auditor = systemAuditor): this {
return this.push({
stream: this.id,
type: "account:name:added",
data: name,
meta,
});
}
addEmail(email: Email, meta: Auditor = systemAuditor): this {
return this.push({
stream: this.id,
type: "account:email:added",
data: email,
meta,
});
}
addRole(roleId: string, meta: Auditor = systemAuditor): this {
return this.push({
stream: this.id,
type: "account:role:added",
data: roleId,
meta,
});
}
addEmailStrategy(email: string, meta: Auditor = systemAuditor): this {
return this.push({
stream: this.id,
type: "strategy:email:added",
data: email,
meta,
});
}
addPasswordStrategy(alias: string, password: string, meta: Auditor = systemAuditor): this {
return this.push({
stream: this.id,
type: "strategy:password:added",
data: { alias, password },
meta,
});
}
}
/*
|--------------------------------------------------------------------------------
| Utilities
|--------------------------------------------------------------------------------
*/
export async function isEmailClaimed(email: string): Promise<boolean> {
const relations = await eventStore.relations.getByKey(getAccountEmailRelation(email));
if (relations.length > 0) {
return true;
}
return false;
}
/*
|--------------------------------------------------------------------------------
| Relations
|--------------------------------------------------------------------------------
*/
export function getAccountEmailRelation(email: string): string {
return `/accounts/emails/${email}`;
}
export function getAccountAliasRelation(alias: string): string {
return `/accounts/aliases/${alias}`;
}
/*
|--------------------------------------------------------------------------------
| Projectors
|--------------------------------------------------------------------------------
*/
projector.on("account:created", async ({ stream: id }) => {
await db.collection("accounts").insertOne(
toAccountDocument({
id,
name: {
given: null,
family: null,
},
contact: {
emails: [],
},
strategies: [],
roles: [],
}),
);
});
projector.on("account:avatar:added", async ({ stream: id, data: url }) => {
await db.collection("accounts").updateOne({ id }, { $set: { avatar: { url } } });
});
projector.on("account:name:added", async ({ stream: id, data: name }) => {
await db.collection("accounts").updateOne({ id }, { $set: { name } });
});
projector.on("account:email:added", async ({ stream: id, data: email }) => {
await db.collection("accounts").updateOne({ id }, { $push: { "contact.emails": email } });
});
projector.on("account:role:added", async ({ stream: id, data: roleId }) => {
await db.collection("accounts").updateOne({ id }, { $push: { roles: roleId } });
});
projector.on("strategy:email:added", async ({ stream: id, data: email }) => {
await eventStore.relations.insert(getAccountEmailRelation(email), id);
await db.collection("accounts").updateOne({ id }, { $push: { strategies: { type: "email", value: email } } });
});
projector.on("strategy:password:added", async ({ stream: id, data: strategy }) => {
await eventStore.relations.insert(getAccountAliasRelation(strategy.alias), id);
await db.collection("accounts").updateOne({ id }, { $push: { strategies: { type: "password", ...strategy } } });
});

View File

@@ -0,0 +1,66 @@
import { AggregateRoot, getDate } from "@valkyr/event-store";
import { CodeIdentity } from "../events/code.ts";
import { EventStoreFactory } from "../events/mod.ts";
export class Code extends AggregateRoot<EventStoreFactory> {
static override readonly name = "code";
identity!: CodeIdentity;
value!: string;
createdAt!: Date;
claimedAt?: Date;
// -------------------------------------------------------------------------
// Accessors
// -------------------------------------------------------------------------
get isClaimed(): boolean {
return this.claimedAt !== undefined;
}
// -------------------------------------------------------------------------
// Folder
// -------------------------------------------------------------------------
with(event: EventStoreFactory["$events"][number]["$record"]): void {
switch (event.type) {
case "code:created": {
this.value = event.data.value;
this.identity = event.data.identity;
this.createdAt = getDate(event.created);
break;
}
case "code:claimed": {
this.claimedAt = getDate(event.created);
break;
}
}
}
// -------------------------------------------------------------------------
// Actions
// -------------------------------------------------------------------------
create(identity: CodeIdentity): this {
return this.push({
type: "code:created",
stream: this.id,
data: {
identity,
value: crypto
.getRandomValues(new Uint8Array(5))
.map((v) => v % 10)
.join(""),
},
});
}
claim(): this {
return this.push({
type: "code:claimed",
stream: this.id,
});
}
}

View File

@@ -0,0 +1,118 @@
import { AggregateRoot, getDate, makeAggregateReducer } from "@valkyr/event-store";
import { db } from "~libraries/read-store/database.ts";
import type { Auditor } from "../events/auditor.ts";
import { EventStoreFactory } from "../events/mod.ts";
import type { RoleCreatedData, RolePermissionOperation } from "../events/role.ts";
import { projector } from "../projector.ts";
export class Role extends AggregateRoot<EventStoreFactory> {
static override readonly name = "role";
id!: string;
name!: string;
permissions: { [resource: string]: Set<string> } = {};
createdAt!: Date;
updatedAt!: Date;
// -------------------------------------------------------------------------
// Factories
// -------------------------------------------------------------------------
static #reducer = makeAggregateReducer(Role);
static create(data: RoleCreatedData, meta: Auditor): Role {
return new Role().push({
type: "role:created",
data,
meta,
});
}
static async getById(stream: string): Promise<Role | undefined> {
return this.$store.reduce({ name: "role", stream, reducer: this.#reducer });
}
// -------------------------------------------------------------------------
// Reducer
// -------------------------------------------------------------------------
override with(event: EventStoreFactory["$events"][number]["$record"]): void {
switch (event.type) {
case "role:created": {
this.id = event.stream;
this.createdAt = getDate(event.created);
this.updatedAt = getDate(event.created);
break;
}
case "role:name-set": {
this.name = event.data;
this.updatedAt = getDate(event.created);
break;
}
case "role:permissions-set": {
for (const operation of event.data) {
if (operation.type === "grant") {
if (this.permissions[operation.resource] === undefined) {
this.permissions[operation.resource] = new Set();
}
this.permissions[operation.resource].add(operation.action);
}
if (operation.type === "deny") {
if (operation.action === undefined) {
delete this.permissions[operation.resource];
} else {
this.permissions[operation.resource]?.delete(operation.action);
}
}
}
break;
}
}
}
// -------------------------------------------------------------------------
// Actions
// -------------------------------------------------------------------------
setName(name: string, meta: Auditor): this {
return this.push({
type: "role:name-set",
stream: this.id,
data: name,
meta,
});
}
setPermissions(operations: RolePermissionOperation[], meta: Auditor): this {
return this.push({
type: "role:permissions-set",
stream: this.id,
data: operations,
meta,
});
}
}
/*
|--------------------------------------------------------------------------------
| Projectors
|--------------------------------------------------------------------------------
*/
projector.on("role:created", async ({ stream, data: { name, permissions } }) => {
await db.collection("roles").insertOne({
id: stream,
name,
permissions: permissions.reduce(
(map, permission) => {
map[permission.resource] = permission.actions;
return map;
},
{} as Record<string, string[]>,
),
});
});

View File

@@ -0,0 +1,24 @@
import { EventStore } from "@valkyr/event-store";
import { MongoAdapter } from "@valkyr/event-store/mongo";
import { config } from "~config";
import { container } from "~libraries/database/container.ts";
import { events } from "./events/mod.ts";
import { projector } from "./projector.ts";
export const eventStore = new EventStore({
adapter: new MongoAdapter(() => container.get("client"), `${config.name}:event-store`),
events,
snapshot: "auto",
});
eventStore.onEventsInserted(async (records, { batch }) => {
if (batch !== undefined) {
await projector.pushMany(batch, records);
} else {
for (const record of records) {
await projector.push(record, { hydrated: false, outdated: false });
}
}
});

View File

@@ -0,0 +1,14 @@
import { EmailSchema } from "@spec/schemas/email.ts";
import { NameSchema } from "@spec/schemas/name.ts";
import { event } from "@valkyr/event-store";
import z from "zod";
import { AuditorSchema } from "./auditor.ts";
export default [
event.type("account:created").meta(AuditorSchema),
event.type("account:avatar:added").data(z.string()).meta(AuditorSchema),
event.type("account:name:added").data(NameSchema).meta(AuditorSchema),
event.type("account:email:added").data(EmailSchema).meta(AuditorSchema),
event.type("account:role:added").data(z.string()).meta(AuditorSchema),
];

View File

@@ -0,0 +1,21 @@
import z from "zod";
export const AuditorSchema = z.object({
auditor: z.union([
z.object({
type: z.literal("system"),
}),
z.object({
type: z.literal("account"),
accountId: z.string(),
}),
]),
});
export const systemAuditor: Auditor = {
auditor: {
type: "system",
},
};
export type Auditor = z.infer<typeof AuditorSchema>;

View File

@@ -0,0 +1,18 @@
import { event } from "@valkyr/event-store";
import z from "zod";
const CodeIdentitySchema = z.object({
accountId: z.string(),
});
export default [
event.type("code:created").data(
z.object({
identity: CodeIdentitySchema,
value: z.string(),
}),
),
event.type("code:claimed"),
];
export type CodeIdentity = z.infer<typeof CodeIdentitySchema>;

View File

@@ -0,0 +1,11 @@
import { EventFactory } from "@valkyr/event-store";
import account from "./account.ts";
import code from "./code.ts";
import organization from "./organization.ts";
import role from "./role.ts";
import strategy from "./strategy.ts";
export const events = new EventFactory([...account, ...code, ...organization, ...role, ...strategy]);
export type EventStoreFactory = typeof events;

View File

@@ -0,0 +1,11 @@
import { event } from "@valkyr/event-store";
import z from "zod";
import { AuditorSchema } from "./auditor.ts";
export default [
event
.type("organization:created")
.data(z.object({ name: z.string() }))
.meta(AuditorSchema),
];

View File

@@ -0,0 +1,37 @@
import { event } from "@valkyr/event-store";
import z from "zod";
import { AuditorSchema } from "./auditor.ts";
const CreatedSchema = z.object({
name: z.string(),
permissions: z.array(
z.object({
resource: z.string(),
actions: z.array(z.string()),
}),
),
});
const OperationSchema = z.discriminatedUnion("type", [
z.object({
type: z.literal("grant"),
resource: z.string(),
action: z.string(),
}),
z.object({
type: z.literal("deny"),
resource: z.string(),
action: z.string().optional(),
}),
]);
export default [
event.type("role:created").data(CreatedSchema).meta(AuditorSchema),
event.type("role:name-set").data(z.string()).meta(AuditorSchema),
event.type("role:permissions-set").data(z.array(OperationSchema)).meta(AuditorSchema),
];
export type RoleCreatedData = z.infer<typeof CreatedSchema>;
export type RolePermissionOperation = z.infer<typeof OperationSchema>;

View File

@@ -0,0 +1,13 @@
import { event } from "@valkyr/event-store";
import z from "zod";
import { AuditorSchema } from "./auditor.ts";
export default [
event.type("strategy:email:added").data(z.string()).meta(AuditorSchema),
event.type("strategy:passkey:added").meta(AuditorSchema),
event
.type("strategy:password:added")
.data(z.object({ alias: z.string(), password: z.string() }))
.meta(AuditorSchema),
];

View File

@@ -0,0 +1,5 @@
import { Projector } from "@valkyr/event-store";
import { EventStoreFactory } from "./events/mod.ts";
export const projector = new Projector<EventStoreFactory>();

View File

@@ -0,0 +1,19 @@
import { idIndex } from "~libraries/database/id.ts";
import { register } from "~libraries/database/registrar.ts";
import { db } from "../database.ts";
await register(db.db, [
{
name: "accounts",
indexes: [
idIndex,
[{ "strategies.type": 1, "strategies.alias": 1 }, { name: "strategy.password" }],
[{ "strategies.type": 1, "strategies.value": 1 }, { name: "strategy.email" }],
],
},
{
name: "roles",
indexes: [idIndex, [{ name: 1 }, { name: "role.name" }]],
},
]);

View File

@@ -0,0 +1,14 @@
import { RoleDocument } from "@spec/schemas/access/role.ts";
import type { AccountDocument } from "@spec/schemas/account/account.ts";
import { config } from "~config";
import { getDatabaseAccessor } from "~libraries/database/accessor.ts";
export const db = getDatabaseAccessor<{
accounts: AccountDocument;
roles: RoleDocument;
}>(`${config.name}:read-store`);
export function takeOne<TDocument>(documents: TDocument[]): TDocument | undefined {
return documents[0];
}

View File

@@ -0,0 +1,65 @@
import { type Account, fromAccountDocument } from "@spec/schemas/account/account.ts";
import { PasswordStrategy } from "@spec/schemas/auth/strategies.ts";
import { db, takeOne } from "./database.ts";
/*
|--------------------------------------------------------------------------------
| Accounts
|--------------------------------------------------------------------------------
*/
/**
* Retrieve a single account by its primary identifier.
*
* @param id - Account identifier.
*/
export async function getAccountById(id: string): Promise<Account | undefined> {
return db
.collection("accounts")
.aggregate([
{
$match: { id },
},
{
$lookup: {
from: "roles",
localField: "roles",
foreignField: "id",
as: "roles",
},
},
])
.toArray()
.then(fromAccountDocument)
.then(takeOne);
}
/*
|--------------------------------------------------------------------------------
| Auth
|--------------------------------------------------------------------------------
*/
/**
* Get strategy details for the given password strategy alias.
*
* @param alias - Alias to get strategy for.
*/
export async function getPasswordStrategyByAlias(
alias: string,
): Promise<({ accountId: string } & PasswordStrategy) | undefined> {
const account = await db.collection("accounts").findOne({
strategies: {
$elemMatch: { type: "password", alias },
},
});
if (account === null) {
return undefined;
}
const strategy = account.strategies.find((strategy) => strategy.type === "password" && strategy.alias === alias);
if (strategy === undefined) {
return undefined;
}
return { accountId: account.id, ...strategy } as { accountId: string } & PasswordStrategy;
}