@fabrika/app 0.9.0-dev.12 → 0.9.0-dev.14
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/package.json +9 -9
- package/skill/SKILL.md +7 -4
- package/skill/references/app-setup.md +15 -8
- package/skill/references/endpoint.md +7 -1
- package/skill/references/errors.md +7 -6
- package/skill/references/jobs.md +10 -0
- package/skill/references/relations.md +682 -0
- package/skill/references/table-and-migration.md +18 -7
- package/skill/references/webhooks-links-connectors.md +2 -1
- package/src/bun.ts +10 -0
- package/src/contract/artifact-schema.ts +82 -1
- package/src/contract/build.ts +142 -12
- package/src/contract/compile.ts +1 -0
- package/src/contract/declaration.ts +4 -0
- package/src/contract/define.ts +12 -0
- package/src/contract/group.ts +10 -1
- package/src/contract/kit.ts +3 -1
- package/src/contract/platform.ts +1 -0
- package/src/contract/vocabulary.ts +3 -0
- package/src/disk-assets.ts +15 -3
- package/src/implement/boot.ts +59 -5
- package/src/implement/capability.ts +91 -6
- package/src/implement/dispatch.ts +334 -17
- package/src/implement/egress.ts +409 -9
- package/src/implement/implement.ts +28 -1
- package/src/implement/invocation.ts +10 -9
- package/src/implement/types.ts +15 -4
- package/src/implement/webhook.ts +8 -0
- package/src/jobs/runner.ts +7 -2
- package/src/source-map-path.ts +21 -0
- package/src/testing/caller.ts +20 -2
- package/src/testing/membership.ts +9 -5
- package/types/src/contract/declaration.d.ts +6 -0
- package/types/src/contract/define.d.ts +15 -0
- package/types/src/contract/group.d.ts +9 -1
- package/types/src/contract/kit.d.ts +2 -2
- package/types/src/contract/vocabulary.d.ts +4 -1
- package/types/src/implement/boot.d.ts +6 -0
- package/types/src/implement/capability.d.ts +14 -5
- package/types/src/implement/dispatch.d.ts +20 -1
- package/types/src/implement/egress.d.ts +36 -1
- package/types/src/implement/implement.d.ts +24 -1
- package/types/src/implement/invocation.d.ts +3 -3
- package/types/src/implement/types.d.ts +13 -3
- package/types/src/jobs/runner.d.ts +3 -0
- package/types/src/source-map-path.d.ts +4 -0
- package/types/src/testing/caller.d.ts +6 -1
- package/types/src/testing/membership.d.ts +1 -1
|
@@ -167,7 +167,10 @@ INSERT INTO priorities (code, label, rank) VALUES ('low', 'Low', 1), ('normal',
|
|
|
167
167
|
`SET`, transaction control, `SECURITY DEFINER`, a domain, `serial` and sequences (use `GENERATED ALWAYS AS IDENTITY`),
|
|
168
168
|
a function overload, and calls outside the reviewed built-ins.
|
|
169
169
|
- Never edit, rename or delete a committed migration; add a new one. Change a schema by expand, switch, contract, and
|
|
170
|
-
ask before you drop or rename anything.
|
|
170
|
+
ask before you drop or rename anything. A migration statement that is not known to keep every stored value (it
|
|
171
|
+
drops a table or a column, empties, deletes, updates or upserts rows, changes a column's type, renames, or calls its
|
|
172
|
+
own database code) shows a separate line that says it deletes, overwrites or may change data. That line waits for a
|
|
173
|
+
person on a protected environment, and the platform backs the database up before the migration runs.
|
|
171
174
|
|
|
172
175
|
## On Cloudflare: SQLite migrations
|
|
173
176
|
|
|
@@ -335,17 +338,25 @@ export const tables = defineTables(vocabulary, columns)({
|
|
|
335
338
|
interface is `<Pascal>View`, every column is `| null`, and its column list entry says `view: true`. A view needs no
|
|
336
339
|
policy; without one only `ctx.sql` reads it. With one, `ctx.db` reads it like a child table, typed and scoped, and nothing writes it:
|
|
337
340
|
|
|
338
|
-
- `scope: { child: '<parent>' }` puts it under its parent
|
|
339
|
-
|
|
341
|
+
- `scope: { child: '<parent>' }` puts it under its parent: the view selects the parent column (`<parent dimension>_id`,
|
|
342
|
+
or `column: '<name>'`), and needs none of the parent's chain columns. A view of one row per parent states
|
|
340
343
|
`key: '<parent column>'` (`{ child: 'deals', key: 'deal_id' }`), and a handler `on` the parent reads that row with
|
|
341
344
|
`ctx.db.target.<view>.get(ctx.target.value)`.
|
|
342
345
|
- `scope: { reference: '<why>' }` is a view every endpoint reads, through `ctx.db.reference.<view>`.
|
|
343
|
-
-
|
|
346
|
+
- A child view takes a `when` on its read actions, as a table does (`references/relations.md`): a path may start at
|
|
347
|
+
its parent column (`'deal_id.stage'`), though no foreign key declares it, and follows the parent's foreign keys from
|
|
348
|
+
there. The parent's own `when` does not narrow the view; state the view's. Every view column is nullable, so a
|
|
349
|
+
`not` over such a path is refused: state the condition without the `not`.
|
|
350
|
+
- It takes `actions: { read, appRead?, appCount? }`, column `read` actions and a child view's `when` only. `insert`, `update`, `delete`,
|
|
344
351
|
`version`, `createdBy`, `queue`, `files`, a column `write` and `unscoped: { <view>: 'write' }` are refused by tsc and
|
|
345
352
|
the checker; its handles' writes are `Unavailable`, and the data layer refuses them.
|
|
346
|
-
-
|
|
347
|
-
|
|
348
|
-
|
|
353
|
+
- Every read reaches a view's rows through the parent row their parent column names: a `Ref` of the parent, a
|
|
354
|
+
`Within` that reaches the parent (its relations and reveals included) and `ctx.db.within.<view>` wherever the
|
|
355
|
+
parent is listed, under the parent's own dimension too (a view of `deals` under a `Within` of `deal`). A row whose
|
|
356
|
+
parent column is null, or names a parent that does not exist or that the capability does not reach, is never read
|
|
357
|
+
through a `Ref` or a `Within`, one of every value included (only `ctx.db.app` lists every row of a view); a chain
|
|
358
|
+
column the view carries does not place a row. The view's SQL decides which parent each row names, and the approver
|
|
359
|
+
reviews it. `ctx.sql.scope` refuses a `Ref` or a `Within` of a view: read it through `ctx.db`.
|
|
349
360
|
- A column of a type the data layer does not read (an array, `numeric` on SQLite) is left out, and every codegen run
|
|
350
361
|
names it. On SQLite an expression has a type only through `CAST(… AS INTEGER | REAL | TEXT)`; on Postgres cast a
|
|
351
362
|
count you want as a number (`count(*)::int4`).
|
|
@@ -52,7 +52,8 @@ export const integrations = app.group({ callers: ['human'] }, (r) => ({
|
|
|
52
52
|
`POST /hooks/github/:bindingId`.
|
|
53
53
|
- A binding is made by a procedure that declares `binds: '<webhook>'` and calls `ctx.webhooks('<webhook>').bind(ref,
|
|
54
54
|
account)` with a capability on the bound value (`ctx.target`, an org here), in its transaction; `unbind(ref, id)`
|
|
55
|
-
removes one.
|
|
55
|
+
removes one. The `Ref` must come from an IAM grant: one held through a relation, a member reveal or a secondary
|
|
56
|
+
path is refused, because the binding would outlive the rows that hold it. A GitHub account is `installation:<id>` or `repository:<id>`. The answer carries the secret and the URL
|
|
56
57
|
once. The generated tests need a fixture for its input (`references/tests.md`).
|
|
57
58
|
- The framework checks the signature, the account and the input (undeclared fields are dropped).
|
|
58
59
|
`ctx.refs['<action>']` is a `Ref` of the bound org for each declared action.
|
package/src/bun.ts
CHANGED
|
@@ -14,6 +14,7 @@ import { directoryEmailProvider } from '@fabrika/email/directory'
|
|
|
14
14
|
import { parseJwks } from '@fabrika/jwks'
|
|
15
15
|
import type { FileObjectStore } from '@fabrika/platform'
|
|
16
16
|
import { applicationRuntimeUrl, S3BlobStore } from '@fabrika/platform-node'
|
|
17
|
+
import { lookup } from 'node:dns/promises'
|
|
17
18
|
import { diskAssets } from './disk-assets.js'
|
|
18
19
|
import type { FetchService, RequestExecutionContext } from './fetch.js'
|
|
19
20
|
import { clamscanScanner } from './files/clamscan.js'
|
|
@@ -550,6 +551,7 @@ async function startContractServer(
|
|
|
550
551
|
membership,
|
|
551
552
|
terminals,
|
|
552
553
|
workloadTokens,
|
|
554
|
+
resolveHost,
|
|
553
555
|
requireProxySecret: true,
|
|
554
556
|
localEmailProviders: LOCAL_EMAIL_PROVIDERS,
|
|
555
557
|
connections: databaseConnections(environment.framework[DATABASE_CONNECTIONS]) ?? DEFAULT_DATABASE_CONNECTIONS,
|
|
@@ -585,6 +587,13 @@ async function startContractServer(
|
|
|
585
587
|
return { port: server.port ?? port, stop }
|
|
586
588
|
}
|
|
587
589
|
|
|
590
|
+
/**
|
|
591
|
+
* Every address `hostname` resolves to, as the operating system's resolver answers Bun's own `fetch`: a cron job's public
|
|
592
|
+
* egress refuses a hop whose name resolves to any private one, and connects to an address it checked (ADR-0075).
|
|
593
|
+
*/
|
|
594
|
+
const resolveHost = async (hostname: string): Promise<readonly string[]> =>
|
|
595
|
+
(await lookup(hostname, { all: true, verbatim: true })).map((entry) => entry.address)
|
|
596
|
+
|
|
588
597
|
/** The application module at `path`, imported when the loader runs; its default export must be what `serve` returned. */
|
|
589
598
|
export function implementationAt(path: string): ImplementationLoader {
|
|
590
599
|
return async () => {
|
|
@@ -631,6 +640,7 @@ export async function runContractJob(
|
|
|
631
640
|
membership,
|
|
632
641
|
terminals,
|
|
633
642
|
workloadTokens,
|
|
643
|
+
resolveHost,
|
|
634
644
|
requireProxySecret: true,
|
|
635
645
|
localEmailProviders: LOCAL_EMAIL_PROVIDERS,
|
|
636
646
|
// ClamAV on PATH, as the provider's build installs it for a `scan: true` file kind; missing, the scan fails closed.
|
|
@@ -6,6 +6,8 @@ import {
|
|
|
6
6
|
type ArrayShape,
|
|
7
7
|
type AttachmentShape,
|
|
8
8
|
BUILTIN_ROLE_KEYS,
|
|
9
|
+
type ColumnTestArtifact,
|
|
10
|
+
type ConditionArtifact,
|
|
9
11
|
CONTRACT_FORMAT,
|
|
10
12
|
type ContractArtifact,
|
|
11
13
|
CROSS_ORIGIN_KINDS,
|
|
@@ -15,6 +17,7 @@ import {
|
|
|
15
17
|
fileKindsIn,
|
|
16
18
|
isOwnWorkloadName,
|
|
17
19
|
JOB_MAILERS,
|
|
20
|
+
JOB_SITE_PREFIX,
|
|
18
21
|
LOCALES,
|
|
19
22
|
mailTemplateProblems,
|
|
20
23
|
MAX_CACHE_AGE_SECONDS,
|
|
@@ -22,7 +25,9 @@ import {
|
|
|
22
25
|
type NumberShape,
|
|
23
26
|
type OutputShape,
|
|
24
27
|
parseEgressEntry,
|
|
28
|
+
PUBLIC_EGRESS,
|
|
25
29
|
type RecordShape,
|
|
30
|
+
type RowsTestArtifact,
|
|
26
31
|
type SchemaShape,
|
|
27
32
|
type StringShape,
|
|
28
33
|
type TablePolicyArtifact,
|
|
@@ -303,6 +308,45 @@ const tableAction = z.union([
|
|
|
303
308
|
z.array(action).min(2).refine((list) => new Set(list).size === list.length, 'a table operation names each action once'),
|
|
304
309
|
])
|
|
305
310
|
|
|
311
|
+
const literal = z.union([z.string(), z.number().finite(), z.boolean()])
|
|
312
|
+
const ordered = z.union([literal, z.strictObject({ now: z.literal(true) })])
|
|
313
|
+
|
|
314
|
+
/** Exactly one operator per column test, as the policy parse reads it. */
|
|
315
|
+
const columnTest: z.ZodType<ColumnTestArtifact> = z.strictObject({
|
|
316
|
+
eq: literal.optional(),
|
|
317
|
+
notEq: literal.optional(),
|
|
318
|
+
in: z.array(literal).nonempty().optional(),
|
|
319
|
+
notIn: z.array(literal).nonempty().optional(),
|
|
320
|
+
isNull: z.boolean().optional(),
|
|
321
|
+
lt: ordered.optional(),
|
|
322
|
+
lte: ordered.optional(),
|
|
323
|
+
gt: ordered.optional(),
|
|
324
|
+
gte: ordered.optional(),
|
|
325
|
+
}).refine((test) => Object.values(test).filter((value) => value !== undefined).length === 1, 'a column test states exactly one operator')
|
|
326
|
+
|
|
327
|
+
/** `some` or `none` of one table's rows: a condition of its own, or the test at the end of a path. */
|
|
328
|
+
const rowsTest: z.ZodType<RowsTestArtifact> = z.lazy(() =>
|
|
329
|
+
z.union([
|
|
330
|
+
z.strictObject({ some: z.record(name, condition).refine((rows) => Object.keys(rows).length === 1, 'some names exactly one table') }),
|
|
331
|
+
z.strictObject({ none: z.record(name, condition).refine((rows) => Object.keys(rows).length === 1, 'none names exactly one table') }),
|
|
332
|
+
])
|
|
333
|
+
)
|
|
334
|
+
|
|
335
|
+
const condition: z.ZodType<ConditionArtifact> = z.lazy(() =>
|
|
336
|
+
z.union([
|
|
337
|
+
z.strictObject({ allOf: z.array(condition).nonempty() }),
|
|
338
|
+
z.strictObject({ anyOf: z.array(condition).nonempty() }),
|
|
339
|
+
z.strictObject({ not: condition }),
|
|
340
|
+
rowsTest,
|
|
341
|
+
z.record(z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*){0,3}$/), z.union([columnTest, rowsTest])).refine(
|
|
342
|
+
(tests) =>
|
|
343
|
+
Object.keys(tests).length > 0 && !('allOf' in tests) && !('anyOf' in tests) && !('not' in tests) && !('some' in tests)
|
|
344
|
+
&& !('none' in tests),
|
|
345
|
+
'a condition tests at least one column',
|
|
346
|
+
),
|
|
347
|
+
])
|
|
348
|
+
)
|
|
349
|
+
|
|
306
350
|
const tablePolicy: z.ZodType<TablePolicyArtifact> = z.strictObject({
|
|
307
351
|
scope: z.discriminatedUnion('mode', [
|
|
308
352
|
z.strictObject({
|
|
@@ -331,6 +375,35 @@ const tablePolicy: z.ZodType<TablePolicyArtifact> = z.strictObject({
|
|
|
331
375
|
columns: record(z.strictObject({ read: action.optional(), write: action.optional() })),
|
|
332
376
|
files: z.record(name, name).optional(),
|
|
333
377
|
view: z.literal(true).optional(),
|
|
378
|
+
confers: record(z.strictObject({
|
|
379
|
+
principal: name,
|
|
380
|
+
node: name,
|
|
381
|
+
expires: nullableName,
|
|
382
|
+
when: condition.optional(),
|
|
383
|
+
assign: z.strictObject({ maxDays: z.int().positive().nullable(), self: z.boolean() }).nullable(),
|
|
384
|
+
})).optional(),
|
|
385
|
+
when: z.record(action, condition).optional(),
|
|
386
|
+
relationWhen: record(z.record(action, condition)).optional(),
|
|
387
|
+
reveals: record(z.strictObject({
|
|
388
|
+
to: name,
|
|
389
|
+
actions: z.array(action).nonempty(),
|
|
390
|
+
when: condition.optional(),
|
|
391
|
+
assign: z.strictObject({ self: z.boolean() }).optional(),
|
|
392
|
+
})).optional(),
|
|
393
|
+
readThrough: z.record(name, name).optional(),
|
|
394
|
+
writeThrough: z.record(name, z.array(action).nonempty()).optional(),
|
|
395
|
+
memberReveals: record(z.strictObject({
|
|
396
|
+
to: name,
|
|
397
|
+
actions: z.array(action).nonempty(),
|
|
398
|
+
when: condition.optional(),
|
|
399
|
+
assign: z.strictObject({ self: z.boolean() }).optional(),
|
|
400
|
+
})).optional(),
|
|
401
|
+
access: record(
|
|
402
|
+
z.strictObject({ view: name, row: name, principal: nullableName, member: nullableName }).refine(
|
|
403
|
+
(access) => access.principal !== null || access.member !== null,
|
|
404
|
+
'an access view binds the principal, a member node or both (ADR-0076)',
|
|
405
|
+
),
|
|
406
|
+
).optional(),
|
|
334
407
|
})
|
|
335
408
|
|
|
336
409
|
export const contractArtifactSchema: z.ZodType<ContractArtifact> = z.strictObject({
|
|
@@ -349,11 +422,16 @@ export const contractArtifactSchema: z.ZodType<ContractArtifact> = z.strictObjec
|
|
|
349
422
|
grants: actions,
|
|
350
423
|
member: z.strictObject({ scope: name, assignableBy: z.array(roleKey) }).nullable(),
|
|
351
424
|
external: z.literal(true).optional(),
|
|
425
|
+
via: record(actions.nonempty()).optional(),
|
|
352
426
|
}).refine((role) => role.external !== true || role.member !== null, {
|
|
353
427
|
path: ['external'],
|
|
354
428
|
message: 'only a membership role admits external principals',
|
|
429
|
+
}).refine((role) => role.via === undefined || role.external !== true, {
|
|
430
|
+
path: ['via'],
|
|
431
|
+
message: 'a relation holds actions through an internal role only, never an external one',
|
|
355
432
|
}),
|
|
356
433
|
),
|
|
434
|
+
relations: record(z.strictObject({ dimension: name })).optional(),
|
|
357
435
|
mounts: record(mount),
|
|
358
436
|
files: record(z.strictObject({
|
|
359
437
|
owner: name,
|
|
@@ -426,9 +504,12 @@ export const contractArtifactSchema: z.ZodType<ContractArtifact> = z.strictObjec
|
|
|
426
504
|
kicks: z.array(name).nonempty().optional(),
|
|
427
505
|
binds: name.optional(),
|
|
428
506
|
signs: z.array(name).nonempty().optional(),
|
|
429
|
-
egress: z.array(z.string().refine((origin) => parseEgressEntry(origin).ok)).nonempty().optional(),
|
|
507
|
+
egress: z.union([z.array(z.string().refine((origin) => parseEgressEntry(origin).ok)).nonempty(), z.literal(PUBLIC_EGRESS)]).optional(),
|
|
430
508
|
})).superRefine((declared, context) => {
|
|
431
509
|
for (const [site, reach] of Object.entries(declared)) {
|
|
510
|
+
if (reach.egress === PUBLIC_EGRESS && !site.startsWith(JOB_SITE_PREFIX)) {
|
|
511
|
+
context.addIssue({ code: 'custom', path: [site, 'egress'], message: "egress: 'public' belongs to a cron job, keyed by job:<name>" })
|
|
512
|
+
}
|
|
432
513
|
if (reach.actions !== undefined && !isOwnWorkloadName('public', site)) {
|
|
433
514
|
context.addIssue({ code: 'custom', path: [site, 'actions'], message: 'workload actions belong to a public procedure, keyed by its endpoint id' })
|
|
434
515
|
}
|
package/src/contract/build.ts
CHANGED
|
@@ -18,6 +18,7 @@ import {
|
|
|
18
18
|
type ContractArtifact,
|
|
19
19
|
type CspExtensions,
|
|
20
20
|
type CspSource,
|
|
21
|
+
type DeclaredEgress,
|
|
21
22
|
type DeclaredReach,
|
|
22
23
|
type DimensionArtifact,
|
|
23
24
|
directoryReach,
|
|
@@ -54,6 +55,7 @@ import {
|
|
|
54
55
|
planEndpoint,
|
|
55
56
|
type ProcedureArtifact,
|
|
56
57
|
type ProcedureChallenge,
|
|
58
|
+
PUBLIC_EGRESS,
|
|
57
59
|
type RoleArtifact,
|
|
58
60
|
type SchemaShape,
|
|
59
61
|
type ScopeBinding,
|
|
@@ -86,6 +88,7 @@ import {
|
|
|
86
88
|
type MountDeclaration,
|
|
87
89
|
type ProcedureDeclaration,
|
|
88
90
|
type ProcedureTreeDeclaration,
|
|
91
|
+
type RoleDeclaration,
|
|
89
92
|
type SpaAccessDeclaration,
|
|
90
93
|
} from './declaration'
|
|
91
94
|
import {
|
|
@@ -149,7 +152,7 @@ const FRAMEWORK_TABLE_PREFIX = 'fabrika_'
|
|
|
149
152
|
/** The most origins one site calls: a site that reaches more is an integration hub, which a connector import serves. */
|
|
150
153
|
const MAX_EGRESS_ORIGINS = 16
|
|
151
154
|
const DECLARED_ALLOWED =
|
|
152
|
-
"sql: 'read' | 'write', unscoped: { <table>: 'read' | 'write' }, connect: ['<import>'], issues: '<link mount>', mailer: 'installation' | 'own', kicks: ['<cron job>'], binds: '<webhook>', signs: ['<token purpose>'], egress: ['https://<host>' | 'https://*.<domain>']"
|
|
155
|
+
"sql: 'read' | 'write', unscoped: { <table>: 'read' | 'write' }, connect: ['<import>'], issues: '<link mount>', mailer: 'installation' | 'own', kicks: ['<cron job>'], binds: '<webhook>', signs: ['<token purpose>'], egress: ['https://<host>' | 'https://*.<domain>'] | 'public' (a cron job)"
|
|
153
156
|
const CSP_FIELDS = ['connectSrc', 'imgSrc', 'frameAncestors', 'scriptSrc', 'frameSrc', 'styleSrc', 'fontSrc']
|
|
154
157
|
/** An environment variable an application reads; a challenge names its secret by one. */
|
|
155
158
|
const APPLICATION_VARIABLE = /^[A-Z][A-Z0-9_]*$/
|
|
@@ -207,6 +210,7 @@ class ArtifactBuilder {
|
|
|
207
210
|
}
|
|
208
211
|
const actions = this.#actions()
|
|
209
212
|
const dimensions = this.#dimensions()
|
|
213
|
+
const relations = this.#relations()
|
|
210
214
|
const roles = this.#roles()
|
|
211
215
|
const tokens = this.#tokens()
|
|
212
216
|
this.#fileKinds = this.#readFileKinds()
|
|
@@ -256,6 +260,7 @@ class ArtifactBuilder {
|
|
|
256
260
|
dimensions,
|
|
257
261
|
actions,
|
|
258
262
|
roles,
|
|
263
|
+
...(Object.keys(relations).length === 0 ? {} : { relations }),
|
|
259
264
|
mounts,
|
|
260
265
|
files: {},
|
|
261
266
|
...(Object.keys(this.#fileKinds).length === 0 ? {} : { fileKinds: this.#fileKinds }),
|
|
@@ -456,8 +461,8 @@ class ArtifactBuilder {
|
|
|
456
461
|
if (BUILTIN_ROLE_KEYS.includes(name)) {
|
|
457
462
|
this.#problem(where, `is a role IAM defines itself for every application (reserved: ${BUILTIN_ROLE_KEYS.join(', ')}); choose another name`)
|
|
458
463
|
}
|
|
459
|
-
if (role.grants.length === 0) {
|
|
460
|
-
this.#problem(where, 'grants nothing (allowed: grants: [<exact actions>])')
|
|
464
|
+
if (role.grants.length === 0 && Object.keys(role.via ?? {}).length === 0) {
|
|
465
|
+
this.#problem(where, 'grants nothing (allowed: grants: [<exact actions>], or via: { <relation>: [<exact actions>] })')
|
|
461
466
|
}
|
|
462
467
|
this.#unique(where, 'grants', role.grants)
|
|
463
468
|
for (const action of role.grants) {
|
|
@@ -484,15 +489,116 @@ class ArtifactBuilder {
|
|
|
484
489
|
if (role.external === true && role.member === undefined) {
|
|
485
490
|
this.#problem(where, 'is declared external and is not a membership role: only a role with member: { scope, … } may admit externals')
|
|
486
491
|
}
|
|
492
|
+
const via = this.#via(where, role)
|
|
487
493
|
roles[name] = {
|
|
488
494
|
grants: [...role.grants],
|
|
489
495
|
member: role.member === undefined ? null : { scope: role.member.scope, assignableBy: [...role.member.assignableBy] },
|
|
490
496
|
...(role.external === true ? { external: true } : {}),
|
|
497
|
+
...(via === undefined ? {} : { via }),
|
|
491
498
|
}
|
|
492
499
|
}
|
|
493
500
|
return roles
|
|
494
501
|
}
|
|
495
502
|
|
|
503
|
+
/**
|
|
504
|
+
* Each relation names a dimension of the contract, and is reached through at most one table's rows that confer it,
|
|
505
|
+
* through access views (ADR-0076), or both; never through neither.
|
|
506
|
+
*/
|
|
507
|
+
#relations(): Record<string, { readonly dimension: string }> {
|
|
508
|
+
const relations: Record<string, { readonly dimension: string }> = {}
|
|
509
|
+
for (const [name, relation] of Object.entries(this.#contract.relations ?? {})) {
|
|
510
|
+
const where = `relation '${name}'`
|
|
511
|
+
this.#name(where, name)
|
|
512
|
+
if (!Object.hasOwn(this.#contract.dimensions, relation.dimension)) {
|
|
513
|
+
this.#problem(where, `names the dimension '${relation.dimension}', which is not a dimension of the contract`)
|
|
514
|
+
}
|
|
515
|
+
const sources = Object.entries(this.#tables).filter(([, table]) => table.confers !== undefined && Object.hasOwn(table.confers, name))
|
|
516
|
+
const viewed = Object.values(this.#tables).some((table) => table.access !== undefined && Object.hasOwn(table.access, name))
|
|
517
|
+
if (sources.length > 1 || (sources.length === 0 && !viewed)) {
|
|
518
|
+
this.#problem(
|
|
519
|
+
where,
|
|
520
|
+
`is conferred by ${sources.length} tables; exactly one table declares confers.${name}, or a table names an access view for it`,
|
|
521
|
+
)
|
|
522
|
+
}
|
|
523
|
+
relations[name] = { dimension: relation.dimension }
|
|
524
|
+
}
|
|
525
|
+
for (const [table, policy] of Object.entries(this.#tables)) {
|
|
526
|
+
for (const relation of Object.keys(policy.confers ?? {})) {
|
|
527
|
+
if (!Object.hasOwn(relations, relation)) {
|
|
528
|
+
this.#problem(`table '${table}'`, `confers '${relation}', which is not a relation of the vocabulary`)
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
for (const relation of Object.keys(policy.access ?? {})) {
|
|
532
|
+
if (!Object.hasOwn(relations, relation)) {
|
|
533
|
+
this.#problem(`table '${table}'`, `names an access view for '${relation}', which is not a relation of the vocabulary`)
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
return relations
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
/**
|
|
541
|
+
* A role's `via`: known relations and actions, on an internal role only (ADR-0051 keeps an external principal to its
|
|
542
|
+
* membership roles' own grants), and never an action that inserts a relation's rows, so a relation never delegates
|
|
543
|
+
* itself onward. A membership role holds a relation inside the value it is held in, so the relation's dimension is
|
|
544
|
+
* the role's or lies inside it.
|
|
545
|
+
*/
|
|
546
|
+
#via(where: string, role: RoleDeclaration): Record<string, readonly string[]> | undefined {
|
|
547
|
+
if (role.via === undefined) {
|
|
548
|
+
return undefined
|
|
549
|
+
}
|
|
550
|
+
if (role.external === true) {
|
|
551
|
+
this.#problem(where, 'holds actions via a relation and is an external role: an external principal holds no relation')
|
|
552
|
+
}
|
|
553
|
+
const relations = this.#contract.relations ?? {}
|
|
554
|
+
const member = role.member?.scope
|
|
555
|
+
for (const relation of Object.keys(role.via)) {
|
|
556
|
+
const dimension = relations[relation]?.dimension
|
|
557
|
+
if (member !== undefined && dimension !== undefined && !this.#lies(dimension, member)) {
|
|
558
|
+
this.#problem(
|
|
559
|
+
where,
|
|
560
|
+
`holds actions via '${relation}', whose dimension '${dimension}' is not '${member}' and does not lie inside it: a membership role holds a relation inside the value it is held in`,
|
|
561
|
+
)
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
const assigning = new Set<string>()
|
|
565
|
+
for (const policy of Object.values(this.#tables)) {
|
|
566
|
+
if (policy.confers === undefined) continue
|
|
567
|
+
const insert = policy.actions.insert
|
|
568
|
+
for (const action of insert === null ? [] : typeof insert === 'string' ? [insert] : insert) assigning.add(action)
|
|
569
|
+
}
|
|
570
|
+
const via: Record<string, readonly string[]> = {}
|
|
571
|
+
for (const [relation, actions] of Object.entries(role.via)) {
|
|
572
|
+
if (!Object.hasOwn(relations, relation)) {
|
|
573
|
+
this.#problem(where, `holds actions via '${relation}', which is not a relation of the vocabulary`)
|
|
574
|
+
}
|
|
575
|
+
if (actions.length === 0) {
|
|
576
|
+
this.#problem(where, `holds nothing via '${relation}' (allowed: via: { ${relation}: [<exact actions>] })`)
|
|
577
|
+
}
|
|
578
|
+
this.#unique(where, `via.${relation}`, actions)
|
|
579
|
+
for (const action of actions) {
|
|
580
|
+
this.#knownAction(where, action)
|
|
581
|
+
if (assigning.has(action)) {
|
|
582
|
+
this.#problem(where, `holds '${action}' via '${relation}', which inserts a relation's rows: a relation never delegates itself onward`)
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
via[relation] = [...actions]
|
|
586
|
+
}
|
|
587
|
+
return via
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
/** Whether `dimension` is `ancestor` or lies inside it, by the contract's declared containment. */
|
|
591
|
+
#lies(dimension: string, ancestor: string): boolean {
|
|
592
|
+
const seen: string[] = []
|
|
593
|
+
let at: string | undefined = dimension
|
|
594
|
+
while (at !== undefined && !seen.includes(at)) {
|
|
595
|
+
if (at === ancestor) return true
|
|
596
|
+
seen.push(at)
|
|
597
|
+
at = this.#contract.dimensions[at]?.in
|
|
598
|
+
}
|
|
599
|
+
return false
|
|
600
|
+
}
|
|
601
|
+
|
|
496
602
|
// ── Mounts ──────────────────────────────────────────────────────────────────────────────────
|
|
497
603
|
|
|
498
604
|
#mount(name: string, mount: MountDeclaration<SchemaShape>): MountArtifact | null {
|
|
@@ -2146,7 +2252,7 @@ class ArtifactBuilder {
|
|
|
2146
2252
|
...(kicks.length === 0 ? {} : { kicks }),
|
|
2147
2253
|
...(binds === undefined ? {} : { binds }),
|
|
2148
2254
|
...(signs.length === 0 ? {} : { signs }),
|
|
2149
|
-
...(egress
|
|
2255
|
+
...(egress === null ? {} : { egress }),
|
|
2150
2256
|
}
|
|
2151
2257
|
if (place.kind !== 'rpc') {
|
|
2152
2258
|
this.#rpcOnly(where, 'connect', value['connect'])
|
|
@@ -2200,6 +2306,9 @@ class ArtifactBuilder {
|
|
|
2200
2306
|
this.#problem(where, `declares unscoped '${table}': 'write', and it runs read-only (allowed: 'read')`)
|
|
2201
2307
|
}
|
|
2202
2308
|
const policy = Object.hasOwn(this.#tables, table) ? this.#tables[table] : undefined
|
|
2309
|
+
if (mode === 'write' && policy?.confers !== undefined) {
|
|
2310
|
+
this.#problem(where, `declares unscoped '${table}': 'write', and its rows confer a relation: write them through a capability`)
|
|
2311
|
+
}
|
|
2203
2312
|
if (mode === 'write' && policy?.view === true) {
|
|
2204
2313
|
this.#problem(where, `declares unscoped '${table}': 'write', and no site writes a view: its rows come from the tables it reads (allowed: 'read')`)
|
|
2205
2314
|
} else if (mode === 'write' && policy?.scope.mode === 'reference') {
|
|
@@ -2347,12 +2456,13 @@ class ArtifactBuilder {
|
|
|
2347
2456
|
|
|
2348
2457
|
/**
|
|
2349
2458
|
* The HTTPS origins a site's code calls: a credentialed procedure of an RPC mount, a webhook or a job, never a public,
|
|
2350
|
-
* export or link procedure. Each is an exact origin or a one-label pattern (`parseEgressEntry`), once
|
|
2351
|
-
*
|
|
2459
|
+
* export or link procedure. Each is an exact origin or a one-label pattern (`parseEgressEntry`), once. Or `'public'`,
|
|
2460
|
+
* every public host (ADR-0075), which only a cron job declares: it calls outside any transaction, and its schedule,
|
|
2461
|
+
* not a caller, decides when. `null` when it declares none or after a problem.
|
|
2352
2462
|
*/
|
|
2353
|
-
#egress(where: string, value: unknown, place: DeclaringSite):
|
|
2463
|
+
#egress(where: string, value: unknown, place: DeclaringSite): DeclaredEgress | null {
|
|
2354
2464
|
if (value === undefined) {
|
|
2355
|
-
return
|
|
2465
|
+
return null
|
|
2356
2466
|
}
|
|
2357
2467
|
const refusedBy = place.kind === 'export'
|
|
2358
2468
|
? 'an export procedure'
|
|
@@ -2363,15 +2473,35 @@ class ArtifactBuilder {
|
|
|
2363
2473
|
: null
|
|
2364
2474
|
if (refusedBy !== null) {
|
|
2365
2475
|
this.#problem(where, `declares egress, which ${refusedBy} never does: a credentialed procedure, a webhook or a job calls out`)
|
|
2366
|
-
return
|
|
2476
|
+
return null
|
|
2477
|
+
}
|
|
2478
|
+
if (value === PUBLIC_EGRESS) {
|
|
2479
|
+
if (place.kind !== 'job') {
|
|
2480
|
+
this.#problem(
|
|
2481
|
+
where,
|
|
2482
|
+
`declares egress: '${PUBLIC_EGRESS}', which only a cron job declares: a procedure or a webhook names its origins (allowed: egress: ['https://api.example.com'])`,
|
|
2483
|
+
)
|
|
2484
|
+
return null
|
|
2485
|
+
}
|
|
2486
|
+
return PUBLIC_EGRESS
|
|
2367
2487
|
}
|
|
2368
2488
|
if (!Array.isArray(value) || value.length === 0 || !value.every((origin) => typeof origin === 'string')) {
|
|
2369
|
-
this.#problem(
|
|
2370
|
-
|
|
2489
|
+
this.#problem(
|
|
2490
|
+
where,
|
|
2491
|
+
place.kind === 'job'
|
|
2492
|
+
? "egress is not a list of origins or 'public' (allowed: egress: ['https://api.example.com'] or egress: 'public')"
|
|
2493
|
+
: "egress is not a list of origins (allowed: egress: ['https://api.example.com'])",
|
|
2494
|
+
)
|
|
2495
|
+
return null
|
|
2371
2496
|
}
|
|
2372
2497
|
const origins: string[] = value.filter((origin) => typeof origin === 'string')
|
|
2373
2498
|
if (origins.length > MAX_EGRESS_ORIGINS) {
|
|
2374
|
-
this.#problem(
|
|
2499
|
+
this.#problem(
|
|
2500
|
+
where,
|
|
2501
|
+
`${origins.length} egress origins exceed the limit of ${MAX_EGRESS_ORIGINS}${
|
|
2502
|
+
place.kind === 'job' ? " (a cron job that calls the websites its operators name declares egress: 'public')" : ''
|
|
2503
|
+
}`,
|
|
2504
|
+
)
|
|
2375
2505
|
}
|
|
2376
2506
|
for (const origin of origins) {
|
|
2377
2507
|
const parsed = parseEgressEntry(origin)
|
package/src/contract/compile.ts
CHANGED
|
@@ -69,6 +69,7 @@ export function describeContract(contract: AnyContract): ContractDeclaration<Sch
|
|
|
69
69
|
dimensions: vocabulary.dimensions,
|
|
70
70
|
actions: vocabulary.actions,
|
|
71
71
|
roles: vocabulary.roles,
|
|
72
|
+
...(vocabulary.relations === undefined ? {} : { relations: vocabulary.relations }),
|
|
72
73
|
mounts,
|
|
73
74
|
files: surface.files ?? {},
|
|
74
75
|
jobs: surface.jobs ?? {},
|
|
@@ -9,6 +9,8 @@ export interface ContractDeclaration<S> {
|
|
|
9
9
|
readonly dimensions: Readonly<Record<string, DimensionDeclaration>>
|
|
10
10
|
readonly actions: Readonly<Record<string, string>>
|
|
11
11
|
readonly roles: Readonly<Record<string, RoleDeclaration>>
|
|
12
|
+
/** The vocabulary's relations, by name; absent without any. */
|
|
13
|
+
readonly relations?: Readonly<Record<string, { readonly dimension: string }>>
|
|
12
14
|
readonly mounts: Readonly<Record<string, MountDeclaration<S>>>
|
|
13
15
|
readonly files: Readonly<Record<string, FileKindDeclaration>>
|
|
14
16
|
readonly jobs: Readonly<Record<string, CronDeclaration>>
|
|
@@ -134,6 +136,8 @@ export interface RoleDeclaration {
|
|
|
134
136
|
readonly member?: { readonly scope: string; readonly assignableBy: readonly string[] }
|
|
135
137
|
/** `true` only; `buildArtifact` refuses another value, and refuses it on a role without `member`. */
|
|
136
138
|
readonly external?: boolean
|
|
139
|
+
/** Relation → the actions a global holder of the role holds where a row of the relation names them. */
|
|
140
|
+
readonly via?: Readonly<Record<string, readonly string[]>>
|
|
137
141
|
}
|
|
138
142
|
|
|
139
143
|
export type AccessDeclaration =
|
package/src/contract/define.ts
CHANGED
|
@@ -95,6 +95,17 @@ export interface RoleDef<A extends string, D extends string, R extends string> {
|
|
|
95
95
|
* only internal people hold it. Only a role with `member` may declare it; an internal person may hold it too.
|
|
96
96
|
*/
|
|
97
97
|
readonly external?: true
|
|
98
|
+
/**
|
|
99
|
+
* Relation → actions: a holder of this role, granted globally, holds them at each node a row of the relation's
|
|
100
|
+
* source names them at (`via: { owner: ['projects.edit'] }`). A grant at a value holds them only on rows inside that
|
|
101
|
+
* value, so a membership role's relation has the role's dimension or one inside it. An external role takes none.
|
|
102
|
+
*/
|
|
103
|
+
readonly via?: { readonly [relation: string]: readonly A[] }
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** A relation of the vocabulary: a table's rows name a principal at a node of `dimension` (`confers` on that table). */
|
|
107
|
+
export interface RelationDef<D extends string> {
|
|
108
|
+
readonly dimension: D
|
|
98
109
|
}
|
|
99
110
|
|
|
100
111
|
export interface Vocabulary<A extends string, D extends string, R extends string> extends Presentation, AppPeople<A>, AppTerminal {
|
|
@@ -102,6 +113,7 @@ export interface Vocabulary<A extends string, D extends string, R extends string
|
|
|
102
113
|
readonly dimensions: { readonly [K in D]: DimensionDef<A, D, R> }
|
|
103
114
|
readonly actions: { readonly [K in A]: string }
|
|
104
115
|
readonly roles: { readonly [K in R]: RoleDef<A, D, R> }
|
|
116
|
+
readonly relations?: { readonly [name: string]: RelationDef<D> }
|
|
105
117
|
}
|
|
106
118
|
|
|
107
119
|
/** The actions that manage and list the application's own people. */
|
package/src/contract/group.ts
CHANGED
|
@@ -115,7 +115,16 @@ export type SignsField<Sg, Purposes extends string> =
|
|
|
115
115
|
* guard on the global `fetch` refuses any other while the site runs; a public procedure declares none.
|
|
116
116
|
*/
|
|
117
117
|
export interface EgressField {
|
|
118
|
-
readonly egress?: readonly `https://${string}`[]
|
|
118
|
+
readonly egress?: readonly `https://${string}`[] | Unavailable<"egress: 'public' is a cron job's only: record a row and kick a job that declares it">
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* A cron job's `egress`: its exact HTTPS origins, or `'public'`, every public host over HTTPS or HTTP on its default
|
|
123
|
+
* port, for a job that calls the websites its operators name (ADR-0075). The guard refuses IP addresses, local and
|
|
124
|
+
* internal names and the installation's own hosts, checks each redirect, and bounds each request's time and body.
|
|
125
|
+
*/
|
|
126
|
+
export interface JobEgressField {
|
|
127
|
+
readonly egress?: readonly `https://${string}`[] | 'public'
|
|
119
128
|
}
|
|
120
129
|
|
|
121
130
|
/** Each purpose `signs` names is one of `defineApp`'s `tokens`. */
|
package/src/contract/kit.ts
CHANGED
|
@@ -57,6 +57,7 @@ import type {
|
|
|
57
57
|
GroupBuild,
|
|
58
58
|
GroupInput,
|
|
59
59
|
GroupKit,
|
|
60
|
+
JobEgressField,
|
|
60
61
|
KicksField,
|
|
61
62
|
LimitsOption,
|
|
62
63
|
LinkGroupKit,
|
|
@@ -96,7 +97,7 @@ export type CronOptions<Acts, S, U, Is, Ix extends AnyDbIndex, M = never, Ks = n
|
|
|
96
97
|
& MailerField<M>
|
|
97
98
|
& KicksField<Ks>
|
|
98
99
|
& SignsField<Sg, Purposes>
|
|
99
|
-
&
|
|
100
|
+
& JobEgressField
|
|
100
101
|
|
|
101
102
|
/** The mail transport a job reaches, inferred from its optional field and then required, like a declared field. */
|
|
102
103
|
type MailerField<M> =
|
|
@@ -555,6 +556,7 @@ function runtimeApp(vocabulary: AnyAppVocabulary, options: KitOptions | undefine
|
|
|
555
556
|
dimensions: vocabulary.dimensions,
|
|
556
557
|
actions: vocabulary.actions,
|
|
557
558
|
roles: vocabulary.roles,
|
|
559
|
+
...(vocabulary.relations === undefined ? {} : { relations: vocabulary.relations }),
|
|
558
560
|
...presentationOf(vocabulary),
|
|
559
561
|
...peopleOf(vocabulary),
|
|
560
562
|
...terminalOf(vocabulary),
|
package/src/contract/platform.ts
CHANGED
|
@@ -96,6 +96,7 @@ function roleDef(key: string, role: RoleArtifact): RoleDef {
|
|
|
96
96
|
permissions: [...role.grants],
|
|
97
97
|
...(role.member === null ? {} : { member: { scope: role.member.scope, assignableBy: [...role.member.assignableBy] } }),
|
|
98
98
|
...(role.external === true ? { external: true } : {}),
|
|
99
|
+
...(role.via === undefined ? {} : { via: Object.fromEntries(Object.entries(role.via).map(([relation, actions]) => [relation, [...actions]])) }),
|
|
99
100
|
}
|
|
100
101
|
}
|
|
101
102
|
|
|
@@ -7,6 +7,7 @@ import {
|
|
|
7
7
|
type DimensionDef,
|
|
8
8
|
type Presentation,
|
|
9
9
|
presentationOf,
|
|
10
|
+
type RelationDef,
|
|
10
11
|
type RoleDefs,
|
|
11
12
|
type TerminalDeclaration,
|
|
12
13
|
type Vocabulary,
|
|
@@ -49,6 +50,7 @@ export function defineVocabulary<
|
|
|
49
50
|
readonly dimensions: Dims & { readonly [K in D]: DimensionDef<NoInfer<A>, NoInfer<D>, NoInfer<R>> }
|
|
50
51
|
readonly actions: { readonly [K in A]: K extends `${string}*${string}` ? WildcardMessage : string }
|
|
51
52
|
readonly roles: RoleDefs<NoInfer<A>, NoInfer<D>, R>
|
|
53
|
+
readonly relations?: { readonly [name: string]: RelationDef<NoInfer<D>> }
|
|
52
54
|
readonly members?: M
|
|
53
55
|
readonly directory?: 'labels'
|
|
54
56
|
readonly terminal?: T
|
|
@@ -60,6 +62,7 @@ export function defineVocabulary<
|
|
|
60
62
|
dimensions: vocabulary.dimensions,
|
|
61
63
|
actions: vocabulary.actions,
|
|
62
64
|
roles: vocabulary.roles,
|
|
65
|
+
...(vocabulary.relations === undefined ? {} : { relations: vocabulary.relations }),
|
|
63
66
|
...presentationOf(vocabulary),
|
|
64
67
|
...(people === undefined ? {} : { members: people }),
|
|
65
68
|
...(vocabulary.directory === undefined ? {} : { directory: vocabulary.directory }),
|
package/src/disk-assets.ts
CHANGED
|
@@ -2,8 +2,10 @@
|
|
|
2
2
|
// test kit serves a built directory the same way.
|
|
3
3
|
|
|
4
4
|
import { rawRequestTarget } from '@fabrika/auth-core'
|
|
5
|
-
import {
|
|
5
|
+
import type { BunFile } from 'bun'
|
|
6
|
+
import { basename, join, resolve, sep } from 'node:path'
|
|
6
7
|
import type { SpaAssets } from './implement/dispatch.js'
|
|
8
|
+
import { isSourceMapName } from './source-map-path.js'
|
|
7
9
|
import { isPageRoute } from './spa-fallback.js'
|
|
8
10
|
|
|
9
11
|
/**
|
|
@@ -18,8 +20,8 @@ export function diskAssets(root: string): SpaAssets {
|
|
|
18
20
|
const relative = mount.prefix === '/' ? pathname.slice(1) : pathname.slice(mount.prefix.length + 1)
|
|
19
21
|
// The path is canonical, so every segment decodes and none is `.` or `..`.
|
|
20
22
|
const file = join(dir, ...relative.split('/').filter((segment) => segment !== '').map((segment) => decodeURIComponent(segment)))
|
|
21
|
-
|
|
22
|
-
const found =
|
|
23
|
+
// The mount refuses a source map before it asks; this holds for any caller that serves through it directly.
|
|
24
|
+
const found = file.startsWith(`${dir}${sep}`) && !isSourceMapName(basename(file)) ? await existing(file) : null
|
|
23
25
|
const served = found ?? (isPageRoute(request) ? Bun.file(join(dir, 'index.html')) : null)
|
|
24
26
|
if (served === null || !(await served.exists())) {
|
|
25
27
|
return new Response('Not found', { status: 404 })
|
|
@@ -28,3 +30,13 @@ export function diskAssets(root: string): SpaAssets {
|
|
|
28
30
|
},
|
|
29
31
|
}
|
|
30
32
|
}
|
|
33
|
+
|
|
34
|
+
/** The file at `path` when it exists. A name no file can have (a decoded control character) is a missing asset, not a fault. */
|
|
35
|
+
async function existing(path: string): Promise<BunFile | null> {
|
|
36
|
+
try {
|
|
37
|
+
const file = Bun.file(path)
|
|
38
|
+
return (await file.exists()) ? file : null
|
|
39
|
+
} catch {
|
|
40
|
+
return null
|
|
41
|
+
}
|
|
42
|
+
}
|