Monetizing TeaQL in Public — Day 1: Models, Queries, and SaaS Isolation
We are adding the account, subscription and billing layer that will let TeaQL charge for its developer services. This series follows that monetization work in public, starting with the identity and Organization foundation.
Our first local console can now create an Organization, add members, assign roles, and offer ownership to another member.
That gives us a small, useful piece of a SaaS backend to discuss: identity and access management, or IAM. Before connecting subscriptions or saved models, we need to know who is signed in, which Organization they belong to, and what they may do there.
On Day 0, we proposed that boundary. Today there is a local TypeScript implementation behind the interface. This entry follows the model into database design, Q queries, E expressions, tenant checks and privacy controls you can adapt to your own SaaS.
Start with the user journey
Alex signs in to TeaQL and creates Acme. Alex becomes its Owner and an active member. Morgan joins as a Developer, and Sam handles Finance. Alex also owns Side Project Lab, with its own memberships and permissions.
Later Alex offers Acme's ownership to Morgan, who must already be an active member and explicitly accept. Alex becomes an Admin in Acme and remains Owner of Side Project Lab. Alex can then review Acme's IAM audit log to see who changed what, and review personal login history separately.
| User need | Requirement we implement |
|---|---|
| Work in several Organizations | One identity, separate memberships and grants |
| Give a colleague a responsibility | Explicit role assignment with actor authorization |
| Hand over ownership | Active recipient, explicit acceptance, atomic updates |
| Explain a membership or owner change | Persisted business audit record scoped to the Organization |
| Review sign-ins | Private account login history, separate from Organization administration |
| Diagnose a failure safely | Fixed security reason codes and sensitive diagnostic masking |
The current member-adding flow uses an existing registered account ID; invitation email and signup-by-invitation are not implemented in this slice.
A working Organization scenario
The local demo starts with a fictional builder, Alex, who owns two Organizations: Acme Developer Studio and Side Project Lab. Acme also has Sam in Finance and Morgan as a Developer.
Alex can create another Organization, manage Acme's members, and offer ownership to Morgan. Each Organization has its own memberships and owner. A change in Acme must leave Side Project Lab's ownership untouched.

