@ultimat3/cli 31.24.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 +2 -1
- package/README.md +1 -0
- package/package.json +29 -29
- package/src/cmd-generate-spec.ts +3 -2
- package/src/cmd-generate.ts +4 -0
- package/src/db-diagnostics.ts +6 -0
- 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/metrics-endpoint.ts +5 -3
- package/src/role-replicator.ts +26 -4
- package/src/runtime-liveness.ts +23 -0
- 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-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 +3 -0
- 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/Realtime.md +17 -1
- package/wiki/Scheduled-Tasks.md +1 -1
- package/wiki/Shapes.md +3 -2
- package/wiki/Tutorial-04-Jobs-And-Realtime.md +1 -1
|
@@ -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
|
+
`;
|
|
@@ -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
|
+
`;
|