pgkiln 0.36.0 → 0.38.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/SECURITY.md +12 -9
- package/db/migrations/090_workspace_isolation.sql +512 -0
- package/db/migrations/091_workspace_service.sql +20 -0
- package/db/migrations/092_app_groups.sql +23 -0
- package/docs/apex-feature-parity.md +16 -11
- package/docs/guide/03-builder.md +125 -11
- package/docs/guide/12-development.md +12 -2
- package/examples/gallery/README.md +13 -0
- package/examples/gallery/gallery.json +20 -0
- package/examples/gallery/starters/asset-inventory.json +30 -0
- package/examples/gallery/starters/contacts.json +41 -0
- package/examples/gallery/starters/event-registrations.json +29 -0
- package/examples/gallery/starters/expense-claims.json +32 -0
- package/examples/gallery/starters/team-tasks.json +35 -0
- package/examples/hr/hr_40_sample_data.sql +1 -1
- package/package.json +1 -1
- package/public/builder.css +91 -0
- package/src/app.ts +24 -0
- package/src/automations.ts +3 -2
- package/src/builder/advisor.ts +11 -5
- package/src/builder/ai-builder.ts +27 -18
- package/src/builder/app-groups.ts +132 -0
- package/src/builder/blueprints.ts +21 -7
- package/src/builder/code-editor.ts +3 -2
- package/src/builder/cross-app.ts +106 -0
- package/src/builder/dataload.ts +24 -14
- package/src/builder/ddl-tools.ts +7 -4
- package/src/builder/documents.ts +2 -1
- package/src/builder/gallery.ts +154 -0
- package/src/builder/home.ts +33 -10
- package/src/builder/newapp.ts +21 -3
- package/src/builder/quicksql.ts +3 -2
- package/src/builder/report-settings.ts +4 -2
- package/src/builder/routes.ts +78 -26
- package/src/builder/sampledata.ts +22 -18
- package/src/builder/scripts.ts +31 -16
- package/src/builder/sql.ts +119 -15
- package/src/builder/ui.ts +30 -7
- package/src/builder/unload.ts +3 -2
- package/src/builder/workspaces.ts +291 -22
- package/src/cli/replace.ts +2 -0
- package/src/db.ts +36 -6
- package/src/ddl.ts +2 -1
- package/src/debug.ts +3 -2
- package/src/migrate.ts +3 -0
- package/src/process-jobs.ts +7 -2
- package/src/restsync.ts +3 -2
- package/src/runtime/calendar.ts +2 -1
- package/src/runtime/routes.ts +4 -1
- package/src/sampledata.ts +3 -3
- package/src/session.ts +18 -4
- package/src/websources.ts +3 -1
- package/src/workflow.ts +65 -9
- package/src/workspace-db.ts +166 -0
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import type { FastifyInstance } from 'fastify';
|
|
2
|
+
import { owner } from '../db.ts';
|
|
3
|
+
import { html, raw } from '../html.ts';
|
|
4
|
+
import { icon } from '../icons.ts';
|
|
5
|
+
import { BASE, developer, region, send, shell, type Req } from './ui.ts';
|
|
6
|
+
import { currentWorkspace } from './workspaces.ts';
|
|
7
|
+
|
|
8
|
+
// Cross-application reports (sprint 61; APEX: Workspace Utilities → Cross
|
|
9
|
+
// Application Reports): one read-only report per topic over every application
|
|
10
|
+
// of the current workspace. Each query takes the workspace id as $1 and
|
|
11
|
+
// returns app_id and app (the name) first; those become a link.
|
|
12
|
+
|
|
13
|
+
interface Report {
|
|
14
|
+
title: string;
|
|
15
|
+
about: string;
|
|
16
|
+
columns: [key: string, label: string, cls?: 'num'][];
|
|
17
|
+
sql: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** The current workspace's applications (alias a). */
|
|
21
|
+
const IN_WS = 'meta.app_workspace(a.id) = $1';
|
|
22
|
+
|
|
23
|
+
export const REPORTS: Record<string, Report> = {
|
|
24
|
+
attributes: {
|
|
25
|
+
title: 'Application attributes',
|
|
26
|
+
about: 'The main settings of every application: type, sign-in, availability, build status, debug level, language and database role.',
|
|
27
|
+
columns: [['alias', 'Alias'], ['app_type', 'Type'], ['authentication', 'Sign-in'], ['availability', 'Availability'], ['build_status', 'Build status'], ['debug_level', 'Debug', 'num'], ['language', 'Language'], ['db_role', 'Database role'], ['updated', 'Updated']],
|
|
28
|
+
sql: `select a.id as app_id, a.name as app, a.alias, a.app_type, a.authentication, a.availability, a.build_status, a.debug_level,
|
|
29
|
+
a.language, coalesce(a.db_role, '(runtime connection)') as db_role, to_char(a.updated_at, 'YYYY-MM-DD HH24:MI') as updated
|
|
30
|
+
from meta.app a where ${IN_WS} order by lower(a.name)`,
|
|
31
|
+
},
|
|
32
|
+
'build-options': {
|
|
33
|
+
title: 'Build options',
|
|
34
|
+
about: 'The build options of every application and whether their components are included.',
|
|
35
|
+
columns: [['name', 'Build option'], ['status', 'Status'], ['description', 'Description']],
|
|
36
|
+
sql: `select a.id as app_id, a.name as app, b.name, b.status, b.description
|
|
37
|
+
from meta.app a join meta.build_option b on b.app_id = a.id where ${IN_WS} order by lower(a.name), b.name`,
|
|
38
|
+
},
|
|
39
|
+
comments: {
|
|
40
|
+
title: 'Developer comments',
|
|
41
|
+
about: 'The developers\' comments on applications and pages, newest first.',
|
|
42
|
+
columns: [['page_no', 'Page', 'num'], ['author', 'Author'], ['created', 'Written'], ['body', 'Comment']],
|
|
43
|
+
sql: `select a.id as app_id, a.name as app, c.page_no, c.author, to_char(c.created_at, 'YYYY-MM-DD HH24:MI') as created, left(c.body, 500) as body
|
|
44
|
+
from meta.app a join meta.dev_comment c on c.app_id = a.id where ${IN_WS} order by c.created_at desc limit 500`,
|
|
45
|
+
},
|
|
46
|
+
authentication: {
|
|
47
|
+
title: 'Authentication',
|
|
48
|
+
about: 'How people sign in to every application: the sign-in method, password sign-in, identity providers and LDAP directories, access control, the login page and Forgot password.',
|
|
49
|
+
columns: [['authentication', 'Sign-in'], ['local_login', 'Passwords'], ['providers', 'Identity providers'], ['ldap', 'LDAP directories'], ['access_control', 'Access'], ['remember_me_days', 'Keep me signed in (days)', 'num'], ['login_page', 'Login page', 'num'], ['password_reset', 'Forgot password']],
|
|
50
|
+
sql: `select a.id as app_id, a.name as app, a.authentication, case when a.local_login then 'yes' else 'no' end as local_login,
|
|
51
|
+
array_to_string(a.sso_providers, ', ') as providers, array_to_string(a.ldap_directories, ', ') as ldap,
|
|
52
|
+
a.access_control, a.remember_me_days, a.login_page, case when a.password_reset then 'yes' else 'no' end as password_reset
|
|
53
|
+
from meta.app a where ${IN_WS} order by lower(a.name)`,
|
|
54
|
+
},
|
|
55
|
+
authorization: {
|
|
56
|
+
title: 'Authorization schemes',
|
|
57
|
+
about: 'The authorization schemes of every application: their type and what they check.',
|
|
58
|
+
columns: [['name', 'Scheme'], ['type', 'Type'], ['value', 'Checks'], ['error_message', 'Error message']],
|
|
59
|
+
sql: `select a.id as app_id, a.name as app, s.name, s.type, left(s.value, 300) as value, s.error_message
|
|
60
|
+
from meta.app a join meta.authz_scheme s on s.app_id = a.id where ${IN_WS} order by lower(a.name), s.name`,
|
|
61
|
+
},
|
|
62
|
+
'password-items': {
|
|
63
|
+
title: 'Password items',
|
|
64
|
+
about: 'Every password item: pgkiln never shows their values again, never keeps them in session state for the next page and never writes them to the debug log.',
|
|
65
|
+
columns: [['page_no', 'Page', 'num'], ['name', 'Item'], ['label', 'Label'], ['reveal', 'Show button'], ['required', 'Required']],
|
|
66
|
+
sql: `select a.id as app_id, a.name as app, p.page_no, i.name, i.label,
|
|
67
|
+
case when (i.config ->> 'reveal')::boolean then 'yes' else 'no' end as reveal, case when i.required then 'yes' else 'no' end as required
|
|
68
|
+
from meta.app a join meta.page p on p.app_id = a.id join meta.item i on i.page_id = p.id
|
|
69
|
+
where ${IN_WS} and i.type = 'password' order by lower(a.name), p.page_no, i.seq`,
|
|
70
|
+
},
|
|
71
|
+
theme: {
|
|
72
|
+
title: 'Theme summary',
|
|
73
|
+
about: 'The look of every application: base style, Theme Roller style, navigation and the colours it sets.',
|
|
74
|
+
columns: [['base', 'Base style'], ['style', 'Style'], ['nav', 'Navigation'], ['colors', 'Colours set', 'num'], ['pwa', 'Installable (PWA)']],
|
|
75
|
+
sql: `select a.id as app_id, a.name as app, coalesce(a.theme ->> 'base', 'default') as base, coalesce(a.theme ->> 'style', '-') as style,
|
|
76
|
+
coalesce(a.theme ->> 'nav', 'side') as nav,
|
|
77
|
+
(select count(*) from jsonb_object_keys(coalesce(a.theme -> 'colors', '{}'::jsonb)))::int as colors,
|
|
78
|
+
case when a.pwa then 'yes' else 'no' end as pwa
|
|
79
|
+
from meta.app a where ${IN_WS} order by lower(a.name)`,
|
|
80
|
+
},
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
/** The links in Workspace utilities' side column. */
|
|
84
|
+
export const crossAppLinks = () =>
|
|
85
|
+
Object.entries(REPORTS).map(([k, r]) => html`<li><a href="${BASE}/utilities/reports/${k}">${r.title}${icon('chevron')}</a></li>`);
|
|
86
|
+
|
|
87
|
+
export async function crossAppRoutes(app: FastifyInstance) {
|
|
88
|
+
app.get(`${BASE}/utilities/reports/:kind`, async (req: Req, reply) => {
|
|
89
|
+
const s = await developer(req, reply);
|
|
90
|
+
if (!s) return;
|
|
91
|
+
const r = Object.hasOwn(REPORTS, req.params.kind) ? REPORTS[req.params.kind] : undefined;
|
|
92
|
+
if (!r) return reply.code(404).send('Not found');
|
|
93
|
+
const rows = (await owner.query(r.sql, [currentWorkspace(s)])).rows;
|
|
94
|
+
const cell = (v: unknown) => (v === null || v === undefined || v === '' ? html`<span class="muted">-</span>` : String(v));
|
|
95
|
+
const main = html`<div class="title-row"><h1>${r.title}</h1></div>
|
|
96
|
+
<p class="muted u-mt0">${r.about} Applications of the workspace ${s.workspace?.name ?? ''}.</p>
|
|
97
|
+
<nav class="ide-tabs u-mb1" aria-label="Cross-application reports">${Object.entries(REPORTS).map(([k, x]) =>
|
|
98
|
+
html`<a class="ide-tab" href="${BASE}/utilities/reports/${k}"${k === req.params.kind ? raw(' aria-current="page"') : ''}><span>${x.title}</span></a>`)}</nav>
|
|
99
|
+
${region(r.title, rows.length
|
|
100
|
+
? html`<div class="table-wrap"><table class="report report-reflow"><thead><tr><th>Application</th>${r.columns.map(([, l, c]) => html`<th${c ? raw(` class="${c}"`) : ''}>${l}</th>`)}</tr></thead>
|
|
101
|
+
<tbody>${rows.map((row) => html`<tr><td data-label="Application"><a href="${BASE}/apps/${row.app_id}">${row.app}</a></td>
|
|
102
|
+
${r.columns.map(([k, l, c]) => html`<td data-label="${l}"${c ? raw(` class="${c}"`) : ''}>${cell(row[k])}</td>`)}</tr>`)}</tbody></table></div>`
|
|
103
|
+
: html`<p class="muted">Nothing to report in this workspace.</p>`, html`<span class="count">${rows.length}</span>`)}`;
|
|
104
|
+
return send(reply, s, shell(s, r.title, [['App Builder', BASE], ['Workspace utilities', `${BASE}/utilities`], [r.title]], main));
|
|
105
|
+
});
|
|
106
|
+
}
|
package/src/builder/dataload.ts
CHANGED
|
@@ -26,6 +26,7 @@ import { readMultipart } from '../runtime/files.ts';
|
|
|
26
26
|
import type { Session } from '../session.ts';
|
|
27
27
|
import type { ComponentSpec } from './components.ts';
|
|
28
28
|
import { back, BASE, csrf, developer, flash, region, send, shell, workshopTabs, type Body, type Req } from './ui.ts';
|
|
29
|
+
import { appWorkspace, currentWorkspace, workshopDb } from './workspaces.ts';
|
|
29
30
|
|
|
30
31
|
// SQL Workshop → Load Data: upload a CSV/TSV/XLSX/JSON/XML file, preview it,
|
|
31
32
|
// and load it into a new table (column types inferred) or an existing one
|
|
@@ -73,17 +74,23 @@ export const DATA_LOAD_DEF_SPEC: ComponentSpec = {
|
|
|
73
74
|
export const dataLoadDefExtras = (row: { id: number }) =>
|
|
74
75
|
html`<p class="u-mt1"><a class="btn" href="${BASE}/sql/load?definition=${row.id}">${icon('upload')} Load a file with this definition</a></p>`;
|
|
75
76
|
|
|
76
|
-
|
|
77
|
+
/** The data load definitions of the current workspace's applications. */
|
|
78
|
+
async function definitions(s: Session) {
|
|
77
79
|
return (
|
|
78
80
|
await owner.query<{ id: number; app_id: number; app_name: string; name: string; table_name: string }>(
|
|
79
|
-
|
|
81
|
+
`select d.id, d.app_id, a.name as app_name, d.name, d.table_name from meta.data_load_def d join meta.app a on a.id = d.app_id
|
|
82
|
+
where meta.app_workspace(a.id) = $1 order by a.name, d.name`,
|
|
83
|
+
[currentWorkspace(s)],
|
|
80
84
|
)
|
|
81
85
|
).rows;
|
|
82
86
|
}
|
|
83
87
|
|
|
84
|
-
async function definition(id: unknown) {
|
|
88
|
+
async function definition(s: Session, id: unknown) {
|
|
85
89
|
if (!/^\d+$/.test(String(id ?? ''))) return undefined;
|
|
86
|
-
return owner.one<DataLoadDefinition & { id: number; app_id: number }>(
|
|
90
|
+
return owner.one<DataLoadDefinition & { id: number; app_id: number }>(
|
|
91
|
+
'select * from meta.data_load_def where id = $1 and meta.app_workspace(app_id) = $2',
|
|
92
|
+
[id, currentWorkspace(s)],
|
|
93
|
+
);
|
|
87
94
|
}
|
|
88
95
|
|
|
89
96
|
export const MAX_MB = Number(process.env.DATA_LOAD_MAX_MB ?? 50);
|
|
@@ -142,7 +149,7 @@ export async function dataLoadRoutes(app: FastifyInstance) {
|
|
|
142
149
|
});
|
|
143
150
|
|
|
144
151
|
const uploadForm = async (s: Session, error?: string, chosen?: string) => {
|
|
145
|
-
const defs = await definitions();
|
|
152
|
+
const defs = await definitions(s);
|
|
146
153
|
return region(
|
|
147
154
|
'Load data from a file',
|
|
148
155
|
html`${error ? html`<div class="alert alert-error" role="alert">${error}</div>` : ''}
|
|
@@ -180,7 +187,7 @@ export async function dataLoadRoutes(app: FastifyInstance) {
|
|
|
180
187
|
if (!s) return;
|
|
181
188
|
if (!file) return page(s, reply, await uploadForm(s, 'Choose a file.'));
|
|
182
189
|
if (file.truncated) return page(s, reply, await uploadForm(s, `The file is larger than ${MAX_MB} MB.`));
|
|
183
|
-
const def = await definition(req.body?.definition);
|
|
190
|
+
const def = await definition(s, req.body?.definition);
|
|
184
191
|
const rowTag = (req.body?.row_tag ?? '').trim();
|
|
185
192
|
try {
|
|
186
193
|
if (def) await parseFile(file.filename, file.data, { headers: def.headers, format: def.format, rowTag: def.row_tag });
|
|
@@ -203,7 +210,7 @@ export async function dataLoadRoutes(app: FastifyInstance) {
|
|
|
203
210
|
if (!f) return reply.redirect(`${BASE}/sql/load`);
|
|
204
211
|
const headers = (req.query.h ?? req.body?.h) !== '0';
|
|
205
212
|
const rowTag = (req.query.rt ?? req.body?.rt ?? '').trim();
|
|
206
|
-
const def = await definition(req.query.d ?? req.body?.d);
|
|
213
|
+
const def = await definition(s, req.query.d ?? req.body?.d);
|
|
207
214
|
let sheet: Sheet;
|
|
208
215
|
try {
|
|
209
216
|
sheet = def
|
|
@@ -256,17 +263,19 @@ export async function dataLoadRoutes(app: FastifyInstance) {
|
|
|
256
263
|
${skip}
|
|
257
264
|
<div class="buttons"><button class="btn btn-hot">Create table and load</button></div></form>`;
|
|
258
265
|
|
|
266
|
+
const db = await workshopDb(s);
|
|
259
267
|
const tables = (
|
|
260
|
-
await
|
|
268
|
+
await db.query(
|
|
261
269
|
`select c.oid::regclass::text as name from pg_class c join pg_namespace n on n.oid = c.relnamespace
|
|
262
|
-
where c.relkind in ('r', 'p') and n.nspname !~ '^pg_' and n.nspname not in ('information_schema', 'meta')
|
|
270
|
+
where c.relkind in ('r', 'p') and n.nspname !~ '^pg_' and n.nspname not in ('information_schema', 'meta')
|
|
271
|
+
and has_table_privilege(c.oid, 'INSERT') order by 1`,
|
|
263
272
|
)
|
|
264
273
|
).rows.map((r) => r.name as string);
|
|
265
274
|
const chosen = tables.find((t) => t === (req.query.table ?? req.body?.table));
|
|
266
|
-
const apps = (await owner.query<{ id: number; name: string }>('select id, name from meta.app order by name')).rows;
|
|
275
|
+
const apps = (await owner.query<{ id: number; name: string }>('select id, name from meta.app where meta.app_workspace(id) = $1 order by name', [currentWorkspace(s)])).rows;
|
|
267
276
|
let mapping: Raw | '' = '';
|
|
268
277
|
if (chosen) {
|
|
269
|
-
const cols = await
|
|
278
|
+
const cols = await db.tx((c) => tableColumns(c, chosen));
|
|
270
279
|
const auto = autoMap(sheet.headers, cols);
|
|
271
280
|
const hasPk = cols.some((c) => c.pk);
|
|
272
281
|
mapping = html`<form method="post" action="${action}">${hidden}<input type="hidden" name="target" value="existing"><input type="hidden" name="table" value="${chosen}">
|
|
@@ -335,6 +344,7 @@ export async function dataLoadRoutes(app: FastifyInstance) {
|
|
|
335
344
|
const mode = ['append', 'replace', 'merge'].includes(b.mode ?? '') ? b.mode : 'append';
|
|
336
345
|
const format = sheet instanceof Error ? 'auto' : sheet.format;
|
|
337
346
|
try {
|
|
347
|
+
if (!/^\d{1,9}$/.test(String(b.def_app ?? '')) || (await appWorkspace(String(b.def_app))) !== currentWorkspace(s)) throw new LoadError('Choose an application of this workspace.');
|
|
338
348
|
const r = await owner.one(
|
|
339
349
|
`insert into meta.data_load_def (app_id, name, table_name, format, headers, row_tag, mode, skip_errors, columns)
|
|
340
350
|
values ($1, $2, $3, $4, $5, $6, $7, $8, $9) returning id, app_id`,
|
|
@@ -344,7 +354,7 @@ export async function dataLoadRoutes(app: FastifyInstance) {
|
|
|
344
354
|
return back(reply, s, `${BASE}/apps/${r!.app_id}/shared?c=data_load_def-${r!.id}`);
|
|
345
355
|
} catch (e) {
|
|
346
356
|
const code = (e as { code?: string }).code;
|
|
347
|
-
if (!code?.startsWith('23') && code !== '22P02') throw e;
|
|
357
|
+
if (!(e instanceof LoadError) && !code?.startsWith('23') && code !== '22P02') throw e;
|
|
348
358
|
reply.code(422);
|
|
349
359
|
return targetPage(req, reply, s, html`<div class="alert alert-error" role="alert">The definition could not be saved: ${
|
|
350
360
|
code === '23505' ? `the application already has a definition named ${name}.` : (e as Error).message}</div>`);
|
|
@@ -354,10 +364,10 @@ export async function dataLoadRoutes(app: FastifyInstance) {
|
|
|
354
364
|
let error: string | undefined;
|
|
355
365
|
let failed = false;
|
|
356
366
|
try {
|
|
357
|
-
const def = b.target === 'definition' ? await definition(b.d) : undefined;
|
|
367
|
+
const def = b.target === 'definition' ? await definition(s, b.d) : undefined;
|
|
358
368
|
const sheet = def ? null : await parseFile(f.filename, f.content, { headers, rowTag });
|
|
359
369
|
const opts = { skipErrors: b.skip_errors === 'true', firstRow: headers && sheet && (sheet.format === 'csv' || sheet.format === 'xlsx') ? 2 : 1 };
|
|
360
|
-
result = await
|
|
370
|
+
result = await (await workshopDb(s)).tx(async (c) => {
|
|
361
371
|
if (def) return loadWithDefinition(c, def, f);
|
|
362
372
|
if (!sheet) throw new LoadError('The data load definition no longer exists.');
|
|
363
373
|
if (b.target === 'new') {
|
package/src/builder/ddl-tools.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { html, raw, type Raw } from '../html.ts';
|
|
|
6
6
|
import { icon } from '../icons.ts';
|
|
7
7
|
import { clientIp, logActivity } from '../session.ts';
|
|
8
8
|
import { BASE, developer, region, send, shell, workshopTabs, type Req } from './ui.ts';
|
|
9
|
+
import { workshopDb } from './workspaces.ts';
|
|
9
10
|
|
|
10
11
|
// SQL Workshop → Generate DDL and Schema Comparison (APEX: SQL Workshop →
|
|
11
12
|
// Utilities). Both only read the catalog (src/ddl.ts); the scripts they
|
|
@@ -32,7 +33,8 @@ export async function ddlToolRoutes(app: FastifyInstance) {
|
|
|
32
33
|
app.get(`${BASE}/sql/ddl`, async (req: Req, reply) => {
|
|
33
34
|
const s = await developer(req, reply);
|
|
34
35
|
if (!s) return;
|
|
35
|
-
const
|
|
36
|
+
const db = await workshopDb(s);
|
|
37
|
+
const schemas = await userSchemas(db, { usable: db !== owner });
|
|
36
38
|
const q = req.query ?? {};
|
|
37
39
|
const schema = schemas.includes(q.schema ?? '') ? q.schema! : '';
|
|
38
40
|
// the first visit: every type, comments and grants
|
|
@@ -42,7 +44,7 @@ export async function ddlToolRoutes(app: FastifyInstance) {
|
|
|
42
44
|
let result: Raw | '' = '';
|
|
43
45
|
if (schema) {
|
|
44
46
|
try {
|
|
45
|
-
const objects = pick(await readSchema(
|
|
47
|
+
const objects = pick(await readSchema(db.pool, schema), types, opts);
|
|
46
48
|
const script = ddlScript(schema, objects);
|
|
47
49
|
await logActivity({ username: s.username, event: 'generate_ddl', ip: clientIp(req), detail: `${schema}: ${objects.length} objects` });
|
|
48
50
|
if (q.download === '1')
|
|
@@ -73,7 +75,8 @@ export async function ddlToolRoutes(app: FastifyInstance) {
|
|
|
73
75
|
app.get(`${BASE}/sql/compare`, async (req: Req, reply) => {
|
|
74
76
|
const s = await developer(req, reply);
|
|
75
77
|
if (!s) return;
|
|
76
|
-
const
|
|
78
|
+
const db = await workshopDb(s);
|
|
79
|
+
const schemas = await userSchemas(db, { usable: db !== owner });
|
|
77
80
|
const q = req.query ?? {};
|
|
78
81
|
const source = schemas.includes(q.source ?? '') ? q.source! : '';
|
|
79
82
|
const target = schemas.includes(q.target ?? '') ? q.target! : '';
|
|
@@ -81,7 +84,7 @@ export async function ddlToolRoutes(app: FastifyInstance) {
|
|
|
81
84
|
if (source && target && source === target) result = html`<div class="alert alert-error" role="alert">Choose two different schemas.</div>`;
|
|
82
85
|
else if (source && target) {
|
|
83
86
|
try {
|
|
84
|
-
const [a, b] = await Promise.all([readSchema(
|
|
87
|
+
const [a, b] = await Promise.all([readSchema(db.pool, source), readSchema(db.pool, target)]);
|
|
85
88
|
const { differences, same } = compare(a, b);
|
|
86
89
|
const script = changeScript(source, target, a, b);
|
|
87
90
|
await logActivity({ username: s.username, event: 'schema_compare', ip: clientIp(req), detail: `${source} → ${target}: ${differences.length} differences` });
|
package/src/builder/documents.ts
CHANGED
|
@@ -2,6 +2,7 @@ import type { FastifyInstance } from 'fastify';
|
|
|
2
2
|
import pg from 'pg';
|
|
3
3
|
import { applyBinds } from '../binds.ts';
|
|
4
4
|
import { owner } from '../db.ts';
|
|
5
|
+
import { devDbForApp } from '../workspace-db.ts';
|
|
5
6
|
import { html } from '../html.ts';
|
|
6
7
|
import { english } from '../i18n.ts';
|
|
7
8
|
import { documentData, documentPdf, fillTemplate, TemplateError } from '../runtime/document.ts';
|
|
@@ -42,7 +43,7 @@ export async function documentRoutes(app: FastifyInstance) {
|
|
|
42
43
|
const tpl = a && /^\d+$/.test(tid) ? await owner.one('select * from meta.document_template where id = $1 and app_id = $2', [tid, a.id]) : undefined;
|
|
43
44
|
if (!a || !tpl) return reply.code(404).send('Not found');
|
|
44
45
|
const binds = previewBinds(String(req.query.binds ?? ''));
|
|
45
|
-
const c = await
|
|
46
|
+
const c = await (await devDbForApp(a.id)).pool.connect();
|
|
46
47
|
try {
|
|
47
48
|
await c.query('begin');
|
|
48
49
|
await c.query(`set local statement_timeout = '10s'`);
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import type { FastifyInstance } from 'fastify';
|
|
4
|
+
import { owner, ownerUrl } from '../db.ts';
|
|
5
|
+
import { root } from '../env.ts';
|
|
6
|
+
import { html, raw } from '../html.ts';
|
|
7
|
+
import { icon } from '../icons.ts';
|
|
8
|
+
import { migrate } from '../migrate.ts';
|
|
9
|
+
import { clientIp, logActivity } from '../session.ts';
|
|
10
|
+
import { openBlueprint } from './blueprints.ts';
|
|
11
|
+
import { isAdmin } from './locks.ts';
|
|
12
|
+
import { back, BASE, csrf, developer, flash, send, shell, type Req } from './ui.ts';
|
|
13
|
+
import { currentWorkspace, inWorkspaceSql, placeApp } from './workspaces.ts';
|
|
14
|
+
import { workspacesChanged } from '../workspace-db.ts';
|
|
15
|
+
|
|
16
|
+
// The App Gallery (sprint 61; APEX: App Gallery with Sample, Starter and Custom Apps).
|
|
17
|
+
//
|
|
18
|
+
// Sample apps applications shipped with pgkiln (examples/): an administrator installs
|
|
19
|
+
// one with its schema, data and demo accounts, as `pgkiln migrate --example`;
|
|
20
|
+
// Starter apps blueprints shipped with pgkiln (examples/gallery/starters/): Install opens
|
|
21
|
+
// the blueprint's review, and the developer creates the application from it
|
|
22
|
+
// in the current workspace (a new role and schema, like every new application);
|
|
23
|
+
// Custom apps the workspace's boilerplate applications: Create application starts from one.
|
|
24
|
+
//
|
|
25
|
+
// The list is examples/gallery/gallery.json.
|
|
26
|
+
|
|
27
|
+
interface Sample {
|
|
28
|
+
key: string;
|
|
29
|
+
title: string;
|
|
30
|
+
alias: string;
|
|
31
|
+
icon: string;
|
|
32
|
+
description: string;
|
|
33
|
+
example?: string;
|
|
34
|
+
file?: string;
|
|
35
|
+
}
|
|
36
|
+
interface Starter {
|
|
37
|
+
key: string;
|
|
38
|
+
title: string;
|
|
39
|
+
icon: string;
|
|
40
|
+
description: string;
|
|
41
|
+
file: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const GALLERY = join(root, 'examples', 'gallery');
|
|
45
|
+
const KEY = /^[a-z][a-z0-9-]{0,40}$/;
|
|
46
|
+
|
|
47
|
+
function catalog(): { samples: Sample[]; starters: Starter[] } {
|
|
48
|
+
try {
|
|
49
|
+
const c = JSON.parse(readFileSync(join(GALLERY, 'gallery.json'), 'utf8'));
|
|
50
|
+
return { samples: Array.isArray(c.samples) ? c.samples : [], starters: Array.isArray(c.starters) ? c.starters : [] };
|
|
51
|
+
} catch {
|
|
52
|
+
return { samples: [], starters: [] };
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** A file of the gallery: only names from the catalogue, never a path from the request. */
|
|
57
|
+
const galleryFile = (rel: string) => readFileSync(join(rel.includes('/') ? GALLERY : join(root, 'examples'), rel), 'utf8');
|
|
58
|
+
|
|
59
|
+
type Tab = 'samples' | 'starters' | 'custom';
|
|
60
|
+
|
|
61
|
+
export async function galleryRoutes(app: FastifyInstance) {
|
|
62
|
+
app.get(`${BASE}/gallery`, async (req: Req, reply) => {
|
|
63
|
+
const s = await developer(req, reply);
|
|
64
|
+
if (!s) return;
|
|
65
|
+
const tab: Tab = (['samples', 'starters', 'custom'] as const).find((t) => t === req.query?.tab) ?? 'samples';
|
|
66
|
+
const admin = await isAdmin(s.username);
|
|
67
|
+
const { samples, starters } = catalog();
|
|
68
|
+
const installed = new Map(
|
|
69
|
+
(await owner.query<{ alias: string; id: number }>('select alias, id from meta.app where alias = any($1)', [samples.map((x) => x.alias)])).rows.map((r) => [r.alias, r.id]),
|
|
70
|
+
);
|
|
71
|
+
const custom = (await owner.query<{ id: number; name: string; description: string | null }>(
|
|
72
|
+
`select a.id, a.name, null::text as description from meta.app a where a.app_type = 'boilerplate' and ${inWorkspaceSql('a', 1)} order by lower(a.name), a.id`,
|
|
73
|
+
[currentWorkspace(s)],
|
|
74
|
+
)).rows;
|
|
75
|
+
const card = (ic: string, title: string, by: string, text: string, action: unknown) =>
|
|
76
|
+
html`<article class="gal-card" data-filter-row><div class="gal-head"><span class="gal-icon">${icon(ic)}</span><div><h2>${title}</h2><span class="muted small">${by}</span></div></div>
|
|
77
|
+
<p>${text}</p><div class="gal-foot">${action}</div></article>`;
|
|
78
|
+
const tabs = html`<nav class="gal-tabs segmented" aria-label="Kinds of applications">${([['samples', 'Sample Apps'], ['starters', 'Starter Apps'], ['custom', 'Custom Apps']] as const).map(([t, l]) =>
|
|
79
|
+
html`<a href="${BASE}/gallery?tab=${t}"${tab === t ? raw(' aria-current="page"') : ''}>${l}</a>`)}</nav>`;
|
|
80
|
+
const cards =
|
|
81
|
+
tab === 'samples'
|
|
82
|
+
? samples.map((x) => card(x.icon, x.title, 'pgkiln', x.description,
|
|
83
|
+
installed.has(x.alias)
|
|
84
|
+
? html`<span class="tag tag-ok">Installed</span><a class="btn btn-sm" href="/a/${x.alias}" target="_blank" rel="noopener">Run</a><a class="btn btn-sm" href="${BASE}/apps/${installed.get(x.alias)}">Edit</a>`
|
|
85
|
+
: admin
|
|
86
|
+
? html`<form method="post" action="${BASE}/gallery/samples/${x.key}">${csrf(s)}<button class="btn btn-hot btn-sm" data-confirm="Install ${x.title}? It adds its own schema, data and demo accounts with known passwords: not for a production instance.">Install</button></form>`
|
|
87
|
+
: html`<span class="muted small">An administrator installs it.</span>`))
|
|
88
|
+
: tab === 'starters'
|
|
89
|
+
? starters.map((x) => card(x.icon, x.title, 'pgkiln', x.description,
|
|
90
|
+
html`<form method="post" action="${BASE}/gallery/starters/${x.key}">${csrf(s)}<button class="btn btn-hot btn-sm">Install</button></form>`))
|
|
91
|
+
: custom.map((x) => card('copy', x.name, 'This workspace', x.description ?? 'A boilerplate application: a new application starts with its pages, shared components and settings.',
|
|
92
|
+
html`<a class="btn btn-hot btn-sm" href="${BASE}/create?boilerplate=${x.id}">Create from it</a><a class="btn btn-sm" href="${BASE}/apps/${x.id}">Edit</a>`));
|
|
93
|
+
const empty = tab === 'custom'
|
|
94
|
+
? html`<p class="muted">No custom apps yet: make an application of type <em>Boilerplate</em> (Application settings → Application type) and it appears here.</p>`
|
|
95
|
+
: html`<p class="muted">The gallery is empty.</p>`;
|
|
96
|
+
const intro = {
|
|
97
|
+
samples: 'Applications that show what pgkiln can do, with their own data and demo accounts. Install them on a development or demo instance.',
|
|
98
|
+
starters: 'Small, ready-to-use applications. Install shows what will be created (tables, pages, sample data) before anything happens; the application gets its own role and schema in this workspace.',
|
|
99
|
+
custom: 'The boilerplate applications of this workspace: start a new application from one.',
|
|
100
|
+
}[tab];
|
|
101
|
+
const main = html`<div class="gal">
|
|
102
|
+
<div class="gal-bar">
|
|
103
|
+
<div class="ab-search gal-search" role="search"><label class="sr-only" for="gal-q">Search apps</label>${icon('search')}
|
|
104
|
+
<input id="gal-q" type="search" placeholder="Search apps" autocomplete="off" data-filter-list=".gal [data-filter-row]"></div>
|
|
105
|
+
${tabs}
|
|
106
|
+
</div>
|
|
107
|
+
<h1 class="sr-only">App Gallery</h1>
|
|
108
|
+
<p class="muted">${intro}</p>
|
|
109
|
+
${cards.length ? html`<div class="gal-grid">${cards}</div>` : empty}
|
|
110
|
+
</div>`;
|
|
111
|
+
return send(reply, s, shell(s, 'App Gallery', [['App Gallery']], main, 'gallery'));
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
// a sample app: an administrator installs it (shipped SQL, run as the owner)
|
|
115
|
+
app.post(`${BASE}/gallery/samples/:key`, async (req: Req, reply) => {
|
|
116
|
+
const s = await developer(req, reply);
|
|
117
|
+
if (!s) return;
|
|
118
|
+
if (!(await isAdmin(s.username))) return reply.code(403).send('Only administrators install sample apps.');
|
|
119
|
+
const x = KEY.test(req.params.key) ? catalog().samples.find((c) => c.key === req.params.key) : undefined;
|
|
120
|
+
if (!x) return reply.code(404).send('Not found');
|
|
121
|
+
try {
|
|
122
|
+
if (await owner.one('select 1 as ok from meta.app where alias = $1', [x.alias])) throw new Error(`an application with the alias ${x.alias} exists already.`);
|
|
123
|
+
if (x.example && KEY.test(x.example)) await migrate({ root, databaseUrl: ownerUrl, example: x.example, log: () => {} });
|
|
124
|
+
else if (x.file && /^[a-z0-9-]+\.sql$/.test(x.file)) await owner.query(galleryFile(x.file));
|
|
125
|
+
else throw new Error('the gallery entry names nothing to install.');
|
|
126
|
+
const made = await owner.one<{ id: number; db_role: string | null }>('select id, db_role from meta.app where alias = $1', [x.alias]);
|
|
127
|
+
if (!made) throw new Error(`the scripts ran, but there is no application ${x.alias}.`);
|
|
128
|
+
// into the current workspace (an isolated one gets the application's role too)
|
|
129
|
+
const ws = currentWorkspace(s);
|
|
130
|
+
if (ws > 1)
|
|
131
|
+
await owner.tx(async (c) => {
|
|
132
|
+
if (made.db_role && (await c.query('select 1 from meta.workspace where id = $1 and isolated', [ws])).rowCount)
|
|
133
|
+
await c.query('insert into meta.workspace_role (workspace_id, role_name) values ($1, $2) on conflict do nothing', [ws, made.db_role]);
|
|
134
|
+
await placeApp(c, made.id, ws);
|
|
135
|
+
});
|
|
136
|
+
await workspacesChanged();
|
|
137
|
+
await logActivity({ appId: made.id, username: s.username, event: 'gallery', ip: clientIp(req), detail: `installed sample app ${x.key}` });
|
|
138
|
+
flash(s, `${x.title} installed (/a/${x.alias}).`);
|
|
139
|
+
return back(reply, s, `${BASE}/apps/${made.id}`);
|
|
140
|
+
} catch (e) {
|
|
141
|
+
flash(s, `${x.title} was not installed: ${(e as Error).message}`, 'error');
|
|
142
|
+
return back(reply, s, `${BASE}/gallery`);
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
// a starter app: its blueprint's review (nothing is created before the developer confirms there)
|
|
147
|
+
app.post(`${BASE}/gallery/starters/:key`, async (req: Req, reply) => {
|
|
148
|
+
const s = await developer(req, reply);
|
|
149
|
+
if (!s) return;
|
|
150
|
+
const x = KEY.test(req.params.key) ? catalog().starters.find((c) => c.key === req.params.key) : undefined;
|
|
151
|
+
if (!x || !/^starters\/[a-z0-9-]+\.json$/.test(x.file)) return reply.code(404).send('Not found');
|
|
152
|
+
return openBlueprint(s, reply, x.title, JSON.stringify(JSON.parse(galleryFile(x.file)), null, 2));
|
|
153
|
+
});
|
|
154
|
+
}
|
package/src/builder/home.ts
CHANGED
|
@@ -3,9 +3,10 @@ import { owner } from '../db.ts';
|
|
|
3
3
|
import { html, raw, type Raw } from '../html.ts';
|
|
4
4
|
import { icon } from '../icons.ts';
|
|
5
5
|
import { APP_COLORS, BASE, csrf, developer, input, region, select, send, shell, type Req } from './ui.ts';
|
|
6
|
+
import { crossAppLinks } from './cross-app.ts';
|
|
6
7
|
import type { Session } from '../session.ts';
|
|
7
8
|
import { isAdmin } from './locks.ts';
|
|
8
|
-
import { currentWorkspace, inWorkspaceSql } from './workspaces.ts';
|
|
9
|
+
import { currentWorkspace, inWorkspaceSql, workspaceAdmin } from './workspaces.ts';
|
|
9
10
|
|
|
10
11
|
// The workspace pages of the builder, laid out like APEX's App Builder: the
|
|
11
12
|
// home page (tiles, a searchable list of applications as a report or as
|
|
@@ -98,15 +99,22 @@ export async function homeRoutes(app: FastifyInstance) {
|
|
|
98
99
|
if (typeof req.query.sort === 'string' && req.query.sort in SORTS) s.state.__BSORT = req.query.sort;
|
|
99
100
|
const view: View = s.state.__BVIEW === 'grid' ? 'grid' : 'report';
|
|
100
101
|
const sort: Sort = (typeof s.state.__BSORT === 'string' && s.state.__BSORT in SORTS ? s.state.__BSORT : 'name') as Sort;
|
|
102
|
+
// (092) application groups of the workspace: a filter, remembered for the session
|
|
103
|
+
const groups = (await owner.query<{ id: number; name: string }>('select id, name from meta.app_group where workspace_id = $1 order by lower(name)', [currentWorkspace(s)])).rows;
|
|
104
|
+
if (typeof req.query.group === 'string') s.state.__BGROUP = req.query.group;
|
|
105
|
+
const group = groups.find((g) => String(g.id) === s.state.__BGROUP) ?? null;
|
|
101
106
|
const [apps, total, recent] = await Promise.all([
|
|
102
107
|
owner.query(
|
|
103
|
-
`select a.id, a.name, a.alias, a.authentication, a.db_role, a.updated_at,
|
|
108
|
+
`select a.id, a.name, a.alias, a.authentication, a.db_role, a.updated_at, g.name as group_name,
|
|
104
109
|
(select count(*) from meta.page p where p.app_id = a.id)::int as pages,
|
|
105
110
|
(select count(*) from meta.activity_log l where l.app_id = a.id and l.event = 'page_view' and l.at > now() - interval '1 day')::int as views
|
|
106
111
|
from meta.app a
|
|
112
|
+
left join meta.app_group_member gm on gm.app_id = a.id
|
|
113
|
+
left join meta.app_group g on g.id = gm.group_id
|
|
107
114
|
where ($1 = '' or a.name ilike '%' || $1 || '%' or a.alias ilike '%' || $1 || '%' or a.id::text = $1) and ${inWorkspaceSql('a', 2)}
|
|
115
|
+
and ($3::int is null or gm.group_id = $3)
|
|
108
116
|
order by ${SORTS[sort]}`,
|
|
109
|
-
[q.replace(/[\\%_]/g, (c) => `\\${c}`), currentWorkspace(s)],
|
|
117
|
+
[q.replace(/[\\%_]/g, (c) => `\\${c}`), currentWorkspace(s), group?.id ?? null],
|
|
110
118
|
),
|
|
111
119
|
owner.one(`select count(*)::int as n from meta.app a where ${inWorkspaceSql('a', 1)}`, [currentWorkspace(s)]),
|
|
112
120
|
recentApps(s),
|
|
@@ -122,11 +130,11 @@ export async function homeRoutes(app: FastifyInstance) {
|
|
|
122
130
|
html`<th scope="col"${cls ? raw(` class="${cls}"`) : ''}${sort === key ? raw(' aria-sort="' + (key === 'pages' || key === 'updated' ? 'descending' : 'ascending') + '"') : ''}><a href="${link({ sort: key })}">${label}${sort === key ? html`<span class="ab-sorted" aria-hidden="true">${key === 'pages' || key === 'updated' ? '↓' : '↑'}</span>` : ''}</a></th>`;
|
|
123
131
|
const rows = apps.rows;
|
|
124
132
|
const list = rows.length === 0
|
|
125
|
-
? html`<p class="ab-empty">${total.n ? html`No application matches “${q}
|
|
133
|
+
? html`<p class="ab-empty">${total.n ? html`No application ${group ? html`in the group ${group.name}${q ? html` matches “${q}”` : ''}` : html`matches “${q}”`}. <a href="${BASE}?q=&group=">Show all</a>` : html`No applications yet. <a href="${BASE}/create">Create one</a> or <a href="${BASE}/import">import one</a>.`}</p>`
|
|
126
134
|
: view === 'grid'
|
|
127
135
|
? html`<div class="ab-cards">${rows.map((a) => html`<article class="ab-card" data-filter-row>
|
|
128
136
|
<a class="ab-card-main" href="${BASE}/apps/${a.id}">${appIcon(a)}<span><strong>${a.name}</strong><small>${a.id} · /a/${a.alias}</small></span></a>
|
|
129
|
-
<div class="ab-card-meta"
|
|
137
|
+
<div class="ab-card-meta">${a.group_name ? html`<span class="tag">${a.group_name}</span>` : ''}<span>${a.pages} pages</span><span>${a.views} views today</span><span>${ago(a.updated_at)}</span></div>
|
|
130
138
|
<div class="ab-card-actions">
|
|
131
139
|
<a class="tb-btn" href="${BASE}/apps/${a.id}" title="Edit ${a.name}">${icon('edit')}<span class="sr-only">Edit ${a.name}</span></a>
|
|
132
140
|
<a class="tb-btn" href="/a/${a.alias}" target="_blank" rel="noopener" title="Run ${a.name}">${icon('play')}<span class="sr-only">Run ${a.name}</span></a>
|
|
@@ -137,7 +145,7 @@ export async function homeRoutes(app: FastifyInstance) {
|
|
|
137
145
|
<tbody>${rows.map((a) => html`<tr data-filter-row>
|
|
138
146
|
<td class="num">${a.id}</td>
|
|
139
147
|
<td class="ab-name"><a href="${BASE}/apps/${a.id}">${appIcon(a)}<span>${a.name}</span></a></td>
|
|
140
|
-
<td>${a.alias}</td>
|
|
148
|
+
<td>${a.alias}${a.group_name ? html` <span class="tag">${a.group_name}</span>` : ''}</td>
|
|
141
149
|
<td class="num">${a.pages}</td>
|
|
142
150
|
<td class="num">${a.views}</td>
|
|
143
151
|
<td>${a.authentication === 'none' ? 'Public' : a.authentication === 'header' ? 'HTTP header' : a.authentication === 'database' ? 'Database accounts' : a.authentication === 'custom' ? 'Custom' : 'App users'}</td>
|
|
@@ -151,6 +159,7 @@ export async function homeRoutes(app: FastifyInstance) {
|
|
|
151
159
|
const main = html`<div class="ab-home">
|
|
152
160
|
<div class="ab-main">
|
|
153
161
|
<h1 class="sr-only">App Builder</h1>
|
|
162
|
+
${s.workspace?.message ? html`<div class="alert alert-info ab-message" role="status">${icon('bell')}<div><strong>${s.workspace.name}</strong><p>${s.workspace.message}</p></div></div>` : ''}
|
|
154
163
|
${tiles()}
|
|
155
164
|
<div class="ab-toolbar">
|
|
156
165
|
<form class="ab-search" method="get" action="${BASE}" role="search">
|
|
@@ -158,6 +167,9 @@ export async function homeRoutes(app: FastifyInstance) {
|
|
|
158
167
|
<input id="ab-q" name="q" type="search" value="${q}" placeholder="Search" autocomplete="off" data-filter-list=".ab-home [data-filter-row]">
|
|
159
168
|
</form>
|
|
160
169
|
<div class="ab-views" role="group" aria-label="View">${viewButton('grid', 'grid', 'Cards')}${viewButton('report', 'list', 'Report')}</div>
|
|
170
|
+
${groups.length ? html`<form method="get" action="${BASE}" class="ab-group"><label class="sr-only" for="ab-group">Application group</label>
|
|
171
|
+
<select id="ab-group" name="group" data-autosubmit><option value="">All groups</option>${groups.map((g) => html`<option value="${g.id}"${group?.id === g.id ? raw(' selected') : ''}>${g.name}</option>`)}</select>
|
|
172
|
+
<noscript><button class="btn btn-sm">Show</button></noscript></form>` : ''}
|
|
161
173
|
<details class="menu ab-menu"><summary class="btn">Actions ${icon('chevron')}</summary>
|
|
162
174
|
<div class="menu-panel" role="menu">
|
|
163
175
|
<div class="menu-section"><span class="small muted">Sort by</span>
|
|
@@ -195,7 +207,7 @@ export async function homeRoutes(app: FastifyInstance) {
|
|
|
195
207
|
${input('name', 'Name', '', { required: true })}
|
|
196
208
|
${input('alias', 'Alias (URL)', '', { required: true, help: 'lowercase, e.g. inventory → /a/inventory' })}
|
|
197
209
|
${boilerplates.length
|
|
198
|
-
? select('boilerplate', 'Start from', '', [['', '- a blank application (a Home page) -'], ...boilerplates.map((x): [string, string] => [String(x.id), `${x.name} (boilerplate)`])],
|
|
210
|
+
? select('boilerplate', 'Start from', /^\d{1,9}$/.test(String(req.query?.boilerplate ?? '')) ? String(req.query!.boilerplate) : '', [['', '- a blank application (a Home page) -'], ...boilerplates.map((x): [string, string] => [String(x.id), `${x.name} (boilerplate)`])],
|
|
199
211
|
'A boilerplate application\'s pages, shared components and settings are copied; the new application keeps its own name, alias, role and authentication.')
|
|
200
212
|
: ''}
|
|
201
213
|
${select('schema', 'Parsing schema', '', [['', '- new schema named after the alias -'], ...schemas.rows.map((r): [string, string] => [r.nspname, r.nspname])],
|
|
@@ -275,9 +287,11 @@ export async function homeRoutes(app: FastifyInstance) {
|
|
|
275
287
|
if (!s) return;
|
|
276
288
|
const card = (href: string, ic: Raw | '', title: string, text: string) =>
|
|
277
289
|
html`<a class="ab-tile" href="${href}"><span class="ab-tile-icon">${ic}</span><strong>${title}</strong><span>${text}</span></a>`;
|
|
278
|
-
const main = html`<h1 class="u-mb1">Workspace utilities</h1>
|
|
290
|
+
const main = html`<div class="ab-home"><div class="ab-main"><h1 class="u-mb1">Workspace utilities</h1>
|
|
279
291
|
<div class="ab-tiles ab-tiles-wrap">
|
|
280
292
|
${card(`${BASE}/users`, icon('user'), 'Users', 'Accounts of the people who use the applications, and their access.')}
|
|
293
|
+
${card(`${BASE}/app-groups`, icon('folder'), 'Application groups', 'Organise the applications of this workspace into groups.')}
|
|
294
|
+
${card(`${BASE}/gallery`, icon('package'), 'App Gallery', 'Sample and starter applications to install, and this workspace\'s boilerplates.')}
|
|
281
295
|
${card(`${BASE}/users/providers`, icon('key'), 'Identity providers', 'OpenID Connect and SAML sign-in.')}
|
|
282
296
|
${card(`${BASE}/users/directories`, icon('org'), 'LDAP directories', 'Sign in with directory accounts.')}
|
|
283
297
|
${card(`${BASE}/users#account-settings`, icon('shield'), 'Password policy', 'Length, complexity and lifetime of passwords.')}
|
|
@@ -285,11 +299,20 @@ export async function homeRoutes(app: FastifyInstance) {
|
|
|
285
299
|
${card(`${BASE}/sql`, icon('database'), 'SQL Workshop', 'Run SQL, browse objects and load data.')}
|
|
286
300
|
${card(`${BASE}/dashboard`, icon('activity'), 'Dashboard', 'Usage and problems across the workspace.')}
|
|
287
301
|
${(await isAdmin(s.username)) ? card(`${BASE}/instance`, icon('settings'), 'Instance settings', 'Session length, sign-in throttling and the server\'s configuration (administrators).') : ''}
|
|
288
|
-
${(await isAdmin(s.username))
|
|
302
|
+
${(await isAdmin(s.username))
|
|
303
|
+
? card(`${BASE}/workspaces`, icon('layers'), 'Workspaces', 'Groups of applications and their developers (administrators).')
|
|
304
|
+
: s.workspace && (await workspaceAdmin(s.username, s.workspace.id))
|
|
305
|
+
? card(`${BASE}/workspaces/${s.workspace.id}`, icon('layers'), `Workspace ${s.workspace.name}`, 'Its name and developers (workspace administrators).')
|
|
306
|
+
: ''}
|
|
289
307
|
${(await isAdmin(s.username)) ? card(`${BASE}/ai`, icon('bolt'), 'AI services', 'Claude and OpenAI for the applications: models, keys, limits and usage (administrators).') : ''}
|
|
290
308
|
${(await isAdmin(s.username)) ? card(`${BASE}/mail`, icon('send'), 'Mail services', 'SMTP, Microsoft 365, Amazon SES, Resend, Postmark, SendGrid or Mailgun for the applications\' e-mail (administrators).') : ''}
|
|
291
309
|
${(await isAdmin(s.username)) ? card(`${BASE}/installation`, icon('history'), 'Installation', 'Version, install and upgrade runs, applied migrations (administrators).') : ''}
|
|
292
|
-
</div
|
|
310
|
+
</div></div>
|
|
311
|
+
<aside class="ab-side" aria-label="About and reports">
|
|
312
|
+
<section><h2>About</h2><p>Workspace utilities hold what the applications of this workspace share: users and sign-in, groups, the gallery, and reports across the applications.</p>
|
|
313
|
+
<a href="https://github.com/pgkiln/pgkiln/blob/main/docs/guide/03-builder.md#workspaces" target="_blank" rel="noopener">Learn more …</a></section>
|
|
314
|
+
<section><h2>Cross Application Reports</h2><ul class="ab-links ab-tasks">${crossAppLinks()}</ul></section>
|
|
315
|
+
</aside></div>`;
|
|
293
316
|
return send(reply, s, shell(s, 'Workspace utilities', [['App Builder', BASE], ['Workspace utilities']], main));
|
|
294
317
|
});
|
|
295
318
|
}
|
package/src/builder/newapp.ts
CHANGED
|
@@ -64,9 +64,27 @@ export async function createApp(c: Client, a: CheckedApp): Promise<{ id: number;
|
|
|
64
64
|
const S = pg.escapeIdentifier(a.schema);
|
|
65
65
|
const R = pg.escapeIdentifier(a.role);
|
|
66
66
|
// The parsing schema: a role that can only use this schema.
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
await c.query(
|
|
67
|
+
// (090) an isolated workspace's application gets a new role, and a schema that is new (owned by that
|
|
68
|
+
// role) or one of the workspace's own: never another workspace's
|
|
69
|
+
const isolated = (await c.query('select 1 from meta.workspace where id = $1 and isolated', [a.workspaceId])).rowCount;
|
|
70
|
+
const roleExists = (await c.query('select 1 from pg_roles where rolname = $1', [a.role])).rowCount;
|
|
71
|
+
if (isolated) {
|
|
72
|
+
// (a taken alias fails below, with its own message)
|
|
73
|
+
const aliasTaken = (await c.query('select 1 from meta.app where alias = $1', [a.alias])).rowCount;
|
|
74
|
+
if (roleExists && !aliasTaken) throw new Error(`The database role ${a.role} exists already: choose another alias.`);
|
|
75
|
+
const foreign = await c.query(
|
|
76
|
+
`select 1 from pg_namespace n where n.nspname = $1
|
|
77
|
+
and n.nspowner::regrole::text not in (select role_name from meta.workspace_role where workspace_id = $2)`,
|
|
78
|
+
[a.schema, a.workspaceId],
|
|
79
|
+
);
|
|
80
|
+
if (foreign.rowCount) throw new Error(`The schema ${a.schema} exists already and doesn't belong to this workspace: choose another schema.`);
|
|
81
|
+
}
|
|
82
|
+
if (!roleExists) await c.query(`create role ${R} nologin`);
|
|
83
|
+
await c.query(`create schema if not exists ${S}${isolated ? ` authorization ${R}` : ''}`);
|
|
84
|
+
if (isolated) {
|
|
85
|
+
// a name the workspace lists already (an application deleted, its role dropped) is its own; another workspace's is refused
|
|
86
|
+
await c.query('insert into meta.workspace_role (workspace_id, role_name) values ($1, $2) on conflict (workspace_id, role_name) do nothing', [a.workspaceId, a.role]);
|
|
87
|
+
} else await c.query(`grant ${R} to pgkiln_runtime`);
|
|
70
88
|
await c.query(`grant usage on schema ${S} to ${R}`);
|
|
71
89
|
await c.query(`grant select, insert, update, delete on all tables in schema ${S} to ${R}`);
|
|
72
90
|
await c.query(`grant usage, select on all sequences in schema ${S} to ${R}`);
|
package/src/builder/quicksql.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { quickSql } from '../quicksql.ts';
|
|
|
6
6
|
import { clientIp, type Session } from '../session.ts';
|
|
7
7
|
import { runAndRecord, runOptions, SCRIPT_MAX_MB } from './scripts.ts';
|
|
8
8
|
import { back, BASE, csrf, developer, flash, region, send, shell, workshopTabs, type Req } from './ui.ts';
|
|
9
|
+
import { currentWorkspace } from './workspaces.ts';
|
|
9
10
|
|
|
10
11
|
// SQL Workshop → Quick SQL: shorthand → DDL preview, then save it as a SQL
|
|
11
12
|
// script or run it (as a script, so the results per statement are kept).
|
|
@@ -85,8 +86,8 @@ export async function quickSqlRoutes(app: FastifyInstance) {
|
|
|
85
86
|
return back(reply, s, `${BASE}/sql/scripts/runs/${id}`);
|
|
86
87
|
}
|
|
87
88
|
let unique = name;
|
|
88
|
-
for (let n = 2; await owner.one('select 1 from meta.sql_script where name = $1', [unique]); n++) unique = `${name} (${n})`;
|
|
89
|
-
const r = await owner.one(`insert into meta.sql_script (name, content, created_by, updated_by) values ($1, $2, $3, $3) returning id`, [unique, content, s.username]);
|
|
89
|
+
for (let n = 2; await owner.one('select 1 from meta.sql_script where name = $1 and workspace_id = $2', [unique, currentWorkspace(s)]); n++) unique = `${name} (${n})`;
|
|
90
|
+
const r = await owner.one(`insert into meta.sql_script (name, content, created_by, updated_by, workspace_id) values ($1, $2, $3, $3, $4) returning id`, [unique, content, s.username, currentWorkspace(s)]);
|
|
90
91
|
flash(s, `Saved as script “${unique}”.`);
|
|
91
92
|
return back(reply, s, `${BASE}/sql/scripts/${r!.id}`);
|
|
92
93
|
});
|