Local demo with fictional accounts and a temporary SQLite database.
The screenshots use a separate demo sign-in. Our GitHub adapter and callback are implemented and tested with a simulated provider response; the actual OAuth App still needs configuration before we can verify a live GitHub login.
The domain is identity and access
We are dividing the backend into three processes: IAM, billing, and the Developer
Console. There is one shared TypeScript frontend. The first process is
iam-backend-service.
Its responsibility is the account and Organization boundary: identities, memberships, role grants, permission checks, sessions, and ownership changes. Subscriptions belong to the billing service. Model processing and model review belong to the Developer Console service. Those two integrations are still ahead.
This separation also makes the first service useful beyond TeaQL. Another SaaS can need accounts, Organizations, and billing while having a completely different product behind them.
What we mean by a model
Here, a model describes the entities, relationships, and states in that business domain. It is the contract from which TeaQL generates the TypeScript domain library. The application supplies the authorization rules and workflows that use that library.
The essential relationship is a membership between a user and an Organization. Roles attach to that membership. Alex can be an Owner in Acme and a Developer elsewhere without changing Alex's account identity.
Conceptual relationships. The UI says Organization; the current model names that
entity tenant_team.
The complete KSML model has 17 entities, including state catalogs. Its main parts are straightforward:
| Part | What it records |
|---|---|
| User account | Stable GitHub identity, verified email, and account state |
| Organization and membership | Owning account, organization state, and who is an active member |
| Roles and permissions | Roles granted within a membership and the actions those roles permit |
| Ownership transfer | Initiating Owner, recipient and membership, state, and expiry |
| Session and OAuth flow | Session digest and revocation, plus expiring one-time login state |
| Access change record | Organization, actor, action, subject, and the change being explained |
The full IAM model contains the exact entity names and relationships. The reference notes explain the scope of the downloadable material.
Design the data around the tenant boundary
A single user_account can belong to several Organizations. A membership connects
that account to one tenant_team, and a membership_role grants a role within
that connection. The role-to-permission catalog is shared by the IAM installation;
a membership supplies the Organization scope in which those grants apply.
Here are three actual declarations from our KSML model:
<tenant_team _name="Tenant Team" _module="Teams" _module_key="teams"
iam_platform="iam_platform()" team_name="Example Team" team_slug="example-team"
owner_user="user_account()" team_state="team_state()"
create_time="createTime()" update_time="updateTime()" />
<team_membership _name="Team Membership" _module="Teams" _module_key="teams"
tenant_team="tenant_team()" user_account="user_account()"
membership_state="membership_state()"
create_time="createTime()" update_time="updateTime()" />
<membership_role _name="Membership Role" _module="Access" _module_key="access"
team_membership="team_membership()" role_definition="role_definition()"
create_time="createTime()" update_time="updateTime()" />
An excerpt from the complete model; the referenced account, state and role objects are defined elsewhere in that model.
The () notation declares an object relationship. The example name and slug are
representative values used to infer field types; they do not create a real
Organization. createTime() and updateTime() describe managed timestamps.
This gives us a database design with explicit ownership paths: a membership belongs to a Team, and an assignment belongs to a membership. A transfer records the Team, initiating Owner, recipient account and recipient membership. We can ask whether each record is inside an authorized Organization before changing it.
There is also shared data. An account belongs to the identity system; one Team does not own that person's account or their memberships elsewhere. Roles and states are installation-wide reference catalogs. Copying every object into a customer's private graph would obscure these different responsibilities.
The generated metadata and SQLite provider turn this model into stored records. We inspect the actual schema in the executable example. We still have to decide and test business uniqueness, database constraints and concurrency. A relationship in XML alone does not prove a deployed foreign-key constraint or safe concurrent writes from several processes.
The fixture's actual membership table was created as follows (line breaks added):
CREATE TABLE "team_membership_data" (
"id" INTEGER PRIMARY KEY,
"version" INTEGER NOT NULL,
"tenant_team" INTEGER NOT NULL,
"user_account" INTEGER NOT NULL,
"membership_state" INTEGER NOT NULL,
"create_time" INTEGER NOT NULL,
"update_time" INTEGER NOT NULL
);
This baseline uses integer IDs and relation columns, a version for optimistic writes, and managed timestamps. The captured definition does not declare foreign keys or uniqueness for the user/Team pair. Our single-writer application currently checks logical membership uniqueness transactionally; multi-writer database constraints need separate implementation and tests.
Apply DDD through language and invariants
Domain-driven design helps us decide which business rules belong together. IAM owns the language of account, membership, grant and ownership. Billing will own subscriptions and entitlements. The Developer Console will own processing requests and saved model content.
An Organization is the consistency boundary for membership and owner changes. Creating one must also create its owner's active membership. Accepting ownership must change the owner and the former Owner's role together. An identity change on a user account has a different lifecycle and must preserve that person's other Organizations.
Those invariants are implemented in application-owned services using TeaQL transactions. The generated entities express the model; our services check the business rules, authorize the actor and coordinate the writes. We have not added an event bus or event sourcing. The access-change record is persisted history, with an actor and reason, rather than a claim that an event reached another service.
The practical DDD takeaway is to name the operation after the business intent:
accept an ownership offer, rather than exposing a generic “update owner ID” API.
The named operation has somewhere to enforce recipient consent, expiry and the
active-membership condition.
Ownership is an explicit relationship
We store the current owner in tenant_team.owner_user. Each Organization has one
owner, and that person must also have an active membership.
Admin, Developer, and Finance can be combined on a membership. Owner authority comes from the Organization's owner relationship. Assigning a role named OWNER through the member-role API cannot make someone the owner.
That distinction gives us a clear way to transfer responsibility:
- The current Owner offers ownership to an existing active member.
- The recipient explicitly accepts before the offer expires.
- The application checks the current accounts, memberships, and offer again.
- One transaction changes the owner, makes the former Owner an Admin, marks the offer accepted, and records the change.
The application names this operation OwnerTransferService.accept. Inside its
transaction, it reloads the scoped offer and both active memberships, checks
recipient identity and expiry, then performs these audited writes:
team.updateOwnerUser(principal.userId);
await team.auditAs('Accept Organization ownership as designated active member').save(tx);
await this.replaceRoles(tx, String(previousOwner.id), ['ADMIN']);
transfer.updateTransferStateToAccepted();
await transfer.auditAs('Complete accepted Organization ownership transfer').save(tx);
await this.audit(tx, principal, teamId, previousOwnerId, 'OWNERSHIP_TRANSFER_ACCEPTED', transferId,
previousOwnerId, principal.userId);
The write portion of the executed method; participant validation and test fault hooks are omitted here. The implementation validates the current recipient, accounts and memberships inside that transaction before these writes. All these operations use the same transaction context.
If the recipient is removed, the pending offer is cancelled. Rejoining later does not revive it. If acceptance fails partway through, the transaction must leave the previous ownership intact.
A SaaS builder can reuse that workflow with another database or framework. The important decisions are who may receive ownership, whether acceptance is required, and which changes must succeed together.
Role names need rules behind them
Our first IAM permission rules are deliberately small:
| Action | Owner | Admin | Developer only | Finance only |
|---|---|---|---|---|
| View own Organization | Yes | Yes | Yes | Yes |
| View members | Yes | Yes | No | No |
| Manage Developer-only members | Yes | Yes | No | No |
| Grant Admin or Finance | Yes | No | No | No |
| Offer ownership transfer | Yes | No | No | No |
The current Owner's membership is protected from ordinary role editing or removal. A transfer recipient accepts through the dedicated ownership workflow.
Finance is a separate responsibility that can be combined with another role. For example, Admin plus Finance retains the Admin permissions; Finance alone does not grant member administration. Actual billing and model-content endpoints will need their own authorization tests when those services are connected.

