@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,23 @@
|
|
|
1
|
+
// Single responsibility: the LIVENESS answer of the roles whose only socket is the scrape port —
|
|
2
|
+
// `worker`, `scheduler`, `replicator`. Core's `/healthz` (503 once stopped) plus every running
|
|
3
|
+
// loop's heartbeat (`@ultimat3/jobs`' `staleLoops`): a loop past its bound is a wedged process
|
|
4
|
+
// the kubelet must restart, even while its event loop still answers every scrape.
|
|
5
|
+
|
|
6
|
+
import { type HealthPayload, healthzPayload, logger } from '@ultimat3/core';
|
|
7
|
+
import { staleLoops } from '@ultimat3/jobs';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* `/healthz` on `METRICS_PORT`. The answer carries no loop name — that port is unauthenticated and
|
|
11
|
+
* names are topology — so the log line is where an operator reads which loop, why and how long.
|
|
12
|
+
* `/readyz` never reads loops: a wedge is a restart, never a traffic decision.
|
|
13
|
+
*/
|
|
14
|
+
export function livenessPayload(): HealthPayload {
|
|
15
|
+
const health = healthzPayload();
|
|
16
|
+
if (!health.ok) return health;
|
|
17
|
+
const stale = staleLoops();
|
|
18
|
+
if (stale.length === 0) return health;
|
|
19
|
+
logger.error('ultimate.liveness.loop-stale', {
|
|
20
|
+
loops: stale.map((loop) => `${loop.name} ${loop.reason} ${loop.ageMs}ms > ${loop.boundMs}ms`),
|
|
21
|
+
});
|
|
22
|
+
return { ok: false, status: 503, body: health.body };
|
|
23
|
+
}
|
package/src/schema-drift.ts
CHANGED
|
@@ -22,7 +22,7 @@ import {
|
|
|
22
22
|
snapshotOf,
|
|
23
23
|
unrenderedOf,
|
|
24
24
|
} from '@ultimat3/db';
|
|
25
|
-
import {
|
|
25
|
+
import { registeredEntities } from '@ultimat3/entity';
|
|
26
26
|
import { loadApp } from './app-load';
|
|
27
27
|
import { checkSourceDrift, DB_PACKAGE } from './drift';
|
|
28
28
|
import {
|
|
@@ -32,6 +32,7 @@ import {
|
|
|
32
32
|
} from './drift-replica-identity';
|
|
33
33
|
import { MIGRATIONS_DIR, readMigrations } from './migrations';
|
|
34
34
|
import type { Finding } from './output';
|
|
35
|
+
import { settledDescriptions } from './redundant-indexes';
|
|
35
36
|
import { appRowSecurity, type RowSecurityWanted, rowSecurityFindings } from './row-security-wanted';
|
|
36
37
|
import { diffDeclaredSchema, type SchemaDifference } from './schema-diff';
|
|
37
38
|
|
|
@@ -53,7 +54,9 @@ export type DeclaredEntities = (
|
|
|
53
54
|
export const appEntities: DeclaredEntities = async (root) => {
|
|
54
55
|
const app = await loadApp(root);
|
|
55
56
|
if (app.findings.length > 0) return undefined;
|
|
56
|
-
|
|
57
|
+
// What `x db gen` diffed (`settledDescriptions`): a covered index `--drop-redundant` dropped is
|
|
58
|
+
// still described by its entity, and reading the raw registry would report it as unmigrated.
|
|
59
|
+
return settledDescriptions(registeredEntities(), await readMigrations(root), false);
|
|
57
60
|
};
|
|
58
61
|
|
|
59
62
|
/**
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
// The roles each boot warning concerns, in one table, and the step that runs the
|
|
2
|
-
// the booting role alone.
|
|
3
|
-
//
|
|
1
|
+
// The roles each FRAMEWORK boot warning concerns, in one table, and the step that runs the
|
|
2
|
+
// post-load ones for the booting role alone. The role rule is core's `bootWarning`'s
|
|
3
|
+
// (`bootRolesConcerned`) — one answer for these and for an app's own role-scoped boot line.
|
|
4
4
|
|
|
5
5
|
import type { Role } from '@ultimat3/core';
|
|
6
|
+
import { bootRolesConcerned } from '@ultimat3/core';
|
|
6
7
|
|
|
7
8
|
/** Every warning a container boot can say. A new one does not compile until it names its roles. */
|
|
8
9
|
export type BootWarning =
|
|
@@ -32,13 +33,13 @@ export const BOOT_WARNINGS: ReadonlyMap<BootWarning, readonly Role[]> = new Map(
|
|
|
32
33
|
Object.entries(DECLARED) as [BootWarning, readonly Role[]][],
|
|
33
34
|
);
|
|
34
35
|
|
|
35
|
-
/** Whether `warning` is one `role` can act on. An unknown warning concerns nobody. */
|
|
36
|
-
export const bootWarningConcerns = (warning: BootWarning, role: Role): boolean =>
|
|
37
|
-
BOOT_WARNINGS.get(warning)?.includes(role) ?? false;
|
|
38
|
-
|
|
39
36
|
/** Whether any of `roles` — `x dev` runs several in one process — can act on `warning`. */
|
|
40
37
|
export const bootWarningConcernsAny = (warning: BootWarning, roles: readonly Role[]): boolean =>
|
|
41
|
-
|
|
38
|
+
bootRolesConcerned(BOOT_WARNINGS.get(warning) ?? [], roles);
|
|
39
|
+
|
|
40
|
+
/** Whether `warning` is one `role` can act on. An unknown warning concerns nobody. */
|
|
41
|
+
export const bootWarningConcerns = (warning: BootWarning, role: Role): boolean =>
|
|
42
|
+
bootWarningConcernsAny(warning, [role]);
|
|
42
43
|
|
|
43
44
|
/** The post-load probes: each logs its own line and answers whether it had anything to say. */
|
|
44
45
|
export interface BootWarningProbes {
|
package/src/serve.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
// `dev: true`. The only production-shaped decisions live here: which role, which port, and which
|
|
5
5
|
// interface — every one by default, because a container is reached through a port mapping.
|
|
6
6
|
|
|
7
|
-
import { assertNoDevSecretsOutsideLocal, logger } from '@ultimat3/core';
|
|
7
|
+
import { assertNoDevSecretsOutsideLocal, frameworkVersion, logger } from '@ultimat3/core';
|
|
8
8
|
import { assertNoSchemaDrift, checkDrift, migrate } from '@ultimat3/db';
|
|
9
9
|
import { loadAppRuntime } from './app-runtime';
|
|
10
10
|
import { acceptCreatedTables } from './db-accept-created';
|
|
@@ -218,6 +218,9 @@ export async function runRole(input: ServeOptions): Promise<StartedApp> {
|
|
|
218
218
|
// `nats(connecting)` on a role that only publishes is a served pod with the bus down;
|
|
219
219
|
// `ultimate bus` is logged with `nats(up)` when the dial lands.
|
|
220
220
|
bus: app.bus,
|
|
221
|
+
// `buildId` is the app's; this is which framework release booted it — the same fact the
|
|
222
|
+
// monitor's `framework_version` tag and `target_info`'s label carry.
|
|
223
|
+
frameworkVersion: frameworkVersion(),
|
|
221
224
|
});
|
|
222
225
|
await hold();
|
|
223
226
|
return app;
|
|
@@ -113,12 +113,43 @@ const literalCodeIn = (text: string, open: number): boolean => {
|
|
|
113
113
|
return false;
|
|
114
114
|
};
|
|
115
115
|
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
116
|
+
/** The first literal code in a span: the one a finding's fix declares. */
|
|
117
|
+
const CODE_LITERAL = /\\b(?:code|'code'|"code")\\s*:\\s*['"\`](X(?:_[A-Z0-9]+)+)['"\`]/;
|
|
118
|
+
const CLASS_NAME = /\\bclass\\s+([A-Za-z_$][\\w$]*)\\s*$/;
|
|
119
|
+
/** Where the next declaration starts, so a span never reads the following class's code. */
|
|
120
|
+
const NEXT_DECLARATION = /\\b(?:class|new)\\s/g;
|
|
121
|
+
|
|
122
|
+
const codeIn = (text: string, from: number): string | undefined => {
|
|
123
|
+
NEXT_DECLARATION.lastIndex = from + 1;
|
|
124
|
+
const next = NEXT_DECLARATION.exec(text);
|
|
125
|
+
return CODE_LITERAL.exec(text.slice(from, next === null ? text.length : next.index))?.[1];
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
/** The code's own words, the binding a class-less finding's fix declares: X_POST_GONE → PostGone. */
|
|
129
|
+
const bindingOf = (code: string): string =>
|
|
130
|
+
code
|
|
131
|
+
.slice(2)
|
|
132
|
+
.split('_')
|
|
133
|
+
.map((word) => word.charAt(0) + word.slice(1).toLowerCase())
|
|
134
|
+
.join('');
|
|
135
|
+
|
|
136
|
+
/** What a finding can name of the class it replaces; a placeholder for whatever it cannot read. */
|
|
137
|
+
interface Declared {
|
|
138
|
+
readonly name?: string | undefined;
|
|
139
|
+
readonly code?: string | undefined;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const finding = (file: SourceFile, line: number, what: string, declared: Declared): Finding => {
|
|
143
|
+
const name =
|
|
144
|
+
declared.name ?? (declared.code === undefined ? '<ErrorName>' : bindingOf(declared.code));
|
|
145
|
+
const code = \`'\${declared.code ?? 'X_<CODE>'}'\`;
|
|
146
|
+
return {
|
|
147
|
+
code: CODE,
|
|
148
|
+
cause: \`\${file.path}:\${line} \${what} — the title, the HTTP status and the class are then declared apart, and a code with no status answers 500 and hides its cause\`,
|
|
149
|
+
fix: \`rewrite it in \${file.path} as one call per class, from @ultimat3/core/page: export const \${name} = defineError({ code: \${code}, title, status, cause, fix, problemMeta: ['<meta key>'] }) — it replaces the class and its registerErrorStatus / registerProblemMeta rows (offSocket: true instead of status for a code no response carries; publicCause: true for a 5xx whose cause a caller may read; drop problemMeta when its meta stays operator-only), then: x verify\`,
|
|
150
|
+
at: file.path,
|
|
151
|
+
};
|
|
152
|
+
};
|
|
122
153
|
|
|
123
154
|
const barrelFinding = (file: SourceFile, line: number): Finding => ({
|
|
124
155
|
code: CODE,
|
|
@@ -150,24 +181,30 @@ export function undeclaredErrors(files: readonly SourceFile[]): readonly Finding
|
|
|
150
181
|
for (const file of files) {
|
|
151
182
|
const text = blank(file.source);
|
|
152
183
|
const names = nameSource(classNames(text));
|
|
153
|
-
const push = (index: number, what: string): void => {
|
|
184
|
+
const push = (index: number, what: string, declared: Declared): void => {
|
|
154
185
|
const line = lineOf(text, index);
|
|
155
|
-
found.push({ path: file.path, line, finding: finding(file, line, what) });
|
|
186
|
+
found.push({ path: file.path, line, finding: finding(file, line, what, declared) });
|
|
156
187
|
};
|
|
157
188
|
for (const line of barrelDefineErrorLines(text)) {
|
|
158
189
|
found.push({ path: file.path, line, finding: barrelFinding(file, line) });
|
|
159
190
|
}
|
|
160
191
|
for (const match of text.matchAll(new RegExp(\`\\\\bextends\\\\s+(?:\${names})\\\\b\`, 'g'))) {
|
|
161
|
-
|
|
192
|
+
const name = CLASS_NAME.exec(text.slice(0, match.index))?.[1];
|
|
193
|
+
push(match.index, 'subclasses UltimateError by hand', {
|
|
194
|
+
name,
|
|
195
|
+
code: codeIn(text, match.index),
|
|
196
|
+
});
|
|
162
197
|
}
|
|
163
198
|
for (const match of text.matchAll(new RegExp(\`\\\\bnew\\\\s+(?:\${names})\\\\s*\\\\(\\\\s*\`, 'g'))) {
|
|
164
199
|
const at = match.index + match[0].length;
|
|
165
200
|
// Anything but an object literal hides its code from this read: a value built elsewhere,
|
|
166
201
|
// Object.assign over a literal. A re-raise is written as a literal, with code: err.code.
|
|
167
202
|
if (text[at] !== '{')
|
|
168
|
-
push(match.index, 'builds new UltimateError from a value this guard cannot read');
|
|
203
|
+
push(match.index, 'builds new UltimateError from a value this guard cannot read', {});
|
|
169
204
|
else if (literalCodeIn(text, at))
|
|
170
|
-
push(match.index, 'builds new UltimateError with a literal code'
|
|
205
|
+
push(match.index, 'builds new UltimateError with a literal code', {
|
|
206
|
+
code: codeIn(text, at),
|
|
207
|
+
});
|
|
171
208
|
}
|
|
172
209
|
}
|
|
173
210
|
return found
|
|
@@ -1,17 +1,22 @@
|
|
|
1
|
-
// The `repo-unbounded` guard `x new` ships
|
|
2
|
-
// `.
|
|
3
|
-
//
|
|
1
|
+
// The `repo-unbounded` guard `x new` ships: a handle chain in a `repo.ts` ending in `.all()` with no
|
|
2
|
+
// `.limit(n)` answers the handle's default page and drops the cursor to the rest — neither every
|
|
3
|
+
// row nor a page the caller chose. Pairs with entity's `X_ENTITY_ALL_TRUNCATED` warning. A new app
|
|
4
|
+
// gets it FAILING the gate; `'warning'` renders the report-only form apps scaffolded earlier hold.
|
|
4
5
|
|
|
5
6
|
import { guardCode } from './guard';
|
|
6
7
|
import { repoUnboundedTest } from './guard-repo-unbounded-test';
|
|
7
8
|
import type { GeneratedFile } from './naming';
|
|
8
9
|
|
|
10
|
+
/** How the emitted guard reports: failing `boundaries`, or listing on it (`severity: 'warning'`). */
|
|
11
|
+
export type RepoUnboundedSeverity = 'error' | 'warning';
|
|
12
|
+
|
|
9
13
|
/** Derived from the guard's name, never a literal: an `X_*` literal here is a FRAMEWORK code. */
|
|
10
14
|
const NAME = 'repo-unbounded';
|
|
11
15
|
const CODE = guardCode(NAME);
|
|
12
16
|
|
|
13
|
-
const source =
|
|
14
|
-
|
|
17
|
+
const source = (
|
|
18
|
+
severity: RepoUnboundedSeverity,
|
|
19
|
+
): string => `// repo-unbounded: a repo.ts read says how many rows it wants, never a bare \`.all()\`.
|
|
15
20
|
// \`x verify\` discovers every file in \`guards/\` and runs its \`guard\` inside the \`boundaries\`
|
|
16
21
|
// step — nothing registers this file, so nothing can forget to. Delete it to drop the rule.
|
|
17
22
|
//
|
|
@@ -20,8 +25,11 @@ const source =
|
|
|
20
25
|
// only from a missing row. Read: a \`db.<table>…all()\` or \`tx.<table>…all()\` chain with no
|
|
21
26
|
// \`.limit(\`, \`.page(\`, \`.keyset(\` or \`.one(\` in it, in \`{apps,packages}/**/repo{,-*}.ts\`, never a
|
|
22
27
|
// test. Admitted: a \`// why:\` on the chain's first line or the line above it, naming the bound.
|
|
23
|
-
|
|
24
|
-
|
|
28
|
+
${
|
|
29
|
+
severity === 'warning'
|
|
30
|
+
? "// REPORT ONLY (`severity: 'warning'`): its findings list on `boundaries`, never fail it.\n"
|
|
31
|
+
: ''
|
|
32
|
+
}
|
|
25
33
|
import type { Finding, Guard } from '@ultimat3/cli';
|
|
26
34
|
|
|
27
35
|
/** The app owns the codes its own conventions raise — this one is named for the guard. */
|
|
@@ -179,9 +187,11 @@ export function unboundedReads(files: readonly RepoFile[]): readonly Finding[] {
|
|
|
179
187
|
|
|
180
188
|
export const guard: Guard = {
|
|
181
189
|
summary: 'a repo.ts read says how many rows it wants: no .all() without a .limit(n)',
|
|
182
|
-
|
|
183
|
-
severity
|
|
184
|
-
|
|
190
|
+
${
|
|
191
|
+
severity === 'warning'
|
|
192
|
+
? " // REPORT ONLY: findings are warnings on the `boundaries` step. Delete this line to enforce it.\n severity: 'warning',\n"
|
|
193
|
+
: ''
|
|
194
|
+
} async check(_root, sources) {
|
|
185
195
|
// The run's ONE read of these files: \`repo-raw-sql\` asks for the same glob, so they share it.
|
|
186
196
|
const repos = await sources.files('{apps,packages}/**/repo{,-*}.ts');
|
|
187
197
|
const read = repos.filter((file) => !file.path.endsWith('.test.ts'));
|
|
@@ -190,8 +200,14 @@ export const guard: Guard = {
|
|
|
190
200
|
};
|
|
191
201
|
`;
|
|
192
202
|
|
|
193
|
-
/**
|
|
194
|
-
|
|
195
|
-
|
|
203
|
+
/**
|
|
204
|
+
* `guards/repo-unbounded.ts` and its test. No index, no registry — the directory registers it.
|
|
205
|
+
* `'error'` is what `x new` and `x g guard` write; `'warning'` is the form shipped before, which an
|
|
206
|
+
* existing app keeps until it deletes the severity line itself.
|
|
207
|
+
*/
|
|
208
|
+
export const repoUnboundedGuardFiles = (
|
|
209
|
+
severity: RepoUnboundedSeverity = 'error',
|
|
210
|
+
): readonly GeneratedFile[] => [
|
|
211
|
+
{ path: `guards/${NAME}.ts`, contents: source(severity) },
|
|
196
212
|
{ path: `guards/${NAME}.test.ts`, contents: repoUnboundedTest(CODE) },
|
|
197
213
|
];
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// The two pages `x g invite` writes: the inviter's (invite an address, withdraw one) and the
|
|
2
|
+
// invitee's, where the mailed link lands and its org and token are posted back at `acceptInvite`.
|
|
3
|
+
// Native forms only: nothing hydrates, so each page ships 0 bytes of script.
|
|
4
|
+
|
|
5
|
+
import { sortedImports } from './imports';
|
|
6
|
+
import { catalogImport, translatorBinding } from './sign-in-shared';
|
|
7
|
+
|
|
8
|
+
export type InvitePage = 'manage' | 'accept';
|
|
9
|
+
|
|
10
|
+
const KEY: Readonly<Record<InvitePage, string>> = {
|
|
11
|
+
manage: 'app.auth.invites',
|
|
12
|
+
accept: 'app.auth.inviteAccept',
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
const URL_PATH: Readonly<Record<InvitePage, string>> = {
|
|
16
|
+
manage: '/auth/invites',
|
|
17
|
+
accept: '/auth/invites/accept',
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
const routeConfig = (key: string): string => `export const config = defineRoute({
|
|
21
|
+
render: 'stream',
|
|
22
|
+
hydrate: 'never',
|
|
23
|
+
// Never from a cache: a stale form posts at a build that has moved on.
|
|
24
|
+
offline: 'network-only',
|
|
25
|
+
budget: { js: '0kb' },
|
|
26
|
+
meta: ({ t }) => ({
|
|
27
|
+
title: t('${key}.title'),
|
|
28
|
+
description: t('${key}.description'),
|
|
29
|
+
robots: { index: false, follow: false },
|
|
30
|
+
}),
|
|
31
|
+
});`;
|
|
32
|
+
|
|
33
|
+
const MANAGE_BODY = ` <form method="post" action={derivePath('inviteMember').path}>
|
|
34
|
+
<Field label={t('app.auth.invites.email')} required>
|
|
35
|
+
{(control) => <Input {...control} name="email" type="email" autocomplete="off" />}
|
|
36
|
+
</Field>
|
|
37
|
+
<Button type="submit">{t('app.auth.invites.submit')}</Button>
|
|
38
|
+
</form>
|
|
39
|
+
<form method="post" action={derivePath('revokeInvite').path}>
|
|
40
|
+
<Field label={t('app.auth.invites.revokeEmail')} required>
|
|
41
|
+
{(control) => <Input {...control} name="email" type="email" autocomplete="off" />}
|
|
42
|
+
</Field>
|
|
43
|
+
<Button type="submit" variant="secondary">
|
|
44
|
+
{t('app.auth.invites.revoke')}
|
|
45
|
+
</Button>
|
|
46
|
+
</form>`;
|
|
47
|
+
|
|
48
|
+
const ACCEPT_BODY = ` <p>{t('app.auth.inviteAccept.explain')}</p>
|
|
49
|
+
<form method="post" action={derivePath('acceptInvite').path}>
|
|
50
|
+
<input type="hidden" name="orgId" value={props.query?.orgId ?? ''} />
|
|
51
|
+
<input type="hidden" name="token" value={props.query?.token ?? ''} />
|
|
52
|
+
<Button type="submit">{t('app.auth.inviteAccept.submit')}</Button>
|
|
53
|
+
</form>`;
|
|
54
|
+
|
|
55
|
+
const COMMENT: Readonly<Record<InvitePage, string>> = {
|
|
56
|
+
manage: `// Invite a person into your org, or withdraw an invite: two native forms at the routes
|
|
57
|
+
// \`inviteMember\` and \`revokeInvite\` derive. Both refuse an actor without \`member:invite\`.`,
|
|
58
|
+
accept: `// Where the mailed invite lands: its org and token, posted back at \`acceptInvite\` by a signed-in
|
|
59
|
+
// account. Only the account at the invited address can redeem it.`,
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
export const invitePageSource = (module: string | undefined, page: InvitePage): string => {
|
|
63
|
+
const accept = page === 'accept';
|
|
64
|
+
return `${COMMENT[page]}
|
|
65
|
+
${sortedImports([
|
|
66
|
+
catalogImport(module),
|
|
67
|
+
"import { derivePath } from '@ultimat3/action';",
|
|
68
|
+
"import { defineRoute } from '@ultimat3/render';",
|
|
69
|
+
accept
|
|
70
|
+
? "import { Button } from '@ultimat3/ui';"
|
|
71
|
+
: "import { Button, Field, Input } from '@ultimat3/ui';",
|
|
72
|
+
])}
|
|
73
|
+
import styles from '${accept ? '../page.module.scss' : './page.module.scss'}';
|
|
74
|
+
|
|
75
|
+
${routeConfig(KEY[page])}
|
|
76
|
+
${
|
|
77
|
+
accept
|
|
78
|
+
? `
|
|
79
|
+
export interface InviteAcceptProps {
|
|
80
|
+
readonly query?: Readonly<Record<string, string>> | undefined;
|
|
81
|
+
}
|
|
82
|
+
`
|
|
83
|
+
: ''
|
|
84
|
+
}
|
|
85
|
+
export function Page(${accept ? 'props: InviteAcceptProps' : ''}) {${translatorBinding(module)}
|
|
86
|
+
return (
|
|
87
|
+
<main class={styles.page}>
|
|
88
|
+
<h1>{t('${KEY[page]}.title')}</h1>
|
|
89
|
+
${accept ? ACCEPT_BODY : MANAGE_BODY}
|
|
90
|
+
</main>
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
`;
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
/** The render line as Biome prints it: one line when it fits in 100 columns, else wrapped. */
|
|
97
|
+
const renderCall = (url: string): string => {
|
|
98
|
+
const inline = ` const view = await renderRoute(page, { url: 'https://example.test${url}', params: {} });`;
|
|
99
|
+
return inline.length <= 100
|
|
100
|
+
? inline
|
|
101
|
+
: ` const view = await renderRoute(page, {\n url: 'https://example.test${url}',\n params: {},\n });`;
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
const POSTS_AT = (action: string): string => `\`action="\${derivePath('${action}').path}"\``;
|
|
105
|
+
|
|
106
|
+
/** The page renders, names itself, ships no island, and posts at its actions. */
|
|
107
|
+
export const invitePageTest = (module: string | undefined, page: InvitePage): string => {
|
|
108
|
+
const actions = page === 'accept' ? ['acceptInvite'] : ['inviteMember', 'revokeInvite'];
|
|
109
|
+
const url =
|
|
110
|
+
page === 'accept' ? `${URL_PATH[page]}?orgId=org-1&token=a-token` : `${URL_PATH[page]}`;
|
|
111
|
+
return `// The page renders its forms at the routes they post to, with no script and no search listing.
|
|
112
|
+
${sortedImports([
|
|
113
|
+
catalogImport(module),
|
|
114
|
+
"import { derivePath } from '@ultimat3/action';",
|
|
115
|
+
"import { expect, renderRoute, unitTest } from '@ultimat3/testing';",
|
|
116
|
+
])}
|
|
117
|
+
import * as page from './page';
|
|
118
|
+
|
|
119
|
+
unitTest('the page renders its forms, names itself, and ships no island', async () => {${translatorBinding(module)}
|
|
120
|
+
${renderCall(url)}
|
|
121
|
+
${actions.map((action) => ` expect(view.html).toContain(${POSTS_AT(action)});`).join('\n')}${
|
|
122
|
+
page === 'accept'
|
|
123
|
+
? `
|
|
124
|
+
// The link's org and token reach the form, or every accept posts empty values.
|
|
125
|
+
expect(view.html).toContain('value="org-1"');
|
|
126
|
+
expect(view.html).toContain('value="a-token"');`
|
|
127
|
+
: ''
|
|
128
|
+
}
|
|
129
|
+
expect(view.meta.title).toBe(t('${KEY[page]}.title'));
|
|
130
|
+
expect(view.islands).toEqual([]);
|
|
131
|
+
expect(page.config.budget.js).toBe('0kb');
|
|
132
|
+
});
|
|
133
|
+
`;
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
/** Every key both pages and the invite mail read. */
|
|
137
|
+
export const INVITE_CATALOG: Readonly<Record<string, string>> = {
|
|
138
|
+
'app.auth.invites.title': 'Invite people',
|
|
139
|
+
'app.auth.invites.description': 'Invite a person into your organisation.',
|
|
140
|
+
'app.auth.invites.email': 'Email',
|
|
141
|
+
'app.auth.invites.submit': 'Send invite',
|
|
142
|
+
'app.auth.invites.revokeEmail': 'Email to remove',
|
|
143
|
+
'app.auth.invites.revoke': 'Withdraw invite',
|
|
144
|
+
'app.auth.inviteAccept.title': 'Join',
|
|
145
|
+
'app.auth.inviteAccept.description': 'Accept an invitation to an organisation.',
|
|
146
|
+
'app.auth.inviteAccept.explain': 'Sign in as the address the invite was sent to, then accept.',
|
|
147
|
+
'app.auth.inviteAccept.submit': 'Accept invite',
|
|
148
|
+
'app.auth.inviteMail.subject': 'You are invited',
|
|
149
|
+
'app.auth.inviteMail.body': 'You have been invited to join an organisation.',
|
|
150
|
+
'app.auth.inviteMail.cta': 'Accept invite',
|
|
151
|
+
};
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
// The tests `x g invite` writes beside its files: the link shape on its own, then each action RUN
|
|
2
|
+
// inside a real request context over the app's migrated database, so the paths a person takes —
|
|
3
|
+
// refused, invited, joined, replayed, removed — are what is held.
|
|
4
|
+
|
|
5
|
+
const DATABASE = `// A template restore is ~0.5 s; its first build (initdb plus every migration) is what this bounds.
|
|
6
|
+
const BOOT_MS = 120_000;
|
|
7
|
+
|
|
8
|
+
const workerDatabase = reusableDatabase(() => migratedDatabase({ root: import.meta.dir }));
|
|
9
|
+
beforeAll(async () => {
|
|
10
|
+
setDbClient(await workerDatabase());
|
|
11
|
+
}, BOOT_MS);
|
|
12
|
+
// Back to memory, so this file's database never reaches the next file's unit tests.
|
|
13
|
+
afterAll(() => setDbClient(undefined));`;
|
|
14
|
+
|
|
15
|
+
const SHARED_IMPORTS = `import { migratedDatabase } from '@ultimat3/cli';
|
|
16
|
+
import { type Actor, runWithContext } from '@ultimat3/core';
|
|
17
|
+
import { setDbClient } from '@ultimat3/db';
|
|
18
|
+
import { asCtx, defineHttpConfig, requestContext } from '@ultimat3/http';
|
|
19
|
+
import { testActor } from '@ultimat3/policy';
|
|
20
|
+
import { afterAll, beforeAll, expect, reusableDatabase, unitTest } from '@ultimat3/testing';`;
|
|
21
|
+
|
|
22
|
+
/** One POST as `actor`, the action run inside it: the response headers come back with it. */
|
|
23
|
+
const postAs = (
|
|
24
|
+
action: string,
|
|
25
|
+
path: string,
|
|
26
|
+
): string => `const post = async (input: Parameters<typeof target>[0], actor: Actor | undefined, cookie = '') => {
|
|
27
|
+
const request = requestContext({
|
|
28
|
+
url: new URL('https://app.test${path}'),
|
|
29
|
+
method: 'POST',
|
|
30
|
+
role: 'web',
|
|
31
|
+
config: defineHttpConfig({ dev: true, rateLimit: { scope: 'process' } }),
|
|
32
|
+
requestHeaders: { accept: 'application/json', cookie },
|
|
33
|
+
});
|
|
34
|
+
if (actor !== undefined) request.actor = actor;
|
|
35
|
+
const output = await runWithContext(asCtx(request), () => target(input, { ctx: asCtx(request) }));
|
|
36
|
+
return { output, request };
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const target = ${action}.named('${action}');`;
|
|
40
|
+
|
|
41
|
+
/** Org ids are uuids: \`x_users.org_id\` is one. */
|
|
42
|
+
const ORGS = `const ORG = '00000000-0000-4000-8000-0000000000a1';
|
|
43
|
+
const OTHER_ORG = '00000000-0000-4000-8000-0000000000b2';
|
|
44
|
+
const PASSWORD = 'a long scaffold test passphrase';
|
|
45
|
+
/** Issuing mails nothing in these tests: the link comes back as the returned token. */
|
|
46
|
+
const silent = { send: async () => {} };`;
|
|
47
|
+
|
|
48
|
+
export const inviteModuleTest =
|
|
49
|
+
(): string => `// The invite link is absolute and carries both halves accept needs; the flow is the one declared.
|
|
50
|
+
import { expect, unitTest } from '@ultimat3/testing';
|
|
51
|
+
import { appOrigin, INVITE_ACCEPT_PATH, INVITE_TTL_MS, inviteLink, memberInvite } from './invite';
|
|
52
|
+
|
|
53
|
+
unitTest('the mailed link is the accept page, carrying the org and the token', () => {
|
|
54
|
+
const link = new URL(inviteLink(new URL('https://app.test/x'), 'org-1')('a-token'));
|
|
55
|
+
expect(link.origin).toBe('https://app.test');
|
|
56
|
+
expect(link.pathname).toBe(INVITE_ACCEPT_PATH);
|
|
57
|
+
expect(link.searchParams.get('orgId')).toBe('org-1');
|
|
58
|
+
expect(link.searchParams.get('token')).toBe('a-token');
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
unitTest('the origin is APP_URL, and with none declared there is no link to mail', () => {
|
|
62
|
+
expect(appOrigin({ APP_URL: 'https://app.example/' }).origin).toBe('https://app.example');
|
|
63
|
+
expect(() => appOrigin({})).toThrow(expect.objectContaining({ code: 'X_ENV_MISSING' }));
|
|
64
|
+
expect(() => appOrigin({ APP_URL: ' ' })).toThrow(
|
|
65
|
+
expect.objectContaining({ code: 'X_ENV_MISSING' }),
|
|
66
|
+
);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
unitTest('an invite is the declared member-invite purpose and lives a week', () => {
|
|
70
|
+
expect(memberInvite.purpose).toBe('member-invite');
|
|
71
|
+
expect(INVITE_TTL_MS).toBe(7 * 24 * 60 * 60 * 1000);
|
|
72
|
+
});
|
|
73
|
+
`;
|
|
74
|
+
|
|
75
|
+
export const inviteMemberTest =
|
|
76
|
+
(): string => `// inviteMember, run inside a real request over the app's migrated database: an actor without the
|
|
77
|
+
// grant is refused, and one holding it mails a single-use link into their own org.
|
|
78
|
+
${SHARED_IMPORTS}
|
|
79
|
+
import { INVITE_ACCEPT_PATH } from '../invite';
|
|
80
|
+
import { inviteMember } from './invite-member';
|
|
81
|
+
|
|
82
|
+
${DATABASE}
|
|
83
|
+
|
|
84
|
+
const ORG = '00000000-0000-4000-8000-0000000000a1';
|
|
85
|
+
|
|
86
|
+
${postAs('inviteMember', '/auth/invites')}
|
|
87
|
+
|
|
88
|
+
unitTest('inviteMember is an action that takes an address and refuses the rest', async () => {
|
|
89
|
+
expect(target.kind).toBe('action');
|
|
90
|
+
await expect(target.input).toAcceptInput({ email: 'ada@example.com' });
|
|
91
|
+
await expect(target.input).toRejectInput({ email: 'not an address' });
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
unitTest('an actor without member:invite is refused', async () => {
|
|
95
|
+
const outsider = testActor('outsider', { orgId: ORG }).actor;
|
|
96
|
+
const refused = await post({ email: 'ada@example.com' }, outsider).catch((e: unknown) => e);
|
|
97
|
+
expect(refused).toBeUltimateError('X_FORBIDDEN');
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
/** \`APP_URL\` set for one test, and put back after it. */
|
|
101
|
+
const withAppUrl = async (value: string | undefined, run: () => Promise<void>): Promise<void> => {
|
|
102
|
+
const before = Bun.env.APP_URL;
|
|
103
|
+
if (value === undefined) delete Bun.env.APP_URL;
|
|
104
|
+
else Bun.env.APP_URL = value;
|
|
105
|
+
try {
|
|
106
|
+
await run();
|
|
107
|
+
} finally {
|
|
108
|
+
if (before === undefined) delete Bun.env.APP_URL;
|
|
109
|
+
else Bun.env.APP_URL = before;
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
unitTest('an inviter mails a link on the declared origin', async ({ mail, runJobs }) => {
|
|
114
|
+
const inviter = testActor('inviter', { orgId: ORG, permissions: ['member:invite'] }).actor;
|
|
115
|
+
await withAppUrl('https://invites.example', async () => {
|
|
116
|
+
// The request arrives on another host: the caller writes \`Host\`, so it never names the link.
|
|
117
|
+
const { output } = await post({ email: 'Ada@Example.com' }, inviter);
|
|
118
|
+
expect(output.ok).toBe(true);
|
|
119
|
+
});
|
|
120
|
+
await runJobs.drain();
|
|
121
|
+
const sent = mail.lastTo('ada@example.com');
|
|
122
|
+
const link = \`https://invites.example\${INVITE_ACCEPT_PATH}?orgId=\${ORG}\`;
|
|
123
|
+
expect(sent?.message.html).toContain(link);
|
|
124
|
+
expect(sent?.message.html).not.toContain('app.test');
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
unitTest('with no APP_URL declared nothing is mailed', async ({ mail, runJobs }) => {
|
|
128
|
+
const inviter = testActor('inviter', { orgId: ORG, permissions: ['member:invite'] }).actor;
|
|
129
|
+
await withAppUrl(undefined, async () => {
|
|
130
|
+
const refused = await post({ email: 'nobody@example.com' }, inviter).catch((e: unknown) => e);
|
|
131
|
+
expect(refused).toBeUltimateError('X_ENV_MISSING');
|
|
132
|
+
});
|
|
133
|
+
await runJobs.drain();
|
|
134
|
+
expect(mail.lastTo('nobody@example.com')).toBeUndefined();
|
|
135
|
+
});
|
|
136
|
+
`;
|
|
137
|
+
|
|
138
|
+
export const acceptInviteTest =
|
|
139
|
+
(): string => `// acceptInvite, run inside a real request over the app's migrated database: anonymous is refused,
|
|
140
|
+
// the invited account joins and its session is rotated, and the spent link never works again.
|
|
141
|
+
import { login, register } from '@ultimat3/auth';
|
|
142
|
+
${SHARED_IMPORTS}
|
|
143
|
+
import { appAuth } from '../auth';
|
|
144
|
+
import { memberInvite } from '../invite';
|
|
145
|
+
import { acceptInvite } from './accept-invite';
|
|
146
|
+
|
|
147
|
+
${DATABASE}
|
|
148
|
+
|
|
149
|
+
${ORGS}
|
|
150
|
+
|
|
151
|
+
${postAs('acceptInvite', '/auth/invites/accept')}
|
|
152
|
+
|
|
153
|
+
unitTest('an anonymous caller is refused before the link is read', async () => {
|
|
154
|
+
const refused = await post({ orgId: ORG, token: 'a-token' }, undefined).catch((e: unknown) => e);
|
|
155
|
+
expect(refused).toBeUltimateError('X_UNAUTHENTICATED');
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
unitTest('the invited account joins, its session is rotated, and the link is spent', async () => {
|
|
159
|
+
const user = await register(appAuth(), { email: 'join@example.com', password: PASSWORD });
|
|
160
|
+
const signedIn = await login(appAuth(), { email: 'join@example.com', password: PASSWORD });
|
|
161
|
+
const { token } = await memberInvite.invite(appAuth(), silent, {
|
|
162
|
+
orgId: ORG,
|
|
163
|
+
email: 'join@example.com',
|
|
164
|
+
locale: 'en',
|
|
165
|
+
});
|
|
166
|
+
const cookie = signedIn.cookie.split(';')[0] ?? '';
|
|
167
|
+
const actor = testActor(user.id).actor;
|
|
168
|
+
const { output, request } = await post({ orgId: ORG, token }, actor, cookie);
|
|
169
|
+
expect(output.ok).toBe(true);
|
|
170
|
+
expect((await appAuth().adapter.findUserById(user.id))?.orgId).toBe(ORG);
|
|
171
|
+
const name = appAuth().sessions.policy.cookieName;
|
|
172
|
+
expect(request.headers.getSetCookie().some((line) => line.startsWith(\`\${name}=\`))).toBe(true);
|
|
173
|
+
const replayed = await post({ orgId: ORG, token }, actor).catch((e: unknown) => e);
|
|
174
|
+
expect(replayed).toBeUltimateError('X_UNAUTHENTICATED');
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
unitTest('a link for one org redeems in no other', async () => {
|
|
178
|
+
const user = await register(appAuth(), { email: 'cross@example.com', password: PASSWORD });
|
|
179
|
+
const { token } = await memberInvite.invite(appAuth(), silent, {
|
|
180
|
+
orgId: ORG,
|
|
181
|
+
email: 'cross@example.com',
|
|
182
|
+
locale: 'en',
|
|
183
|
+
});
|
|
184
|
+
const actor = testActor(user.id).actor;
|
|
185
|
+
const refused = await post({ orgId: OTHER_ORG, token }, actor).catch((e: unknown) => e);
|
|
186
|
+
expect(refused).toBeUltimateError('X_UNAUTHENTICATED');
|
|
187
|
+
expect((await appAuth().adapter.findUserById(user.id))?.orgId).toBeNull();
|
|
188
|
+
});
|
|
189
|
+
`;
|
|
190
|
+
|
|
191
|
+
export const revokeInviteTest =
|
|
192
|
+
(): string => `// revokeInvite, run inside a real request over the app's migrated database: an actor without the
|
|
193
|
+
// grant is refused, and an inviter removes a joined member from their own org.
|
|
194
|
+
import { register } from '@ultimat3/auth';
|
|
195
|
+
${SHARED_IMPORTS}
|
|
196
|
+
import { appAuth } from '../auth';
|
|
197
|
+
import { memberInvite } from '../invite';
|
|
198
|
+
import { revokeInvite } from './revoke-invite';
|
|
199
|
+
|
|
200
|
+
${DATABASE}
|
|
201
|
+
|
|
202
|
+
${ORGS}
|
|
203
|
+
|
|
204
|
+
${postAs('revokeInvite', '/auth/invites')}
|
|
205
|
+
|
|
206
|
+
unitTest('an actor without member:invite is refused', async () => {
|
|
207
|
+
const outsider = testActor('outsider', { orgId: ORG }).actor;
|
|
208
|
+
const refused = await post({ email: 'ada@example.com' }, outsider).catch((e: unknown) => e);
|
|
209
|
+
expect(refused).toBeUltimateError('X_FORBIDDEN');
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
unitTest('a joined member is removed from the inviter org, never from another', async () => {
|
|
213
|
+
const user = await register(appAuth(), { email: 'leave@example.com', password: PASSWORD });
|
|
214
|
+
const { token } = await memberInvite.invite(appAuth(), silent, {
|
|
215
|
+
orgId: ORG,
|
|
216
|
+
email: 'leave@example.com',
|
|
217
|
+
locale: 'en',
|
|
218
|
+
});
|
|
219
|
+
await memberInvite.accept(appAuth(), { orgId: ORG, token, userId: user.id });
|
|
220
|
+
const elsewhere = testActor('elsewhere', { orgId: OTHER_ORG, permissions: ['member:invite'] });
|
|
221
|
+
const untouched = await post({ email: 'leave@example.com' }, elsewhere.actor);
|
|
222
|
+
expect(untouched.output.memberRemoved).toBe(false);
|
|
223
|
+
const inviter = testActor('inviter', { orgId: ORG, permissions: ['member:invite'] }).actor;
|
|
224
|
+
const { output } = await post({ email: 'leave@example.com' }, inviter);
|
|
225
|
+
expect(output.memberRemoved).toBe(true);
|
|
226
|
+
expect((await appAuth().adapter.findUserById(user.id))?.orgId).toBeNull();
|
|
227
|
+
});
|
|
228
|
+
`;
|