@ultimat3/cli 31.23.0 → 31.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +4 -2
- package/README.md +1 -0
- package/package.json +29 -29
- package/src/cmd-db-recount.ts +81 -24
- package/src/cmd-db-spec.ts +9 -1
- package/src/cmd-db.ts +1 -0
- package/src/cmd-doctor.ts +7 -1
- package/src/cmd-generate-spec.ts +3 -2
- package/src/cmd-generate.ts +4 -0
- package/src/db-diagnostics.ts +6 -0
- package/src/db-generate.ts +14 -3
- package/src/doctor-guards.ts +5 -3
- package/src/doctor-redundant-indexes.ts +76 -0
- package/src/fix-sequence.ts +0 -1
- package/src/framework-schema.ts +5 -4
- package/src/generate-files.ts +10 -0
- package/src/generate-invite.ts +195 -0
- package/src/generate-kinds.ts +4 -0
- package/src/messages.ts +3 -0
- package/src/metrics-endpoint.ts +5 -3
- package/src/redundant-indexes.ts +101 -0
- package/src/retained-assets-boot.ts +28 -15
- package/src/role-replicator.ts +26 -4
- package/src/role-start.ts +13 -0
- package/src/runtime-boot-warnings.ts +65 -0
- package/src/runtime-cache.ts +14 -8
- package/src/runtime-liveness.ts +23 -0
- package/src/schema-drift.ts +5 -2
- package/src/serve-boot-warnings.ts +9 -8
- package/src/serve.ts +4 -1
- package/src/templates/guard-error-declared.ts +48 -11
- package/src/templates/guard-repo-unbounded.ts +29 -13
- package/src/templates/invite-pages.ts +151 -0
- package/src/templates/invite-tests.ts +228 -0
- package/src/templates/invite.ts +293 -0
- package/src/templates/scaffold-container-compose.ts +3 -2
- package/src/templates/scaffold-guards.ts +26 -3
- package/src/templates/scaffold-helm-templates.ts +1 -1
- package/src/templates/scaffold-repo.ts +1 -0
- package/wiki/Auth.md +24 -0
- package/wiki/Building-Your-Own-Base.md +20 -0
- package/wiki/CLI-Reference.md +7 -1
- package/wiki/Entities-And-Migrations.md +6 -2
- package/wiki/FAQ.md +2 -2
- package/wiki/Home.md +1 -1
- package/wiki/Jobs-And-Workflows.md +8 -6
- package/wiki/Known-Gaps.md +1 -2
- package/wiki/Migrations-And-Backfills.md +1 -1
- package/wiki/Observability.md +2 -1
- package/wiki/Outbound-HTTP.md +40 -0
- package/wiki/Policies-And-Authz.md +52 -20
- package/wiki/Realtime.md +18 -1
- package/wiki/Scheduled-Tasks.md +1 -1
- package/wiki/Shapes.md +3 -2
- package/wiki/Testing.md +1 -0
- package/wiki/Tutorial-04-Jobs-And-Realtime.md +1 -1
- package/wiki/Upgrading.md +2 -0
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
// `x g invite`: the member invite as the app's own actions over `@ultimat3/auth`'s
|
|
2
|
+
// `defineMemberInvite` — the flow, its mail, the one permission it needs, three actions, and the
|
|
3
|
+
// two native-form pages that post at them. The framework holds the link to one org, one address
|
|
4
|
+
// and one use; who may invite, and what a joiner becomes, are these files' — the app's to edit.
|
|
5
|
+
|
|
6
|
+
import { catalogJson } from './catalog-json';
|
|
7
|
+
import { INVITE_CATALOG, invitePageSource, invitePageTest } from './invite-pages';
|
|
8
|
+
import {
|
|
9
|
+
acceptInviteTest,
|
|
10
|
+
inviteMemberTest,
|
|
11
|
+
inviteModuleTest,
|
|
12
|
+
revokeInviteTest,
|
|
13
|
+
} from './invite-tests';
|
|
14
|
+
import { catalogPath } from './locales';
|
|
15
|
+
import type { GeneratedFile } from './naming';
|
|
16
|
+
import { authModule } from './scaffold-auth';
|
|
17
|
+
import { AUTH_DIR } from './sign-in-shared';
|
|
18
|
+
|
|
19
|
+
export interface InviteTemplateOptions {
|
|
20
|
+
readonly locales: readonly string[];
|
|
21
|
+
/** The app's `@<app>/i18n`; absent, the pages import `t` from `@ultimat3/i18n`. */
|
|
22
|
+
readonly catalogModule?: string | undefined;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The inviter's page, and where the mailed link lands beneath it. */
|
|
26
|
+
export const INVITES_PATH = '/auth/invites';
|
|
27
|
+
export const INVITE_ACCEPT_PATH = `${INVITES_PATH}/accept`;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The app's catalog module, imported for its effect: \`defineCatalogs()\` runs on import, and the
|
|
31
|
+
* mail resolves its keys against what is registered when it renders. Nothing else this file pulls
|
|
32
|
+
* in is guaranteed to have imported it — a mail sent from a worker or a test rendered raw keys.
|
|
33
|
+
*/
|
|
34
|
+
const catalogImport = (module: string | undefined): string =>
|
|
35
|
+
module === undefined
|
|
36
|
+
? ''
|
|
37
|
+
: `// Registers the app's catalog: the mail below renders its keys against it.\nimport '${module}';\n`;
|
|
38
|
+
|
|
39
|
+
const moduleSource = (
|
|
40
|
+
module: string | undefined,
|
|
41
|
+
): string => `// The member invite: one declaration of the flow, the mail it sends and the link it carries.
|
|
42
|
+
// \`defineMemberInvite\` binds each link to ONE org and ONE address, single-use and expiring; the
|
|
43
|
+
// actions beside this file are the app's policy over it.
|
|
44
|
+
${catalogImport(module)}import { defineMemberInvite, type MailSender } from '@ultimat3/auth';
|
|
45
|
+
import { EnvMissingError } from '@ultimat3/core';
|
|
46
|
+
import { setRedirect, useRequestHeader } from '@ultimat3/http';
|
|
47
|
+
import { blocks, defineMail, send, t } from '@ultimat3/mail';
|
|
48
|
+
|
|
49
|
+
/** A week: long enough to survive a holiday, short enough that a stale inbox is not a door. */
|
|
50
|
+
export const INVITE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
51
|
+
/** The inviter's page, and the invitee's beneath it. */
|
|
52
|
+
export const INVITES_PATH = '${INVITES_PATH}';
|
|
53
|
+
export const INVITE_ACCEPT_PATH = '${INVITE_ACCEPT_PATH}';
|
|
54
|
+
/** Where a joiner lands. The app's to move. */
|
|
55
|
+
export const AFTER_JOIN = '/dashboard';
|
|
56
|
+
|
|
57
|
+
export const inviteMail = defineMail({
|
|
58
|
+
id: 'auth.invite',
|
|
59
|
+
subject: 'app.auth.inviteMail.subject',
|
|
60
|
+
input: t.object({ link: t.string }),
|
|
61
|
+
template: ({ data }) => [
|
|
62
|
+
blocks.paragraph('app.auth.inviteMail.body'),
|
|
63
|
+
blocks.button('app.auth.inviteMail.cta', data.link),
|
|
64
|
+
],
|
|
65
|
+
preview: { link: 'https://app.example${INVITE_ACCEPT_PATH}?orgId=preview&token=preview' },
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
export const memberInvite = defineMemberInvite({ template: inviteMail.id, ttlMs: INVITE_TTL_MS });
|
|
69
|
+
|
|
70
|
+
/** The flow hands over the address and the link; this mail is what reaches the inbox. */
|
|
71
|
+
export const inviteMailer: MailSender = {
|
|
72
|
+
async send(_template, to, data, locale) {
|
|
73
|
+
const link = typeof data.link === 'string' ? data.link : '';
|
|
74
|
+
await send(inviteMail, { link }, { to, locale });
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* The origin a mailed link is built on: \`APP_URL\`, declared. Never the request's own — that is
|
|
80
|
+
* the \`Host\` header, which the caller writes, so a link built from it is a phishing link sent
|
|
81
|
+
* from this app's own address. With none declared there is no link to mail.
|
|
82
|
+
*/
|
|
83
|
+
export const appOrigin = (env: Readonly<Record<string, string | undefined>> = Bun.env): URL => {
|
|
84
|
+
const declared = (env.APP_URL ?? '').trim();
|
|
85
|
+
if (declared === '') {
|
|
86
|
+
throw new EnvMissingError({
|
|
87
|
+
cause: 'APP_URL is not set, so there is no declared origin to build the invite link from',
|
|
88
|
+
fix: 'export APP_URL=http://localhost:3000 # the origin this app is served from',
|
|
89
|
+
meta: { key: 'APP_URL' },
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
return new URL(declared);
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
/** The accept page's absolute URL, carrying the org and the token: accept needs both. */
|
|
96
|
+
export const inviteLink =
|
|
97
|
+
(origin: URL, orgId: string) =>
|
|
98
|
+
(token: string): string => {
|
|
99
|
+
const url = new URL(INVITE_ACCEPT_PATH, origin);
|
|
100
|
+
url.search = new URLSearchParams({ orgId, token }).toString();
|
|
101
|
+
return url.href;
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
/** A browser that posted the native form gets a 303; an agent posting JSON gets the path as data. */
|
|
105
|
+
export const landAt = (path: string): string => {
|
|
106
|
+
if ((useRequestHeader('accept') ?? '').includes('text/html')) setRedirect(path);
|
|
107
|
+
return path;
|
|
108
|
+
};
|
|
109
|
+
`;
|
|
110
|
+
|
|
111
|
+
const policySource =
|
|
112
|
+
(): string => `// Who may invite into — and remove from — their own org: one permission, which \`x g invite\`
|
|
113
|
+
// granted to \`admin\`. Seat limits and which roles a joiner gets are this app's: add them here.
|
|
114
|
+
import { can, definePermissions } from '@ultimat3/policy';
|
|
115
|
+
|
|
116
|
+
declare module '@ultimat3/policy' {
|
|
117
|
+
interface PermissionRegistry {
|
|
118
|
+
'member:invite': true;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export const invitePermissions = definePermissions(['member:invite']);
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* The org is the actor's own, never an input: the tenancy rule is that the actor HAS one. It also
|
|
126
|
+
* gates \`revokeInvite\`, which removes an address that joined through an invite — and only such an
|
|
127
|
+
* address (\`defineMemberInvite\`'s revoke never touches a member who did not). Who may remove
|
|
128
|
+
* whom beyond that — an owner nobody may remove, a seat that must stay filled — is this app's:
|
|
129
|
+
* give \`revokeInvite\` its own rule here, \`can<{ email: string }>('member:invite', …)\`.
|
|
130
|
+
*/
|
|
131
|
+
export const canInvite = can(
|
|
132
|
+
'member:invite',
|
|
133
|
+
({ actor }) => actor !== null && typeof actor.orgId === 'string' && actor.orgId !== '',
|
|
134
|
+
);
|
|
135
|
+
`;
|
|
136
|
+
|
|
137
|
+
const inviteMemberSource =
|
|
138
|
+
(): string => `// Invite a person into the actor's org: a single-use link, mailed in the inviter's locale. Asking
|
|
139
|
+
// again for the same address is the resend — the new link replaces the old one.
|
|
140
|
+
import { action, t } from '@ultimat3/action';
|
|
141
|
+
import { authForbidden } from '@ultimat3/auth';
|
|
142
|
+
import { appAuth } from '../auth';
|
|
143
|
+
import { appOrigin, INVITES_PATH, inviteLink, inviteMailer, landAt, memberInvite } from '../invite';
|
|
144
|
+
import { canInvite } from '../policy';
|
|
145
|
+
|
|
146
|
+
export const inviteMember = action({
|
|
147
|
+
input: t.object({ email: t.email }),
|
|
148
|
+
output: t.object({ ok: t.boolean, next: t.string }),
|
|
149
|
+
policy: canInvite,
|
|
150
|
+
// Mailing a person is a browser operation here; an app that wants it as a tool exposes it.
|
|
151
|
+
mcp: { expose: false },
|
|
152
|
+
async handle({ input, ctx }) {
|
|
153
|
+
const orgId = ctx.actor.orgId;
|
|
154
|
+
if (typeof orgId !== 'string' || orgId === '') {
|
|
155
|
+
throw authForbidden('POST inviteMember', 'the actor belongs to no org');
|
|
156
|
+
}
|
|
157
|
+
await memberInvite.invite(appAuth(), inviteMailer, {
|
|
158
|
+
orgId,
|
|
159
|
+
email: input.email,
|
|
160
|
+
locale: ctx.locale,
|
|
161
|
+
link: inviteLink(appOrigin(), orgId),
|
|
162
|
+
});
|
|
163
|
+
return { ok: true, next: landAt(INVITES_PATH) };
|
|
164
|
+
},
|
|
165
|
+
});
|
|
166
|
+
`;
|
|
167
|
+
|
|
168
|
+
const acceptInviteSource =
|
|
169
|
+
(): string => `// Accept an invite: the signed-in account joins the org the link names. The link is the
|
|
170
|
+
// credential — \`accept\` consumes it only under this account's own address, so a forwarded link
|
|
171
|
+
// joins nobody — and the session is rotated, because membership is a privilege change.
|
|
172
|
+
import { action, t } from '@ultimat3/action';
|
|
173
|
+
import { authUnauthenticated, verifySession } from '@ultimat3/auth';
|
|
174
|
+
import { isAnonymous } from '@ultimat3/core';
|
|
175
|
+
import { useRequestContext, useRequestCookie } from '@ultimat3/http';
|
|
176
|
+
import { allow } from '@ultimat3/policy';
|
|
177
|
+
import { appAuth } from '../auth';
|
|
178
|
+
import { AFTER_JOIN, landAt, memberInvite } from '../invite';
|
|
179
|
+
|
|
180
|
+
export const acceptInvite = action({
|
|
181
|
+
input: t.object({ orgId: t.uuid, token: t.string.min(1).max(256) }),
|
|
182
|
+
output: t.object({ ok: t.boolean, next: t.string }),
|
|
183
|
+
// Public by declaration: the invitee holds no permission yet. The link is what authorises, and
|
|
184
|
+
// the handler refuses an anonymous caller before it reads it.
|
|
185
|
+
policy: allow('invite-link'),
|
|
186
|
+
mcp: { expose: false },
|
|
187
|
+
async handle({ input, ctx }) {
|
|
188
|
+
if (isAnonymous(ctx.actor)) throw authUnauthenticated('POST acceptInvite');
|
|
189
|
+
const auth = appAuth();
|
|
190
|
+
const cookie = useRequestCookie(auth.sessions.policy.cookieName);
|
|
191
|
+
const session =
|
|
192
|
+
cookie === null || cookie === '' ? undefined : await verifySession(auth.sessions, cookie);
|
|
193
|
+
const joined = await memberInvite.accept(auth, {
|
|
194
|
+
orgId: input.orgId,
|
|
195
|
+
token: input.token,
|
|
196
|
+
userId: ctx.actor.id,
|
|
197
|
+
session,
|
|
198
|
+
});
|
|
199
|
+
if (joined.cookie !== undefined) {
|
|
200
|
+
useRequestContext('acceptInvite').headers.append('set-cookie', joined.cookie);
|
|
201
|
+
}
|
|
202
|
+
return { ok: true, next: landAt(AFTER_JOIN) };
|
|
203
|
+
},
|
|
204
|
+
});
|
|
205
|
+
`;
|
|
206
|
+
|
|
207
|
+
const revokeInviteSource =
|
|
208
|
+
(): string => `// Withdraw an invite from the actor's org: the link dies, and an address that already joined
|
|
209
|
+
// leaves the org with every session it held.
|
|
210
|
+
import { action, t } from '@ultimat3/action';
|
|
211
|
+
import { authForbidden } from '@ultimat3/auth';
|
|
212
|
+
import { appAuth } from '../auth';
|
|
213
|
+
import { INVITES_PATH, landAt, memberInvite } from '../invite';
|
|
214
|
+
import { canInvite } from '../policy';
|
|
215
|
+
|
|
216
|
+
export const revokeInvite = action({
|
|
217
|
+
input: t.object({ email: t.email }),
|
|
218
|
+
output: t.object({ ok: t.boolean, next: t.string, memberRemoved: t.boolean }),
|
|
219
|
+
policy: canInvite,
|
|
220
|
+
mcp: { expose: false },
|
|
221
|
+
async handle({ input, ctx }) {
|
|
222
|
+
const orgId = ctx.actor.orgId;
|
|
223
|
+
if (typeof orgId !== 'string' || orgId === '') {
|
|
224
|
+
throw authForbidden('POST revokeInvite', 'the actor belongs to no org');
|
|
225
|
+
}
|
|
226
|
+
const revoked = await memberInvite.revoke(appAuth(), {
|
|
227
|
+
orgId,
|
|
228
|
+
email: input.email,
|
|
229
|
+
reason: \`revokeInvite by \${ctx.actor.id}\`,
|
|
230
|
+
});
|
|
231
|
+
const next = landAt(INVITES_PATH);
|
|
232
|
+
return { ok: true, next, memberRemoved: revoked.memberRemoved };
|
|
233
|
+
},
|
|
234
|
+
});
|
|
235
|
+
`;
|
|
236
|
+
|
|
237
|
+
/** The exercise pass draws inputs and actors; none of these three can run on drawn ones. */
|
|
238
|
+
const off = (name: string, why: string) => ({ name, value: `{ off: '${why}' }` });
|
|
239
|
+
|
|
240
|
+
export function inviteFiles(options: InviteTemplateOptions): readonly GeneratedFile[] {
|
|
241
|
+
const module = options.catalogModule;
|
|
242
|
+
return [
|
|
243
|
+
{ path: `${AUTH_DIR}/invite.ts`, contents: moduleSource(module) },
|
|
244
|
+
{ path: `${AUTH_DIR}/invite.test.ts`, contents: inviteModuleTest() },
|
|
245
|
+
{ path: `${AUTH_DIR}/policy.ts`, contents: policySource() },
|
|
246
|
+
{
|
|
247
|
+
path: `${AUTH_DIR}/actions/invite-member.ts`,
|
|
248
|
+
contents: inviteMemberSource(),
|
|
249
|
+
exercise: off('inviteMember', 'mails a link; the pass holds no actor in an org'),
|
|
250
|
+
},
|
|
251
|
+
{ path: `${AUTH_DIR}/actions/invite-member.test.ts`, contents: inviteMemberTest() },
|
|
252
|
+
{
|
|
253
|
+
path: `${AUTH_DIR}/actions/accept-invite.ts`,
|
|
254
|
+
contents: acceptInviteSource(),
|
|
255
|
+
exercise: off('acceptInvite', 'needs a live mailed token; the pass draws one nobody issued'),
|
|
256
|
+
},
|
|
257
|
+
{ path: `${AUTH_DIR}/actions/accept-invite.test.ts`, contents: acceptInviteTest() },
|
|
258
|
+
{
|
|
259
|
+
path: `${AUTH_DIR}/actions/revoke-invite.ts`,
|
|
260
|
+
contents: revokeInviteSource(),
|
|
261
|
+
exercise: off('revokeInvite', 'removes a member; the pass holds no actor in an org'),
|
|
262
|
+
},
|
|
263
|
+
{ path: `${AUTH_DIR}/actions/revoke-invite.test.ts`, contents: revokeInviteTest() },
|
|
264
|
+
{ path: `${AUTH_DIR}/invites/page.tsx`, contents: invitePageSource(module, 'manage') },
|
|
265
|
+
{ path: `${AUTH_DIR}/invites/page.test.ts`, contents: invitePageTest(module, 'manage') },
|
|
266
|
+
{ path: `${AUTH_DIR}/invites/accept/page.tsx`, contents: invitePageSource(module, 'accept') },
|
|
267
|
+
{
|
|
268
|
+
path: `${AUTH_DIR}/invites/accept/page.test.ts`,
|
|
269
|
+
contents: invitePageTest(module, 'accept'),
|
|
270
|
+
},
|
|
271
|
+
{ path: `${AUTH_DIR}/invites/page.module.scss`, contents: STYLE },
|
|
272
|
+
// Every action above imports `../auth`; an app from before `x new` wrote it gets it here.
|
|
273
|
+
{ path: `${AUTH_DIR}/auth.ts`, contents: authModule(), merge: 'if-absent' },
|
|
274
|
+
...options.locales.map((locale) => ({
|
|
275
|
+
path: catalogPath(locale),
|
|
276
|
+
contents: catalogJson(INVITE_CATALOG),
|
|
277
|
+
merge: 'json' as const,
|
|
278
|
+
})),
|
|
279
|
+
];
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
const STYLE = `// Semantic tokens only: a raw colour here is refused by guards/raw-colour.ts.
|
|
283
|
+
@use '@ultimat3/ui/tokens' as tokens;
|
|
284
|
+
|
|
285
|
+
.page {
|
|
286
|
+
display: grid;
|
|
287
|
+
gap: tokens.space(4);
|
|
288
|
+
max-width: 28rem;
|
|
289
|
+
margin-inline: auto;
|
|
290
|
+
padding: tokens.space(6);
|
|
291
|
+
color: tokens.role('fg');
|
|
292
|
+
}
|
|
293
|
+
`;
|
|
@@ -71,9 +71,10 @@ x-image: &image
|
|
|
71
71
|
# The image's own HEALTHCHECK fetches \`/readyz\` on $PORT, and only \`web\` and \`sync\` open an HTTP
|
|
72
72
|
# socket — every other role gets the scrape listener and nothing else. A service that inherits that
|
|
73
73
|
# probe is fetching a port it never binds: it reports \`unhealthy\` for its whole life and anything
|
|
74
|
-
# gated on it never starts. Probes follow the role here, exactly as they do in \`docker/helm
|
|
74
|
+
# gated on it never starts. Probes follow the role here, exactly as they do in \`docker/helm\`:
|
|
75
|
+
# \`/healthz\`, the one path on the scrape listener that reads the loops' heartbeats.
|
|
75
76
|
x-metrics-probe: &metrics-probe
|
|
76
|
-
test: ['CMD', 'bun', '--eval', "fetch('http://127.0.0.1:'+(process.env.METRICS_PORT||9090)+'/
|
|
77
|
+
test: ['CMD', 'bun', '--eval', "fetch('http://127.0.0.1:'+(process.env.METRICS_PORT||9090)+'/healthz').then(r=>process.exit(r.ok?0:1),()=>process.exit(1))"]
|
|
77
78
|
interval: 10s
|
|
78
79
|
timeout: 3s
|
|
79
80
|
start_period: 30s
|
|
@@ -25,8 +25,9 @@
|
|
|
25
25
|
// about the TAB: an island polls with `visibleInterval()`, which a hidden tab and a lost session stop.
|
|
26
26
|
// One is about the QUESTION: a destructive act asks through `ConfirmDialog`, never `confirm(`.
|
|
27
27
|
// One is about the POOL: a database call per row runs through `mapBounded`, never all at once.
|
|
28
|
-
// Two more are about the REPO, REPORT ONLY (`severity: 'warning'`)
|
|
29
|
-
//
|
|
28
|
+
// Two more are about the REPO: an `await` per turn of a loop, REPORT ONLY (`severity: 'warning'`)
|
|
29
|
+
// until the apps are clean of it, and a `.all()` that says no bound — failing the gate in an app
|
|
30
|
+
// scaffolded from 31.23 on, while an older app keeps the report-only copy it was given.
|
|
30
31
|
|
|
31
32
|
import { animatedLayoutPropertyGuardFiles } from './guard-animated-layout-property';
|
|
32
33
|
import { bareErrorGuardFiles } from './guard-bare-error';
|
|
@@ -80,7 +81,7 @@ const SHIPPED: readonly (readonly [string, () => readonly GeneratedFile[]])[] =
|
|
|
80
81
|
['raw-z-index', rawZIndexGuardFiles],
|
|
81
82
|
['repo-await-in-loop', repoAwaitInLoopGuardFiles],
|
|
82
83
|
['repo-raw-sql', repoRawSqlGuardFiles],
|
|
83
|
-
['repo-unbounded', repoUnboundedGuardFiles],
|
|
84
|
+
['repo-unbounded', () => repoUnboundedGuardFiles('error')],
|
|
84
85
|
['semantic-interactive', semanticInteractiveGuardFiles],
|
|
85
86
|
['unbounded-fanout', unboundedFanoutGuardFiles],
|
|
86
87
|
['undeclared-custom-property', undeclaredCustomPropertyGuardFiles],
|
|
@@ -111,6 +112,28 @@ export const shippedGuardSource = (name: string): string | undefined => {
|
|
|
111
112
|
return typeof contents === 'string' ? contents : undefined;
|
|
112
113
|
};
|
|
113
114
|
|
|
115
|
+
/**
|
|
116
|
+
* A shipped guard's earlier form that still counts as current for an app holding it: the template
|
|
117
|
+
* moved for NEW apps only. `repo-unbounded` became failing in 31.23; an app scaffolded before keeps
|
|
118
|
+
* its report-only copy, and `x doctor` must not call that copy stale.
|
|
119
|
+
*/
|
|
120
|
+
const ALSO_CURRENT: Readonly<Record<string, () => readonly GeneratedFile[]>> = {
|
|
121
|
+
'repo-unbounded': () => repoUnboundedGuardFiles('warning'),
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Every rule-file text that reads as current for a shipped guard — the template first, then any
|
|
126
|
+
* earlier form an existing app is allowed to keep. Empty when the name was never shipped.
|
|
127
|
+
*/
|
|
128
|
+
export const shippedGuardSources = (name: string): readonly string[] => {
|
|
129
|
+
const current = shippedGuardSource(name);
|
|
130
|
+
if (current === undefined) return [];
|
|
131
|
+
const earlier = (Object.hasOwn(ALSO_CURRENT, name) ? ALSO_CURRENT[name] : undefined)?.().find(
|
|
132
|
+
(file) => file.path === `guards/${name}.ts`,
|
|
133
|
+
);
|
|
134
|
+
return typeof earlier?.contents === 'string' ? [current, earlier.contents] : [current];
|
|
135
|
+
};
|
|
136
|
+
|
|
114
137
|
/**
|
|
115
138
|
* Every guard `x new` ships, each with its test. One module per guard, because an app deletes a
|
|
116
139
|
* rule it does not want by deleting one file — and a guard the app then writes for itself is
|
|
@@ -167,7 +167,7 @@ nobody bound. Derived here rather than stated twice in values.yaml, where the tw
|
|
|
167
167
|
periodSeconds: 5
|
|
168
168
|
{{- end }}
|
|
169
169
|
livenessProbe:
|
|
170
|
-
httpGet: { path: /
|
|
170
|
+
httpGet: { path: /healthz, port: metrics }
|
|
171
171
|
periodSeconds: 15
|
|
172
172
|
failureThreshold: 4
|
|
173
173
|
{{- /*
|
|
@@ -98,6 +98,7 @@ const rootPackage = (app: NameSet, version: string): string => `{
|
|
|
98
98
|
"@ultimat3/http": "^${version}",
|
|
99
99
|
"@ultimat3/i18n": "^${version}",
|
|
100
100
|
"@ultimat3/jobs": "^${version}",
|
|
101
|
+
"@ultimat3/mail": "^${version}",
|
|
101
102
|
"@ultimat3/mcp": "^${version}",
|
|
102
103
|
"@ultimat3/money": "^${version}",
|
|
103
104
|
"@ultimat3/policy": "^${version}",
|
package/wiki/Auth.md
CHANGED
|
@@ -218,6 +218,30 @@ const approved = await verifyPasskeyEvidence(evidence, { rpId: 'example.com', or
|
|
|
218
218
|
| service-to-service | `verifyWorkloadToken` reads a Kubernetes service-account token, a SPIFFE JWT-SVID or a cloud IMDS token (they are all one JWT); `actorFromService` gives a `kind: 'service'` actor. The returned `WorkloadToken` carries `raw`, the whole decoded payload, read only after every check held. mTLS is the mesh's job |
|
|
219
219
|
| an external issuer's bearer (`As of 2026-11`) | `jwtBearerResolver({ keys, issuers, audience, requiredScope?, accept?, actorOf })` — `apiKeyResolver`'s twin for JWTs, the `resolveToken` a bearer mount and `defineAppMcp()` take. `keys` is a thunk read when a token arrives (no discovery at import); `accept(raw)` is the app's own claim check after the signature; `actorOf(token)` builds the actor. Every refusal — signature, issuer, audience, expiry, scope, `accept`, and a key set that cannot be read — is `null` plus one `auth.jwt_bearer.refused` log line naming the check, never a claim's value. The mount answers that `null` as `401 X_UNAUTHENTICATED` |
|
|
220
220
|
|
|
221
|
+
## Member invites
|
|
222
|
+
|
|
223
|
+
`As of 2026-11-14`. `defineMemberInvite({ name?, template, ttlMs })` declares the flow once, at
|
|
224
|
+
module scope, over a verification purpose (default name `member-invite`) and the user's one
|
|
225
|
+
`orgId`. It ships the structural half; who may invite, seat limits and the roles an invite offers
|
|
226
|
+
are the app's `policy` and the app's wrapper action.
|
|
227
|
+
|
|
228
|
+
| Call | What the framework guarantees |
|
|
229
|
+
|---|---|
|
|
230
|
+
| `flow.invite(auth, mail, { orgId, email, locale, link?, data? })` | a single-use token, hashed at rest, living `ttlMs`, keyed on the **pair** (tenant, normalised address) and mailed to the address. Re-inviting the pair is the resend: it supersedes the earlier link, so one live link per pair. A blank `orgId` is `X_FORBIDDEN` before anything is written. `link` must carry `orgId`: accept needs it |
|
|
231
|
+
| `flow.accept(auth, { orgId, token, userId, roles?, session? })` | the token is consumed under (that tenant, **the signed-in account's own address**), so a link aimed at another tenant or forwarded to another account finds no row and stays live for its invitee. Success sets `orgId`, replaces `roles` with what the wrapper passed (default none), clears direct `permissions`, stamps `emailVerifiedAt` (the link proved the inbox), and rotates `session` through `updatePrivileges` — set the returned `cookie`. An unknown or disabled account gets the bad-link refusal word for word, under the flow's own purpose name |
|
|
232
|
+
| `flow.revoke(auth, { orgId, email, reason })` | logs `auth.revocation` first and kills the pending link. It removes a membership **only one this invite flow granted** — the address joined this tenant by redeeming an invite (`orgId`, `roles`, `permissions` cleared, every session ended). A founder, a seeded admin, a member who was already in the org when they redeemed a link, or a member of another tenant is never touched: who else may be removed is the app's. A revoke racing an accept wins — the accept that loses is refused and leaves nobody joined |
|
|
233
|
+
|
|
234
|
+
| Refusal | Code |
|
|
235
|
+
|---|---|
|
|
236
|
+
| expired, already used, superseded, revoked, another tenant's, another account's, unknown or disabled account | `X_UNAUTHENTICATED` — one code and one cause for all of them, as every mailed credential: telling them apart tells a caller which address has a live invite |
|
|
237
|
+
| the account is a member of another tenant | `X_FORBIDDEN`, checked before the consume so the link survives a move. Membership is one tenant per account (`x_users.org_id`); moving is the app's own `updatePrivileges` call |
|
|
238
|
+
|
|
239
|
+
The flow is functions, not actions: `@ultimat3/auth` is tier 2 and cannot import
|
|
240
|
+
`@ultimat3/action`. Wrap each call in the app's own `action()` with the app's policy — the shape
|
|
241
|
+
`x g sign-in` writes for `login()`; `x g invite` writes those three actions, their policy and the two pages
|
|
242
|
+
([CLI reference](CLI-Reference#x-g)). Proof: `bun test ./packages/auth/src/member-invite.test.ts`,
|
|
243
|
+
including a seeded property test that an invite for tenant X never yields membership in Y.
|
|
244
|
+
|
|
221
245
|
## Authorization server
|
|
222
246
|
|
|
223
247
|
`As of 2026-11`. `authorizationServer({ issuer, store, consentPath, lifetimes, scopes, registration?, grants?, resources? })`
|
|
@@ -178,6 +178,26 @@ A **starter** (a whole app shape, not a factory) is not a package: it is a repos
|
|
|
178
178
|
copies, and its README says so. Once one exists, a community list is a wiki page added by pull
|
|
179
179
|
request.
|
|
180
180
|
|
|
181
|
+
## Recipe: a PIN for a shared device
|
|
182
|
+
|
|
183
|
+
Decided 2026-11-14 (plan 101, owner decision OD6): a PIN or device-operator sign-in is **a recipe,
|
|
184
|
+
not a framework method**. One adopter needed it, in two files, and every rule it needs already
|
|
185
|
+
ships. A shared device (a till, a kiosk, a shop-floor tablet) signs in once as a device account;
|
|
186
|
+
an operator then proves who they are with a short PIN, and that browser's session becomes theirs.
|
|
187
|
+
|
|
188
|
+
| Piece | Where it lives | What it calls |
|
|
189
|
+
|---|---|---|
|
|
190
|
+
| the device account | an `x_users` row with the app's own `device` role, signed in by the normal sign-in | `login()` |
|
|
191
|
+
| the operator's PIN | the app's own entity (`operators`: `userId`, `pinHash`), never `x_users.password_hash` — a PIN is weaker than the password policy allows (`X_PASSWORD_WEAK`) | `hashPassword(pin)` on enrolment |
|
|
192
|
+
| the lockout | **before** the KDF, keyed per operator and per device: a 4-digit PIN is 10 000 guesses, so the budget is the whole defence | `appAuth().limiter.reserve('pin:<operatorId>:<deviceId>')` — `X_ACCOUNT_LOCKED` refuses; `recordSuccess` on a match |
|
|
193
|
+
| the check | constant cost whether or not the operator exists | `verifyPassword({ hash: row?.pinHash ?? null, password: pin })` |
|
|
194
|
+
| the switch | a session for the operator, capped at the device session's ceiling, set as that browser's cookie; signing the operator out lands on the device sign-in again | `createSession(appAuth().sessions, { userId: operator.userId, absoluteExpiresAt: device.absoluteExpiresAt })`, then `sessionCookie(issued.token, appAuth().sessions.policy)` on the response |
|
|
195
|
+
| who may switch | the app's policy on its own `switchOperator` action: the caller holds the `device` role | `can('operator:switch', …)` |
|
|
196
|
+
|
|
197
|
+
The action is the app's (`apps/web/app/operators/actions/switch-operator.ts`), so it projects like
|
|
198
|
+
any other — route, typed client, MCP tool, contract test. Nothing in the framework learns that a PIN
|
|
199
|
+
exists, which is the point: the next app's PIN rules (length, rotation, which devices) are its own.
|
|
200
|
+
|
|
181
201
|
## The honest limit
|
|
182
202
|
|
|
183
203
|
**The registry cannot tell that an entity came from your factory, and that erasure is the feature.**
|
package/wiki/CLI-Reference.md
CHANGED
|
@@ -321,6 +321,7 @@ x g island <name> [--at <dir>] # a client component on an otherwise
|
|
|
321
321
|
x g admin:page <name> --permission <perm> [--at <dir>] # a custom admin screen, guarded by construction
|
|
322
322
|
x g guard <name> # a convention this app enforces, as a build error
|
|
323
323
|
x g sign-in --password | --oidc <provider> # the app's one sign-in: pages, actions, boot guard
|
|
324
|
+
x g invite # the member invite: three actions and two pages over defineMemberInvite
|
|
324
325
|
x g chart-alerts [--print] # the chart's ServiceMonitor + alert rules, backfilled
|
|
325
326
|
x g chart-dashboard [--print] # the chart's Grafana dashboard + its ConfigMap, backfilled
|
|
326
327
|
x g app <name> # one more app workspace: apps/<name>/
|
|
@@ -338,6 +339,8 @@ x g package <name> # one more shared package: packages/
|
|
|
338
339
|
|
|
339
340
|
The boot guard is generated, app-owned: `apps/web/runtime.ts` calls `assertSignInConfigured(process.env)` before the boot binds a port, and outside `development`/`test` a `web` or `sync` role with a sign-in key unset refuses to start — `X_AUTH_SIGN_IN_UNCONFIGURED`, fix `export <KEY>="<value>"` in the role's deployed environment, then restart it (`x env example` lists the keys). The keys: `ULTIMATE_SECRETS_KEY` for `--password` (it seals the second-factor challenge); the provider's three plus `SESSION_SECRET` and `APP_URL` for `--oidc`. A second `x g sign-in` is `X_GENERATE_CONFLICT` and writes nothing. `--password` keeps the development viewer: it ships no sign-up page, so the first user is `register(appAuth(), { email, password, orgId, roles })`. An app that already has an `apps/web/runtime.ts` is that conflict too — merge the two `runtime` objects by hand.
|
|
340
341
|
|
|
342
|
+
**`x g invite`** (`As of 2026-11-14`) is the member invite, as the app's own actions over `@ultimat3/auth`'s `defineMemberInvite` ([Auth](Auth#member-invites)) — the shape `x g sign-in` writes for `login()`. No `<name>` (an app has one), and any `x g` flag but `--force`, `--dry-run` and `--locales` is `X_CLI_BAD_FLAG`, fix `x g invite`. Under `apps/web/app/auth/`: `invite.ts` (the flow, its `defineMail` and the link to `/auth/invites/accept?orgId=…&token=…`, built on `APP_URL` — never the request's `Host`, which the caller writes; unset, `inviteMember` is `X_ENV_MISSING`, fix `export APP_URL=…`), `policy.ts` (`member:invite`, the actor's own org), `inviteMember` and `revokeInvite` behind it (revoke removes only an address that joined through an invite; owner protection is the app's rule in `policy.ts`), `acceptInvite` (public by declaration; refuses an anonymous caller, rotates the session), `invites/page.tsx` and `invites/accept/page.tsx` (native forms, 0 kB), a test beside each. Also edits: `apps/web/shared/roles.ts` (`member:invite` to `admin`), `apps/web/api/index.ts` (the three actions), `apps/web/exercise.ts` (each action `off`, with its reason — the pass holds no mailed token), the root `package.json` of an app scaffolded before `x new` declared `@ultimat3/mail` (at the range `@ultimat3/auth` has; run `bun install`), the catalogs. Who may invite, seat limits and the roles a joiner gets are those files', to edit. A second run is `X_GENERATE_CONFLICT`, and so is an API index already binding `inviteMember`. Proof: `bun test ./packages/cli/src/generate-invite.contract.test.ts` — a fresh scaffold, the run, `tsc`, Biome and the generated tests.
|
|
343
|
+
|
|
341
344
|
**`x g chart-alerts`** (`As of 2026-11`) writes the two monitoring templates `x new`'s chart carries into an app chart that predates them — `docker/helm/templates/servicemonitor.yaml` and `alert-rules.yaml`, named after `Chart.yaml`'s `name` — and appends the `serviceMonitor:` / `alerts:` blocks `values.yaml` lacks. Only what is missing: a template already there is kept (`--force` rewrites both), and a values key already there — `enabled: false` included — is never touched; both templates read a missing block as `auto`, rendering only where the cluster serves the Prometheus operator's kinds. A second run writes nothing. No `<name>`, and any other `x g` flag but `--force`/`--dry-run` is `X_CLI_BAD_FLAG`. **`--print`** writes nothing and needs no chart: the same rules as plain Prometheus rule groups, defaults in place, for a loader outside Kubernetes (`--json`: `data.rules`, the YAML text). No `docker/helm/Chart.yaml` is `X_CHART_MISSING`, fix `x g chart-alerts --print --json`. `x doctor` lists the missing templates. The rules: [Observability](Observability).
|
|
342
345
|
|
|
343
346
|
**`x g chart-dashboard`** (`As of 2026-11`) is the same backfill for the chart's Grafana dashboard: `docker/helm/dashboards/ultimate-app.json` (one column of panels over the series the framework declares — requests, latency by route, statements, pool, jobs, realtime, the process) and `templates/dashboard-configmap.yaml`, which ships it as a ConfigMap a Grafana sidecar provisions by label — plus the `dashboard:` block `values.yaml` lacks, `enabled: false` (`x new`'s chart writes the same three). The same rules as `chart-alerts`: only what is missing, `--force` rewrites, no `<name>`, `X_CHART_MISSING` with no chart. **`--print`** writes nothing and needs no chart: the dashboard JSON, to import into a Grafana outside Kubernetes (`--json`: `data.dashboard`).
|
|
@@ -479,7 +482,7 @@ x db gen "add publish_at" | migrate | reset | studio
|
|
|
479
482
|
| `backfill --pending` | every backfill the app **declared**, minus the ones that completed | the alarm: a sweep merged and never enqueued had no ledger row and was invisible everywhere. **Non-zero exit** when anything is unswept, so a cron reads the code and not the table |
|
|
480
483
|
| `backfill <name>` / `backfill --all` | gate one sweep (or every pending one) and enqueue it | **dry run by default** — `--write` is never implied. `--write` enqueues; the workers perform the pass, because the queue is a job's execution surface. `--all` isolates per name and continues past a failure, exiting non-zero naming each |
|
|
481
484
|
| `diagnostics` | what the database is doing now: `blockers` (each waiting `pid` and the `blockedBy` pid holding it, at `data.blockers.rows[]`), `activity`, `slowQueries`, `unusedIndexes`, `invalidIndexes`, `notValidConstraints`, `deadTuples` | **facts, never a verdict: exit 0** whatever they say. The one failure is a connection that never opens, `X_DB_UNAVAILABLE`. Every section is one catalog read in its own `BEGIN READ ONLY` with a 2 s `statement_timeout`, capped at `--limit` rows (default 20, at most 1000). A section that fails is `{ available: false, code, reason, fix }` in place and the other six still answer; `slowQueries` is unavailable until an operator installs `pg_stat_statements` (never on the embedded database). No user table is read; session SQL is printed with every literal as `?`; a credential in a reason is masked. **Whoever runs it sees the redacted SQL of every session on the app's database role** (every role, when it holds `pg_read_all_stats`): statement shape and identifiers, never values. `unusedIndexes` skips unique and primary indexes and carries `statsAgeSeconds` and `replica`. Opens the database without applying the framework tables; an embedded one `x dev` holds is refused (`X_DEV_ALREADY_RUNNING`). `--json`: `data.<section>`. Arbitrary read-only SQL is `db.query` over [`x mcp serve`](MCP-And-AI) |
|
|
482
|
-
| `recount <entity>.<column>` | compare a `countedIn` counter with the true count of its child rows | **dry run by default**: lists the drifted rows (at most 50, the count whole) and exits non-zero with `X_LIFECYCLE_TRIGGER_MISSING` when any drifted.
|
|
485
|
+
| `recount <entity>.<column>` | compare a `countedIn` counter with the true count of its child rows | **dry run by default**: lists the drifted rows (at most 50, the count whole) and exits non-zero with `X_LIFECYCLE_TRIGGER_MISSING` when any drifted. The parent is walked in windows of 1,000 keys, in key order, each window one cross-tenant transaction (`As of 31.23`). `--write` repairs each window's drift inside its transaction and exits 0. An unknown `<entity>.<column>` is `X_CLI_BAD_FLAG`. `--json`: `data` = `{ target, write, drifted, batches, rows }` |
|
|
483
486
|
|
|
484
487
|
A bare `x db backfill` is `X_CLI_BAD_FLAG` naming a shape that works: the four answer four different questions, and defaulting to one of them is the ambiguity axiom 1 refuses.
|
|
485
488
|
|
|
@@ -524,6 +527,7 @@ Two more facts about the set, both `As of 2026-08`:
|
|
|
524
527
|
|---|---|---|---|
|
|
525
528
|
| `--name` | string | — | migration or branch name, or the backfill to filter the ledger by. Under `backfill --list` it is the **only** spelling of that filter: a positional there is a pass target in every other shape and is refused with `X_CLI_BAD_FLAG` rather than silently dropped |
|
|
526
529
|
| `--allow-destructive` | boolean | `false` | let `gen` emit a DROP whose `down` cannot restore the rows. `X_MIGRATION_IRREVERSIBLE`'s own `fix:` line names it |
|
|
530
|
+
| `--drop-redundant` | boolean | `false` | `gen`: leave out of the diff each implicit index (a column's own, from `.references()` or `.index()`) that another index, the primary key or a unique invariant already leads with, so the migration drops it `concurrently` in a non-transactional step you review. Never a default; once dropped, a plain `x db gen` does not rebuild it. A table with no migration yet keeps every index. `x doctor` lists what it would drop (`data.redundantIndexes`), `As of 2026-11-14` |
|
|
527
531
|
| `--list` | boolean | `false` | `backfill`: print the ledger |
|
|
528
532
|
| `--pending` | boolean | `false` | `backfill`: declared minus completed, judged in this `ULTIMATE_ENV`. Non-zero exit when anything is unswept |
|
|
529
533
|
| `--all` | boolean | `false` | `backfill`: every pending sweep, isolated per name |
|
|
@@ -1256,6 +1260,8 @@ Four warnings about how the app is held, `As of 31.16.0` (a fifth, `X_SHIPPED_GU
|
|
|
1256
1260
|
| `X_ENV_NAME_RESERVED` | a name the app declares in `envSchema` or seals in `secrets.enc.json` is one `FRAMEWORK_ENV` (`@ultimat3/core`) lists as a `switch` or `internal` name — setting it for the app also switches that package's behaviour. Deploy-contract names (`DATABASE_URL`, `PORT`) and host names are not collisions | rename it `APP_<name>` (or delete it where the value is meant for the framework); then `x env example` |
|
|
1257
1261
|
| `X_SHIPPED_GUARD_MISSING` (`As of 31.22`) | a guard `x new` ships is not in the app's `guards/`, so the gate does not hold the app to that rule — one per guard | `x g guard <name> && x verify --only boundaries --json` |
|
|
1258
1262
|
|
|
1263
|
+
**Redundant indexes**, the same way (`As of 2026-11-14`): each implicit index the entities describe that another index, the primary key or a unique invariant already leads with, still in the newest migration's snapshot, is one line — `<table>.<index> (<columns>) — <covering index>` — under a header naming `x db gen "drop redundant indexes" --drop-redundant`; `--json`: `data.redundantIndexes[]` = `{ table, name, columns, coveredBy }`, `[]` when none, absent when the app would not load or has no snapshot. A listing, never a finding: every write pays for each twice, and dropping it is a migration the app opts into.
|
|
1264
|
+
|
|
1259
1265
|
**The chart's monitoring templates**, the same way (`As of 2026-11`): an app with a `docker/helm/Chart.yaml` and no `templates/servicemonitor.yaml` or `templates/alert-rules.yaml` gets one line per missing file, then `x g chart-alerts`, which writes only those (`--json`: `data.chartAlerts`, `{ missing[], add }`). The dashboard is its own row: no `dashboards/ultimate-app.json` or `templates/dashboard-configmap.yaml` lists them, then `x g chart-dashboard` (`data.chartDashboard`, the same shape). A chart that dropped them on purpose keeps a green verdict; an app with no chart is listed nothing.
|
|
1260
1266
|
|
|
1261
1267
|
The embedded half is the bare-VM case: the external-database probe answers nothing the moment `DATABASE_URL` is unset, and that silence *is* the configuration a fresh box has. So `x doctor` also asks whether `@electric-sql/pglite` resolves from the app root — a resolve, never an import, because loading it boots the WASM build and takes the single-writer lock the next command needs. Red only where both hold: `DATABASE_URL` unset **and** the peer unresolvable, reported as `X_DB_UNAVAILABLE` with `@ultimat3/db`'s own sentence and its own runnable fix ([Bare VM](Bare-VM)). The snapshot half is `As of 2026-08` and separate from drift on purpose: they are two questions with two remedies, and `x db gen`'s own `X_MIGRATION_SNAPSHOT_MISSING` was a condition this diagnostic could not see at all, so `x doctor --json` — the `fix:` of the `X_CLI_UNEXPECTED` an author reaches it through — ran clean over a broken app.
|
|
@@ -65,6 +65,7 @@ The entity name is the first argument. Everything else is the init object:
|
|
|
65
65
|
| `table` | the physical table, when it is not the entity's own name. For a schema this framework did not generate — see [Adopting an existing database](#adopting-an-existing-database) |
|
|
66
66
|
| `tenant` | the tenant column. Omitted, it is inferred from `.tenant()` or a column named `orgId` — silence never means unscoped |
|
|
67
67
|
| `shared` | `'<why its rows belong to no tenant>'` — for an entity with no tenant column whose references reach one that has a tenant (a price list every org's subscriptions point at). Without it the `exercise` step reports `X_ENTITY_TENANT_UNDECLARED`; blank is refused at `entity()` with the same code, and beside a tenant column it is `X_INVARIANT_VIOLATED`. See [Policies and authz](Policies-And-Authz#the-static-tenant-check) |
|
|
68
|
+
| `global` | `'<why every tenant reads the same rows>'` — for an entity with no tenant column that references none (a plan catalog), `As of 2026-11-14`. A query reading only global entities is the tenant proof's `global` verdict, not `unproven`; projected on `$describe().global`. Blank is `X_ENTITY_TENANT_UNDECLARED`; beside a tenant column, or beside `shared`, `X_INVARIANT_VIOLATED`. See [Policies and authz](Policies-And-Authz#the-dynamic-tenant-proof) |
|
|
68
69
|
| `scan` | `'<why it stays small>'` — a bounded table (`'a closed catalog of 8 rows'`) the `exercise` step's plan sweep may see read whole. Without it a sequential scan of it is `X_QUERY_UNINDEXED`; blank is `X_INVARIANT_VIOLATED`. See [Testing](Testing#the-plan-and-scale-sweeps) |
|
|
69
70
|
| `invariants` | `(c) => [invariant(name, expr), …]` — named predicates enforced on write, projected to a CHECK or UNIQUE constraint where expressible. `c` is typed from `columns`, so a typo is a compile error |
|
|
70
71
|
| `indexes` | composite and partial indexes; a single unique or indexed column declares it on the column instead. On a table that already exists `x db gen` builds it with `create index concurrently` by default (`As of 2026-11`), in a migration of its own, outside a transaction; `concurrently: false` is the plain build, marked `-- lock-heavy: true` ([Indexes built concurrently](Migrations-And-Backfills#indexes-built-concurrently--expand--contract)). Key parts — `expression`, `orders`, `include`, `operatorClass` — under [Index key parts](#index-key-parts) |
|
|
@@ -456,7 +457,8 @@ export async function feed(orgId: string, after: string | null) {
|
|
|
456
457
|
| The plan | `order by` stays on the bare columns: an index on `(created_at desc, id desc)` answers it as an Index Only Scan. `date_trunc('milliseconds', …)` measured 100 ms against 0.2 ms on 300,000 rows |
|
|
457
458
|
| Kinds | `timestamptz`, `uuid`, `text`, `integer`, `bigint` |
|
|
458
459
|
| Directions | all one way: a row comparison. Mixed: the or-chain |
|
|
459
|
-
| A
|
|
460
|
+
| A nullable key | `As of 2026-11-14`: declare it — `{ column: raw('p.published_at'), kind: 'timestamptz', direction: 'desc', nullable: true }`. NULL's place is written into `order by` (`nulls: 'first' \| 'last'`; default `asc nulls last`, `desc nulls first`, the entity driver's), the cursor carries present/absent, and the seek is the or-chain. The last key stays not null |
|
|
461
|
+
| A null key | on a key not declared `nullable`, `X_KEYSET_NULL_KEY` on any row of the page: a row comparison has no null order. A nullable last key is the same code, at `keyset()` |
|
|
460
462
|
| A cursor from another read | `X_CURSOR_INVALID`. The scope is yours plus the keys: the same scope under another sort is refused too |
|
|
461
463
|
| Memory | none: raw SQL has no memory path. Test it on the migrated database |
|
|
462
464
|
|
|
@@ -1258,6 +1260,7 @@ Three declarations on the entity, each compiled to a trigger or a purge target,
|
|
|
1258
1260
|
| `retain: { after: '90d', on: 'createdAt' }` | a `PurgeTarget` per entity — batched, cross-tenant `delete … where created_at < now - after` | no window (`X_ENTITY_RETAIN_INVALID`), `on` not an indexed `timestamp()` (`X_ENTITY_RETAIN_UNINDEXED`), beside `appendOnly`, or on a table the catalog holds partitioned (drift, `X_ENTITY_RETAIN_INVALID`: detach partitions in a `task`) |
|
|
1259
1261
|
| `history: true` · `history: { retain: { after: '365d' }, ignore: ['likeCount', 'updatedAt'] }` | `<table>_history (id, <tenant>, row_id, op, at, actor_id, request_id, before, after)` — a registered entity (`posts.$history`), written by the `ultimate_history` trigger, guarded by `ultimate_history_guard` | a composite primary key, `appendOnly` (`X_INVARIANT_VIOLATED`) |
|
|
1260
1262
|
| `references(() => posts.id, { countedIn: () => posts.likeCount })` | a trigger on the child moving `posts.like_count` by one in the write's own transaction | the column is no `integer()`, or the key points at no single primary key (`X_ENTITY_COUNTS_INVALID`) |
|
|
1263
|
+
| `countedIn: { to: () => posts.upCount, where: (): Expr => whereColumns(likes).kind.eq('up') }` | the same trigger, counting only the child rows the predicate holds over — compiled once into its condition, its `update of` list and the recount | the predicate has no SQL (a function in `matches`/`satisfies`), or names no column of the child (`X_ENTITY_COUNTS_INVALID`) |
|
|
1261
1264
|
|
|
1262
1265
|
```ts
|
|
1263
1266
|
import { entity, integer, timestamp, uuid } from '@ultimat3/entity';
|
|
@@ -1280,7 +1283,8 @@ export const likes = entity('likes', {
|
|
|
1280
1283
|
- **Retention is a promise `x verify` checks.** A `retain` no `purge()` covers is `X_ENTITY_RETAIN_UNSWEPT` in the `manifest` step. `purge({ entities: 'declared' })` covers every one, history tables included, and needs no line per entity.
|
|
1281
1284
|
- **History is recorded by trigger**, so `updateWhere`, a cascade and raw SQL are recorded too. An update that changes nothing records nothing; a change to a counted column, or to columns `history: { ignore }` names, alone records nothing — on both drivers (`history-ignore.test.ts`). `ignore` takes the entity's own columns, typed; another name is `X_INVARIANT_VIOLATED`. Declaring it changes the trigger's arguments, so `x db gen` writes the migration that reinstalls it. `.sealed()` columns stay ciphertext in the images. `actor_id`/`request_id` are what the WRITE'S transaction set (`x.actor`, `x.request`): the repository sets them before its first write to a history entity inside a transaction; an autocommit write records `null`, never a guess. Update of a history row is refused always; delete only under `x.purge` naming that table, which the retention sweep and a subject erase set (`X_ENTITY_APPEND_ONLY`, SQLSTATE `23001`). Reading it is an ordinary, tenant-scoped, cursor-paged read: `database({ posts, postsHistory: posts.$history })`.
|
|
1282
1285
|
- **One row's history is `history(db.postsHistory, id)`**: every version, oldest first, each numbered `version` from 1 — ordered by chaining each `before` onto the previous `after` across every version, `at` only breaking ties: `at` is the transaction's START, so a transaction that began first and committed last carries the earlier `at` and the later image. `history(table, id, { limit: n })` reads the `n` versions with the latest `at` (ties at the edge kept), numbered as the whole history numbers them — chosen by transaction start, so a transaction that began before that window and committed inside it can fall outside. The read is the history table's, so another tenant's row reads back `[]`; the policy is the query or action that calls it. `version` counts what is retained: after a `retain` sweep, 1 is the oldest kept. As of 31.3.
|
|
1283
|
-
- **A counter locks its parent row.** A hot parent serializes its writers; where that matters, `countBy` plus a cache is the alternative. A soft-deleted child is not counted. A new counter's migration recounts once, so an existing table starts true; `x db recount posts.likeCount` reports drift and `--write` repairs it.
|
|
1286
|
+
- **A counter locks its parent row.** A hot parent serializes its writers; where that matters, `countBy` plus a cache is the alternative. A soft-deleted child is not counted. A new counter's migration recounts once, so an existing table starts true; `x db recount posts.likeCount` reports drift and `--write` repairs it, in key-range batches.
|
|
1287
|
+
- **A counter's `where` is the invariant language over the CHILD**, built from `whereColumns(<child>)` — a thunk, like `to`, so it is typed by the child's own columns. Annotate it `(): Expr =>` (`import type { Expr } from '@ultimat3/entity'`): the child names itself inside its own declaration, and without the return type TypeScript reports the cycle (TS7022). A NULL operand is not counted, as a SQL `where` decides it; memory decides it the same way (`counter-where.test.ts`). Changing the predicate reinstalls the trigger and recounts in the same migration. The bare `countedIn: () => col` form is unchanged. As of 31.23.
|
|
1284
1288
|
- **A counter's write is reported as the parent's change.** The WAL replicator sees the trigger's write; the in-process `entity.row` event (what `x dev` on PGlite and the memory driver feed live queries from) reports it too: after a child write, while `entity.row` has a subscriber, the parents whose count moved are read back in the write's transaction and each is an `update` at COMMIT, `before` the row with the count moved back. A filtered write (`deleteWhere`, `updateWhere`, a chain's `deleteAll`/`updateAll`) pinned to one parent by its key reports that row with `before: null`; one spanning parents is `entity.bulk` for the parent table. With no subscriber, nothing is read. So a live count needs no recount in the mutator (`counter-observed.test.ts`). As of 2026-11.
|
|
1285
1289
|
- **An erase reaches history.** A parent `subjectErase()` deletes or anonymizes writes the person into a before image, so its `<table>_history` needs a line in `defineSubject({ tables })`: `'delete'` removes every image of those rows in the parent's own transaction — under `x.purge` on Postgres, under `purgingHistory(table, work)` in memory, the one delete each lets through — `{ retain: '<why>' }` keeps them, `anonymize` is refused. An undeclared one is `X_SUBJECT_TABLE_UNDECLARED`, an `anonymize` `X_SUBJECT_TREATMENT_INVALID`; images written before an upgrade are reached only by the next erase of that subject ([Jobs and workflows](Jobs-And-Workflows#one-persons-data--subjectexport-and-subjecterase)). As of 2026-11.
|
|
1286
1290
|
- **Memory answers as Postgres does**: the memory driver records history and moves counters in its repository (`counter.test.ts`, `history.test.ts` are the parity tables).
|
package/wiki/FAQ.md
CHANGED
|
@@ -27,7 +27,7 @@ What it does **not** claim:
|
|
|
27
27
|
|
|
28
28
|
| Not claimed | Detail |
|
|
29
29
|
|---|---|
|
|
30
|
-
| A multi-node realtime
|
|
30
|
+
| A multi-node realtime **rate** | correctness across nodes is proven over a real NATS bus (`multi-node.live.test.ts`, `As of 2026-11-14`): a publish on one node delivered by another in order, a page resuming on a survivor from its cursor with nothing lost or twice, a restarted node's snapshot, a missed-bus gap re-served at once ([Realtime](Realtime#across-nodes-over-a-real-bus)). The 50k forced-restart benchmark is still **one** `sync` node over `InProcessTransport`; fanout throughput and per-node socket capacity across nodes are unmeasured targets, not results |
|
|
31
31
|
| A rolling restart on **Compose** | Compose is the single-node rung: one published port has one binder, so a restart there is a restart. The invisible-restart proof is Kubernetes only ([Deployment](Deployment)) |
|
|
32
32
|
| Not shipped, `As of 2026-09-23` | the plugin API, multi-region replication, and the Redis **job** driver — all behind the interfaces that ship today (there is no NATS job driver since 25.0.0). The Redis driver throws `X_NOT_IMPLEMENTED` with a runnable `fix:` line rather than pretending to work |
|
|
33
33
|
|
|
@@ -119,7 +119,7 @@ Yes. `realtime: { enabled: false }` in `app.config.ts` is the opt-out (its defau
|
|
|
119
119
|
|
|
120
120
|
### What happens if the sync engine doesn't work out?
|
|
121
121
|
|
|
122
|
-
It is roughly **70% of total effort** and the single largest risk. Tiers 1–2 shipped in milestone 6 and are under semver; tier 3 local-first shipped in 21.0.0, opt-in per entity (`entity(name, { persist: true })`). The reconnect benchmark that gated topology — 50k sockets, a forced `sync` restart, recovery time and DB load — **is measured at 1.1.0**: all 50,000 reconnected, 49,981 received a channel patch inside the window, p50 54.0s / p90 105.5s, 156,851 connect attempts shed before any query path ([Realtime](Realtime)). That is **reachability** — first patch on the reconnected socket — not consistency; the delivery half is a separate 10,000-client run, **1,666,882 patches received, 0 observed sequence gaps** — a lower bound, since a hole is only visible between two frames one connection received ([Realtime](Realtime)) — and `As of 2026-08` the only run that counts lost patches at all. Both were run on **one** node,
|
|
122
|
+
It is roughly **70% of total effort** and the single largest risk. Tiers 1–2 shipped in milestone 6 and are under semver; tier 3 local-first shipped in 21.0.0, opt-in per entity (`entity(name, { persist: true })`). The reconnect benchmark that gated topology — 50k sockets, a forced `sync` restart, recovery time and DB load — **is measured at 1.1.0**: all 50,000 reconnected, 49,981 received a channel patch inside the window, p50 54.0s / p90 105.5s, 156,851 connect attempts shed before any query path ([Realtime](Realtime)). That is **reachability** — first patch on the reconnected socket — not consistency; the delivery half is a separate 10,000-client run, **1,666,882 patches received, 0 observed sequence gaps** — a lower bound, since a hole is only visible between two frames one connection received ([Realtime](Realtime)) — and `As of 2026-08` the only run that counts lost patches at all. Both were run on **one** node. Correctness across nodes — delivery, ordering, cursor resume on a survivor, gap repair — is proven separately over a real NATS bus ([Realtime](Realtime#across-nodes-over-a-real-bus)); multi-node fanout throughput and socket capacity are still unmeasured. If the incremental matcher turns out to be the bottleneck, wrapping an existing protocol (Zero's) is an accepted fallback.
|
|
123
123
|
|
|
124
124
|
### Why ship realtime last if it's the differentiator?
|
|
125
125
|
|
package/wiki/Home.md
CHANGED
|
@@ -17,7 +17,7 @@ No Docker and no service: embedded Postgres, in-process NATS, local storage, a s
|
|
|
17
17
|
| an agent writes most of your code: one way per task, `--json` everywhere, every error a code, a cause and a `fix:` command | you need Node.js or Deno: Bun only |
|
|
18
18
|
| you want authz written once: one `policy` guards HTTP, live queries, jobs, MCP and admin | your database is not Postgres, or your UI is not SolidJS |
|
|
19
19
|
| you want jobs, realtime, auth, mail, storage, i18n, SEO, admin and MCP decided and gated | you deploy to Vercel functions, Lambda or Workers: containers only |
|
|
20
|
-
| the app may grow: the same code from one PaaS process to Kubernetes | you want a plugin API (an app wraps a primitive instead), or
|
|
20
|
+
| the app may grow: the same code from one PaaS process to Kubernetes | you want a plugin API (an app wraps a primitive instead), or realtime throughput and socket capacity measured across nodes today — delivery, ordering and resume across nodes are proven, the rates are not ([Realtime](Realtime#across-nodes-over-a-real-bus)) |
|
|
21
21
|
|
|
22
22
|
## Is it for a project this size
|
|
23
23
|
|