The running interface uses the same scoped IAM operations as the backend tests.
Every operation checks the signed-in account's current membership in the requested Organization. A team ID or member ID from the browser only identifies a resource; it does not establish permission to use it.
Query the Organizations this account actually belongs to
The following methods are executable examples from DayOneQueries, an
application service that extends our existing IAM service. They use the generated
Q and E facades. We compiled them and ran them against the same generated
TypeScript library and SQLite runtime as the console.
The account ID in principal comes from the server's session adapter. A browser
cannot provide an arbitrary principal in the request body. This first query starts
from that account's active memberships and selects the related Teams:
async organizations(principal: Principal) {
return this.runtime.context(principal.userId).transaction(async tx => {
await this.activeUser(tx, principal.userId);
const memberships = await Q.teamMemberships()
.filterByUserAccount(principal.userId)
.filterByMembershipState('1001')
.selectTenantTeamWith(Q.tenantTeams())
.orderByIdAscending().limit(25)
.comment('Read the signed-in account organization memberships')
.purpose('Render the organization switcher').executeForList(tx);
return memberships.flatMap(membership => {
const team = E.teamMembership(membership).tenantTeam().eval();
if (!team || E.tenantTeam(team).teamStateId().eval() !== '1001') return [];
return [{ id: E.tenantTeam(team).id().eval(),
name: E.tenantTeam(team).teamName().eval(),
ownerUserId: E.tenantTeam(team).ownerUserId().eval() }];
});
});
}
Q constructs the request: which records, which relationships and how many.
E reads the resulting typed graph. selectTenantTeamWith(...) is what makes the
Team available for the later expression evaluation.
The synthetic run returned these names for Alex:
["Acme Developer Studio", "Side Project Lab"]
Another account owns a third Organization in the fixture. It does not appear in Alex's results. This example is intentionally bounded to the first 25 memberships; the console's directory adds cursor pagination so users can load further pages.
Query members with an explicit data projection
Opening an Organization's member page requires more than knowing its ID. We first
check the current account and membership and require iam.members.read. Then we
constrain the query to that Team:
async members(principal: Principal, teamId: string) {
return this.runtime.context(principal.userId).transaction(async tx => {
const access = await this.require(tx, principal, teamId, 'iam.members.read');
const members = await Q.teamMemberships()
.filterByTenantTeam(teamId).filterByMembershipState('1001')
.selectUserAccountWith(Q.userAccountsWithMinimalFields().selectGithubUsername())
.selectMembershipRoleListWith(Q.membershipRoles().orderByIdAscending().limit(4))
.orderByIdAscending().limit(25)
.comment('Read members in the authorized organization')
.purpose('Review membership without disclosing email addresses').executeForList(tx);
return members.map(member => {
const account = E.teamMembership(member).userAccount().eval();
const explicitRoleCount = E.teamMembership(member).membershipRoleList().size().eval();
if (typeof explicitRoleCount !== 'number' || explicitRoleCount > 3) throw new IamError(403, 'INVALID_ROLE_ASSIGNMENTS');
return { id: E.teamMembership(member).id().eval(), userId: E.teamMembership(member).userAccountId().eval(),
username: account ? E.userAccount(account).githubUsername().eval() : undefined,
explicitRoleCount, isOwner: E.teamMembership(member).userAccountId().eval() ===
E.tenantTeam(access.team).ownerUserId().eval() };
});
});
}
The relation selections also define what the screen needs. The account request selects the GitHub username without the verified email. The role request is bounded per member. The Team's owner is derived from its owner relationship, so the Owner can have zero ordinary role assignments.
The run returned alex-builder, sam-finance and morgan-dev, with explicit role
counts of 0, 1 and 1. Its response objects contain no email addresses. The
query uses generated relation selection instead of an application loop that
issues another query for each member; it does not promise a single physical SQL
statement for the entire graph.
The browser does not get a generic API that accepts arbitrary Q requests. These are server-owned application operations with a deliberately selected result shape.
E makes loading mistakes visible
A missing relationship selection should not silently become an empty result.
E preserves that distinction. We tested the following outcomes with the same
Owner membership:
| What the query loaded | Expression outcome |
|---|---|
| Selected the role list; no ordinary role rows exist | E.teamMembership(member).membershipRoleList().size().eval() returns 0 |
| Did not select the role list | The same expression throws TeaQLNotLoadedError |
Did not select it, but used E.teamMembership(member).membershipRoleList().size().orElse(0) | Still throws; a fallback does not hide NotLoaded |
| Selected username but omitted verified email | Reading E.userAccount(account).verifiedEmail().eval() throws NotLoaded |
This helps distinguish “there is no value” from “the application did not request that value.” The correct repair for an unloaded relationship is to review the query's selector, rather than silently substituting a role count of zero.
E evaluates the loaded data. It does not authorize an account, fetch an omitted relationship, or make arbitrary entity serialization safe. The service must still choose which data it may query and return.
A direct ID must stay inside its Organization
A particularly useful negative test is to authorize Alex for Acme, then supply a membership ID belonging to the other Organization. A lookup by membership ID alone would lose the Team condition. Our example keeps both conditions:
async memberById(principal: Principal, teamId: string, memberId: string) {
return this.runtime.context(principal.userId).transaction(async tx => {
await this.require(tx, principal, teamId, 'iam.members.read');
const member = await Q.teamMemberships().withIdIs(memberId)
.filterByTenantTeam(teamId).filterByMembershipState('1001').limit(1)
.comment('Load one member inside the authorized organization')
.purpose('Prevent a direct member ID escaping organization scope').executeForOne(tx);
if (!member) throw new IamError(404, 'MEMBER_NOT_FOUND');
return { id: E.teamMembership(member).id().eval(),
userId: E.teamMembership(member).userAccountId().eval() };
});
}
That foreign membership ID produces MEMBER_NOT_FOUND within Acme. Asking to list
the other Organization directly is denied for lack of membership. Asking as the
Finance-only member to administer Acme's members is denied for lack of permission.
Those are three different checks: resource scope, Organization access and action
authorization.
The current prototype enforces those checks in the application services. Its
active root is the shared IamPlatform, and its provider request policy is
currently permissive. Setting that root does not automatically isolate customer
Organizations. We are demonstrating tested service-level separation here, not
database row-level security. A mandatory lower-level policy must also cover
relations, aggregates, writes and background jobs before we can make a broader
production isolation claim.
How we used TeaQL
We started with KSML, evaluated the saved model, corrected it, and generated the TypeScript library and Hono application workspace. During implementation, we used TeaQL's model-aware Assist to discover the query and write APIs for the entities and fields involved.
Generated domain files stayed unchanged. Application-owned services implement member administration, owner transfer, and the browser authentication boundary. Queries declare their purpose and have bounded results. Writes carry an audit reason, and the multi-step business operations use transactions.
One small correction was instructive: our initial provider-ID example was inferred
as numeric. We now represent the stable GitHub subject as an opaque string such
as github-user-12345678. Representative values in a model can affect generated
types, so we check those types as part of the workflow.
The interface is TypeScript too. For this local slice, we use a small browser application, Hono, and SQLite. GitHub supplies identity during sign-in; TeaQL then manages an opaque, revocable session. Role checks use current membership data.
Start with SQLite and keep the PostgreSQL path small
SQLite makes the local demo easy to run. TeaQL's TypeScript runtime also provides a PostgreSQL provider, so the application is organized to keep that switch small: replace the provider and connection setup at the composition root while keeping the domain model and most Q/E business code in place. We do not need to rewrite every query as PostgreSQL-specific application SQL.
The current startup uses SQLiteTeaQLClient; PostgreSQL uses
PostgreSQLTeaQLClient. The operational move still includes schema/data migration
and tests for constraints, IDs and concurrent writes. We have verified this IAM
slice on SQLite; its PostgreSQL migration is a later acceptance step.
TypeScript is also a choice for this implementation, rather than a restriction of the model. TeaQL supports six other language families: Java, Rust, Go, Python, C#/.NET and Swift. The same KSML model can generate their native domain libraries, letting builders use the language that fits their application. Business services and integrations still need implementation and tests in that language; we have not built seven versions of this IAM console.
See the language overview and database compatibility guide for each runtime's scope.
Protect data at each place it can escape
Authorization answers who may perform an operation. Data minimization answers which values that operation needs. Diagnostic masking answers which of those values should appear in operational output. We implement those as separate steps.
Keep member emails out of the member query
The member query above uses
Q.userAccountsWithMinimalFields().selectGithubUsername() for its account
relation. The service returns an explicit object with username and role information.
It does not return the account entity wholesale.
We verified that the response contains no email, and that reading the omitted email through E produces NotLoaded. The user's own account endpoint can still return their verified email where account management needs it. This is deliberate access and projection, rather than a blanket claim that emails never leave storage.
Declare sensitive fields in the model
Our account declaration includes:
_audit_mask_fields="verified_email"
The session declares session_digest; the OAuth flow declares state_digest,
browser_digest and proof_challenge. Access-change records declare
previous_summary,next_summary. These declarations carry privacy metadata into
the generated model/runtime. They do not change an authorized database read into
an encrypted or anonymized value.
We tested an actual SQL diagnostic callback while provisioning the fictional
alex-builder account. This is a reduced view of the captured event, retaining
its parameter order:
{
"operation": "insert",
"parameters": [
"1",
"1",
"alex-builder",
"al********************om",
"1001",
1795685407607,
1795685407607,
"github-user-9301",
1
],
"parameterLogPolicies": [
"plain",
"plain",
"plain",
"masked",
"plain",
"plain",
"plain",
"plain",
"plain"
],
"maskedParameters": [
false,
false,
false,
true,
false,
false,
false,
false,
false
],
"logMode": "masked"
}
The fourth parameter is the masked email. Its policy is masked, its mask flag
is true, and the original synthetic email is absent from the captured diagnostics.
This is partial masking: some characters remain visible. It is not anonymous data.
The runtime's rendered SQL also identifies itself as MASKED; NOT REPLAYABLE.
That output is for diagnosis; it is not a statement to copy back into the database.
We ran this check with sensitive plaintext diagnostic permission disabled.
Keep audit intent useful without logging customer values
Every save in these operations supplies an auditAs(...) reason. The default
audit event observed in our callback records entity, action, reason, version and
changed field names. For the account creation it lists verified_email as changed
without including the email value. The test checks that the synthetic email is
absent there while the authorized database read still returns the original value.
The business access-change record is saved with the same transaction as the change it explains. The callback itself is not a durable external audit archive; our runtime defaults to a no-op callback unless a sink is supplied. Production retention and reliable delivery need their own configuration and acceptance checks.
Do not put a customer's model contents, email or credentials in a free-form reason, query comment or exception message. A field-level masking declaration is not a universal scrubber for arbitrary text or third-party logs. Even metadata such as account IDs and action history needs controlled access.
Store a session digest instead of its bearer credential
A successful login issues a random 256-bit session credential. The browser keeps it in an HttpOnly cookie; the database stores a domain-separated SHA-256 digest, its user reference, expiry and revoked state. The GitHub token is used transiently by the login adapter and is not stored in our model.
Logout revokes the server record. HTTPS configuration uses Secure host cookies; state-changing browser requests also require the expected Origin and a CSRF token. The loopback HTTP demonstration is separate from a production HTTPS deployment.
None of those controls encrypts the SQLite database file. Storage and backup encryption, key management, operator access and retention are deployment work that we still need to configure and verify. The local example demonstrates the application behavior, projection and diagnostic masking described above.
Make audit history a business feature
We now persist two kinds of history. access_change_record explains business
changes in an Organization: creation, member and role changes, and the ownership
workflow. authentication_event records login start, success, failure, cancellation
and logout, with outcome, fixed reason code, authentication method, request
reference and time. It has an optional account relation because a failed OAuth
callback may not have established any identity.
Successful business changes and their records commit together. Session creation and its login-success record also share a transaction; logout revocation and its record do the same. A failed transaction must leave neither a partial business change nor a misleading success record.
The Organization's IAM audit page requires current Owner/Admin permission and always scopes the query by Team. Personal login history derives the account from the verified session. Owning an Organization does not grant access to colleagues' login histories. Both views support bounded, newest-first pagination and exact action-code filtering, with no public mutation API for the records.
Authentication events have no token, cookie, OAuth code, verifier, email, IP or
user-agent payload fields. Anonymous failures stay anonymous rather than trusting
a browser-supplied account identity. A trusted operator view for those events is
separate future work; they are not exposed to Organization members. Local demo
sign-ins are explicitly labelled LOCAL_DEMO rather than presented as live GitHub
authorization.
This is append-only behavior through these application APIs. It does not provide
cryptographic tamper evidence or prevent database operators from changing storage.
Retention, archive delivery and anonymous-event volume limits remain operational
work. The read endpoints are GET /v1/teams/:teamId/audit-log and
GET /v1/me/login-events; the server derives authorization from the current session.
What another SaaS builder can take away
Start with these relationships and rules, even if you use a different stack:
- Keep account identity separate from membership in an Organization.
- Put role assignments on the membership so access can differ by Organization.
- Give ownership a dedicated relationship and an explicit transfer workflow.
- Define combined roles and the limits of an Admin's authority.
- Check the requested Organization again when reading or changing its resources.
Then write the failure cases alongside the successful scenario. Can an Admin grant Finance? Can a recipient accept after removal and rejoining? Can a member submit an ID from another Organization? Does transferring one Organization affect another? Does the old session still work after logout?
These cases are part of the design. They make “supports teams” mean something specific enough to implement and review.
What comes next
We now have a local Organization workflow to build on. Next we need to verify GitHub against the configured OAuth App, then connect Paddle Sandbox events to Organization entitlements. Production deployment also needs its own operational checks beyond this SQLite demo.
For Day 1, the useful artifacts are the IAM model, executable Q/E examples, and permission, ownership and data-protection rules. Download the Query/E source excerpt, retained query results, and checksums alongside the model above. These are reference materials, not a standalone starter; the reference notes describe the dependencies. We will link the complete runnable application once its distribution is ready.
Follow the series under TeaQL SaaS.
