@fabrika/app 0.9.0-dev.14 → 0.9.0-dev.15
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 +14 -9
- package/skill/SKILL.md +2 -2
- package/skill/references/app-setup.md +10 -9
- package/skill/references/endpoint.md +8 -1
- package/src/build-contract-child.ts +16 -0
- package/src/build.ts +48 -2
- package/src/client/contract.ts +6 -4
- package/src/cloudflare/application.ts +3 -0
- package/src/contract/artifact-schema.ts +355 -301
- package/src/contract/attachment.ts +4 -3
- package/src/contract/compile.ts +3 -2
- package/src/contract/context.ts +2 -3
- package/src/contract/define.ts +17 -5
- package/src/contract/group.ts +8 -7
- package/src/contract/index.ts +1 -1
- package/src/contract/kit.ts +2 -2
- package/src/contract/problems.ts +4 -0
- package/src/contract/schema-shape.ts +14 -2
- package/src/contract/token.ts +4 -3
- package/src/from-row.ts +12 -6
- package/src/implement/approved.ts +57 -0
- package/src/implement/attachment.ts +2 -1
- package/src/implement/boot.ts +90 -12
- package/src/implement/dispatch.ts +14 -10
- package/src/implement/egress.ts +7 -6
- package/src/implement/faults.ts +1 -0
- package/src/implement/project.ts +3 -1
- package/src/implement/tokens.ts +3 -2
- package/src/implement/types.ts +18 -6
- package/src/react/hooks.ts +12 -11
- package/src/react/provider.tsx +2 -1
- package/src/react/types.ts +2 -2
- package/src/schema/builder.ts +146 -0
- package/src/schema/data-schema.ts +365 -0
- package/src/schema/index.ts +18 -0
- package/src/schema/replay.ts +623 -0
- package/src/testing/kit.ts +3 -3
- package/types/src/build-contract-child.d.ts +1 -0
- package/types/src/build.d.ts +16 -1
- package/types/src/client/contract.d.ts +3 -4
- package/types/src/cloudflare/application.d.ts +2 -0
- package/types/src/contract/artifact-schema.d.ts +8 -0
- package/types/src/contract/attachment.d.ts +3 -2
- package/types/src/contract/context.d.ts +2 -3
- package/types/src/contract/define.d.ts +14 -5
- package/types/src/contract/group.d.ts +5 -6
- package/types/src/contract/index.d.ts +1 -1
- package/types/src/contract/kit.d.ts +2 -3
- package/types/src/contract/problems.d.ts +1 -0
- package/types/src/contract/schema-shape.d.ts +3 -2
- package/types/src/contract/token.d.ts +3 -3
- package/types/src/from-row.d.ts +9 -5
- package/types/src/implement/approved.d.ts +11 -0
- package/types/src/implement/boot.d.ts +6 -0
- package/types/src/implement/faults.d.ts +1 -0
- package/types/src/implement/project.d.ts +2 -1
- package/types/src/implement/types.d.ts +4 -5
- package/types/src/react/hooks.d.ts +4 -5
- package/types/src/react/types.d.ts +2 -2
- package/types/src/schema/builder.d.ts +45 -0
- package/types/src/schema/data-schema.d.ts +124 -0
- package/types/src/schema/index.d.ts +3 -0
- package/types/src/schema/replay.d.ts +27 -0
- package/types/src/testing/kit.d.ts +2 -3
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
// zod schema of what the handler returns (the rows' array), marked with what it declares beside it.
|
|
4
4
|
|
|
5
5
|
import { z } from 'zod/v4'
|
|
6
|
+
import { type ZodOf, zodOf } from '../schema/data-schema'
|
|
6
7
|
import { type AttachmentDeclaration, unknownOptions } from './declaration'
|
|
7
8
|
import type { InputSchema, NotLoose, Schema } from './define'
|
|
8
9
|
|
|
@@ -17,8 +18,8 @@ export interface AttachmentMark {
|
|
|
17
18
|
/** The marks `attachmentOutput` made: a property another module set on a schema is no attachment. */
|
|
18
19
|
const marks = new WeakSet<object>()
|
|
19
20
|
|
|
20
|
-
/** An attachment output of rows `R`: the handler returns `
|
|
21
|
-
export type Attachment<R extends InputSchema> = z.ZodArray<R
|
|
21
|
+
/** An attachment output of rows `R`: the handler returns `SchemaInput<R>[]`, and the caller receives a file. */
|
|
22
|
+
export type Attachment<R extends InputSchema> = z.ZodArray<ZodOf<R>> & AttachmentBrand
|
|
22
23
|
|
|
23
24
|
/** What tells an attachment output from a JSON one in the types. */
|
|
24
25
|
export interface AttachmentBrand {
|
|
@@ -60,7 +61,7 @@ export function attachment<R extends InputSchema>(options: AttachmentOptions<R &
|
|
|
60
61
|
export function attachmentOutput<R extends InputSchema>(row: R, declaration: AttachmentDeclaration): Attachment<R> {
|
|
61
62
|
const mark: AttachmentMark = Object.freeze({ declaration: Object.freeze({ ...declaration }), row })
|
|
62
63
|
marks.add(mark)
|
|
63
|
-
return Object.assign(z.array(row), { [ATTACHMENT]: mark })
|
|
64
|
+
return Object.assign(z.array(zodOf(row)), { [ATTACHMENT]: mark })
|
|
64
65
|
}
|
|
65
66
|
|
|
66
67
|
/** The mark of an `attachment()` output, or `null` for any other schema. */
|
package/src/contract/compile.ts
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
import type { ContractArtifact, SchemaShape, TablePolicyArtifact } from '@fabrika/auth-core'
|
|
5
5
|
import { isTables, tablePolicies, type Tables } from '@fabrika/db/tables'
|
|
6
6
|
import { z } from 'zod/v4'
|
|
7
|
+
import { DataSchema } from '../schema/data-schema'
|
|
7
8
|
import { attachmentOf } from './attachment'
|
|
8
9
|
import { buildArtifact } from './build'
|
|
9
10
|
import {
|
|
@@ -173,7 +174,7 @@ class SchemaReader {
|
|
|
173
174
|
}
|
|
174
175
|
}
|
|
175
176
|
|
|
176
|
-
/** Whether `value` is a zod
|
|
177
|
+
/** Whether `value` is a schema, zod or held as data: what a contract writes where a schema stands. */
|
|
177
178
|
function isSchema(value: unknown): value is Schema {
|
|
178
|
-
return value instanceof z.ZodType
|
|
179
|
+
return value instanceof z.ZodType || value instanceof DataSchema
|
|
179
180
|
}
|
package/src/contract/context.ts
CHANGED
|
@@ -20,7 +20,6 @@ import type {
|
|
|
20
20
|
UnscopedTables,
|
|
21
21
|
WithinTables,
|
|
22
22
|
} from '@fabrika/db/tables'
|
|
23
|
-
import type { z } from 'zod/v4'
|
|
24
23
|
import type { StoredFilesHandle, StoredFilesReadHandle } from '../files/handle'
|
|
25
24
|
import type { AppCapability, Ref, Within } from '../implement/capability'
|
|
26
25
|
import type { ApplicationDirectory, LinkIssuing, MemberDirectory, MemberLookup, MemberManagement } from '../implement/membership'
|
|
@@ -30,7 +29,7 @@ import type { CapabilityOf, ConnectCall, RequestContext } from '../implement/typ
|
|
|
30
29
|
import type { WebhookDelivery, WebhookPrincipal } from '../implement/webhook'
|
|
31
30
|
import type { AppMail, JobContext } from '../jobs/types'
|
|
32
31
|
import type { ConnectSnapshot } from './connect'
|
|
33
|
-
import type { MemberAccess, Schema } from './define'
|
|
32
|
+
import type { MemberAccess, Schema, SchemaOutput } from './define'
|
|
34
33
|
import type { App } from './kit'
|
|
35
34
|
import type { TokenPurposes, TokenSigning } from './token'
|
|
36
35
|
import type { WebhookBindings } from './webhook-binding'
|
|
@@ -116,7 +115,7 @@ export type SqlValue = string | number | boolean | bigint | Date | null | readon
|
|
|
116
115
|
* transaction; each row is parsed (snake_case → camelCase, `Date` → ISO text, then `Row`).
|
|
117
116
|
*/
|
|
118
117
|
export interface SqlTag<Ix extends AnyDbIndex = AnyDbIndex, M extends SqlMode = SqlMode> {
|
|
119
|
-
<Row extends Schema>(row: Row): (text: TemplateStringsArray, ...values: readonly (SqlValue | SqlScope)[]) => Promise<
|
|
118
|
+
<Row extends Schema>(row: Row): (text: TemplateStringsArray, ...values: readonly (SqlValue | SqlScope)[]) => Promise<SchemaOutput<Row>[]>
|
|
120
119
|
/**
|
|
121
120
|
* The capability's whole predicate on `table`: the object's key and every link of its chain for a `Ref`, what
|
|
122
121
|
* `ctx.db.within` matches for a `Within`, every row for `ctx.app`. Interpolated as
|
package/src/contract/define.ts
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
|
|
4
4
|
import type { BuiltinRoleKey, ChallengeProvider, Locale, MailTemplates, RpcCaller, WebhookScheme } from '@fabrika/auth-core'
|
|
5
5
|
import type { z } from 'zod/v4'
|
|
6
|
+
import type { DataObject, DataSchema, ZodOf } from '../schema/data-schema'
|
|
6
7
|
import {
|
|
7
8
|
type CronDeclaration,
|
|
8
9
|
type CspDeclaration,
|
|
@@ -36,19 +37,30 @@ export interface JobLimitsOption {
|
|
|
36
37
|
readonly timeoutMs?: number
|
|
37
38
|
}
|
|
38
39
|
|
|
39
|
-
/**
|
|
40
|
-
|
|
40
|
+
/**
|
|
41
|
+
* Any zod 4 schema, or one held as data (`@fabrika/app/schema`). `compileContract` refuses every form outside the
|
|
42
|
+
* contract subset.
|
|
43
|
+
*/
|
|
44
|
+
export type Schema = z.core.$ZodType | DataSchema
|
|
45
|
+
|
|
46
|
+
/** What a schema admits once parsed. */
|
|
47
|
+
export type SchemaOutput<S> = z.output<ZodOf<S>>
|
|
48
|
+
|
|
49
|
+
/** What a schema takes before parsing. */
|
|
50
|
+
export type SchemaInput<S> = z.input<ZodOf<S>>
|
|
41
51
|
|
|
42
52
|
/**
|
|
43
53
|
* An input object. zod 4's types do not tell `z.object` from `z.strictObject`, so the type refuses only loose
|
|
44
54
|
* objects; `compileContract` and `@fabrika/check` refuse `z.object` too.
|
|
45
55
|
*/
|
|
46
|
-
export type InputSchema = z.ZodObject<z.core.$ZodShape, z.core.$ZodObjectConfig>
|
|
56
|
+
export type InputSchema = z.ZodObject<z.core.$ZodShape, z.core.$ZodObjectConfig> | DataObject<z.core.$ZodShape, z.core.$ZodObjectConfig>
|
|
47
57
|
|
|
48
58
|
type LooseMessage = 'a loose object admits undeclared keys: declare it with z.strictObject({ … })'
|
|
49
59
|
|
|
50
60
|
/** `S`, unless it is an object that admits undeclared keys (`.loose()`, `.passthrough()`, `.catchall()`). */
|
|
51
|
-
export type NotLoose<S> = S extends
|
|
61
|
+
export type NotLoose<S> = S extends Schema ? LooseChecked<S, ZodOf<S>> : S
|
|
62
|
+
|
|
63
|
+
type LooseChecked<S, Z> = Z extends z.ZodObject<z.core.$ZodShape, infer Config extends z.core.$ZodObjectConfig>
|
|
52
64
|
? string extends keyof Config['out'] ? LooseMessage : S
|
|
53
65
|
: S
|
|
54
66
|
|
|
@@ -230,7 +242,7 @@ export interface PublicAccess {
|
|
|
230
242
|
}
|
|
231
243
|
|
|
232
244
|
/** Without an `input`, TS infers `I` as its whole constraint, not the `null` default; both mean "no input". */
|
|
233
|
-
export type InputOf<I> = [I] extends [InputSchema] ?
|
|
245
|
+
export type InputOf<I> = [I] extends [InputSchema] ? SchemaOutput<I> : Record<never, never>
|
|
234
246
|
|
|
235
247
|
/** Input fields of string type: the only fields a scope value can be read from. */
|
|
236
248
|
export type StringField<In> = { [K in keyof In]-?: In[K] extends string ? K : never }[keyof In] & string
|
package/src/contract/group.ts
CHANGED
|
@@ -4,7 +4,6 @@
|
|
|
4
4
|
|
|
5
5
|
import type { EndpointCache, RpcCaller } from '@fabrika/auth-core'
|
|
6
6
|
import type { AnyDbIndex, ReadOnlyUnscoped, Unavailable, UnscopedDeclaration, UnscopedMode } from '@fabrika/db/tables'
|
|
7
|
-
import type { z } from 'zod/v4'
|
|
8
7
|
import type { Snake } from '../from-row'
|
|
9
8
|
import type { ExtraKeys, HandlerInput, IsAny } from '../implement/types'
|
|
10
9
|
import type { AttachmentBrand } from './attachment'
|
|
@@ -38,6 +37,8 @@ import type {
|
|
|
38
37
|
PublicAccess,
|
|
39
38
|
QueryAccess,
|
|
40
39
|
Schema,
|
|
40
|
+
SchemaInput,
|
|
41
|
+
SchemaOutput,
|
|
41
42
|
} from './define'
|
|
42
43
|
import type { WithClaims } from './token'
|
|
43
44
|
|
|
@@ -227,7 +228,7 @@ export type ListOf<U extends string, Listed extends string = ''> = [U] extends [
|
|
|
227
228
|
: ListOf<Exclude<U, LastOf<U>>, Listed extends '' ? LastOf<U> & string : `${LastOf<U> & string}, ${Listed}`>
|
|
228
229
|
|
|
229
230
|
/** The fields, at any depth, that a handler `F` returns and the output `O` does not declare. */
|
|
230
|
-
export type UndeclaredFields<F, O extends Schema> = ExtraKeys<Returned<F>,
|
|
231
|
+
export type UndeclaredFields<F, O extends Schema> = ExtraKeys<Returned<F>, SchemaInput<O>>
|
|
231
232
|
|
|
232
233
|
/** An object with a camelCase field, which a database row names in snake_case. */
|
|
233
234
|
type HasCamel<V> = { [K in keyof V]: K extends string ? (Snake<K> extends K ? never : K) : never }[keyof V]
|
|
@@ -246,10 +247,10 @@ type RowShaped<V> = V extends readonly (infer Item)[] ? readonly RowShaped<Item>
|
|
|
246
247
|
* `ExactReturn` refuses with the fix, as it refuses anything but rows from an attachment's handler. Any other mistake
|
|
247
248
|
* keeps the compiler's own message about the output.
|
|
248
249
|
*/
|
|
249
|
-
export type HandlerReturn<F, O extends Schema> = [Returned<F>] extends [
|
|
250
|
+
export type HandlerReturn<F, O extends Schema> = [Returned<F>] extends [SchemaInput<O>] ? SchemaInput<O>
|
|
250
251
|
: [O] extends [AttachmentBrand] ? unknown
|
|
251
|
-
: [Returned<F>] extends [RowShaped<
|
|
252
|
-
:
|
|
252
|
+
: [Returned<F>] extends [RowShaped<SchemaInput<O>>] ? RowShaped<SchemaInput<O>>
|
|
253
|
+
: SchemaInput<O>
|
|
253
254
|
|
|
254
255
|
/** A kit endpoint's handler, returning `R`; `X` adds what its HTTP shape reads beside the input (`query`). */
|
|
255
256
|
export type KitHandler<In, Ctx, R, X = unknown> = (args: { readonly input: In; readonly ctx: Ctx } & X) => R | Promise<R>
|
|
@@ -259,7 +260,7 @@ export type KitHandler<In, Ctx, R, X = unknown> = (args: { readonly input: In; r
|
|
|
259
260
|
* as the claims of its purpose.
|
|
260
261
|
*/
|
|
261
262
|
export type QueryArgs<Q, T = Record<never, never>> = [Q] extends [never] ? unknown
|
|
262
|
-
: Q extends InputSchema ? { readonly query: WithClaims<
|
|
263
|
+
: Q extends InputSchema ? { readonly query: WithClaims<SchemaOutput<Q>, T> }
|
|
263
264
|
: unknown
|
|
264
265
|
|
|
265
266
|
/**
|
|
@@ -282,7 +283,7 @@ export interface HttpOption<Q> {
|
|
|
282
283
|
* returns a database row where the output is camelCase, anything but rows for an attachment, or, at any depth, a
|
|
283
284
|
* field the output does not declare. A field whose type is an error elsewhere in the handler is not reported again here.
|
|
284
285
|
*/
|
|
285
|
-
export type ExactReturn<F, O extends Schema, E> = [Returned<F>] extends [
|
|
286
|
+
export type ExactReturn<F, O extends Schema, E> = [Returned<F>] extends [SchemaInput<O>] ? [UndeclaredFields<F, O>] extends [never] ? E
|
|
286
287
|
: IsAny<UndeclaredFields<F, O>> extends true ? E
|
|
287
288
|
: Unavailable<`the handler returns ${ListOf<UndeclaredFields<F, O> & string>}, which the output does not declare: return only declared fields`>
|
|
288
289
|
: [O] extends [AttachmentBrand] ? Unavailable<'an attachment handler returns its rows: an array of its row schema, with nothing around it'>
|
package/src/contract/index.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// @fabrika/app/contract — the contract of an application: the staged kit (`defineVocabulary`, `defineApp`, its
|
|
2
2
|
// groups), `defineContract`, `compileContract`, the artifact parser, and the IAM schema it compiles to. Browser-safe:
|
|
3
3
|
// no server runtime, no Node or Bun API.
|
|
4
|
-
export { contractArtifactSchema, parseContractArtifact, schemaShapeSchema } from './artifact-schema'
|
|
4
|
+
export { contractArtifactSchema, isEncodedArtifact, parseContractArtifact, parseEncodedArtifact, schemaShapeSchema } from './artifact-schema'
|
|
5
5
|
export {
|
|
6
6
|
type Attachment,
|
|
7
7
|
attachment,
|
package/src/contract/kit.ts
CHANGED
|
@@ -5,7 +5,6 @@
|
|
|
5
5
|
|
|
6
6
|
import type { JobMailer, RpcCaller, WebhookScheme } from '@fabrika/auth-core'
|
|
7
7
|
import type { AnyDbIndex, DbIndex, Tables, Unavailable, UnscopedDeclaration, UnscopedMode } from '@fabrika/db/tables'
|
|
8
|
-
import type { z } from 'zod/v4'
|
|
9
8
|
import type { Declared, JobKitContext, KickContext, KitImports, KitTypes, NoTablesIndex, SqlMode, TokensContext, WebhookKitContext } from './context'
|
|
10
9
|
import {
|
|
11
10
|
type AccessDeclaration,
|
|
@@ -43,6 +42,7 @@ import {
|
|
|
43
42
|
type ProcedureTree,
|
|
44
43
|
type RpcMount,
|
|
45
44
|
type Schema,
|
|
45
|
+
type SchemaOutput,
|
|
46
46
|
type Surface,
|
|
47
47
|
surfaceKit,
|
|
48
48
|
terminalOf,
|
|
@@ -157,7 +157,7 @@ export interface WebhookBuilder<
|
|
|
157
157
|
> {
|
|
158
158
|
handle(
|
|
159
159
|
handler: (
|
|
160
|
-
args: { readonly input:
|
|
160
|
+
args: { readonly input: SchemaOutput<I>; readonly ctx: WebhookKitContext<K, B, Acts, D> & KickContext<Ks> & TokensContext<K, Sg> },
|
|
161
161
|
) => void | Promise<void>,
|
|
162
162
|
): KitWebhook<B, Acts, I, D>
|
|
163
163
|
}
|
package/src/contract/problems.ts
CHANGED
|
@@ -17,6 +17,10 @@ export class Problems {
|
|
|
17
17
|
this.#problems.push(`${where}: ${problem}`)
|
|
18
18
|
}
|
|
19
19
|
|
|
20
|
+
isEmpty(): boolean {
|
|
21
|
+
return this.#problems.length === 0
|
|
22
|
+
}
|
|
23
|
+
|
|
20
24
|
throwIfAny(): void {
|
|
21
25
|
if (this.#problems.length > 0) {
|
|
22
26
|
throw new ContractError([...this.#problems])
|
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
|
|
4
4
|
import type { ArrayShape, NumberShape, SchemaShape, StringShape } from '@fabrika/auth-core'
|
|
5
5
|
import { z } from 'zod/v4'
|
|
6
|
+
import { type DataSchema, zodSchemaOf } from '../schema/data-schema'
|
|
7
|
+
import { SchemaRefusal } from '../schema/replay'
|
|
6
8
|
import { attachmentOf } from './attachment'
|
|
7
9
|
import { fileOf } from './file'
|
|
8
10
|
import type { Problems } from './problems'
|
|
@@ -18,8 +20,18 @@ function isStringFormat(format: string): format is StringFormat {
|
|
|
18
20
|
return STRING_FORMATS.has(format)
|
|
19
21
|
}
|
|
20
22
|
|
|
21
|
-
/** A schema's shape, or `null` after recording why it has none. */
|
|
22
|
-
export function describeSchema(
|
|
23
|
+
/** A schema's shape, or `null` after recording why it has none. A schema held as data is read as the zod it builds. */
|
|
24
|
+
export function describeSchema(described: z.core.$ZodType | DataSchema, where: string, problems: Problems): SchemaShape | null {
|
|
25
|
+
let schema: z.core.$ZodType
|
|
26
|
+
try {
|
|
27
|
+
schema = zodSchemaOf(described)
|
|
28
|
+
} catch (error) {
|
|
29
|
+
if (error instanceof SchemaRefusal) {
|
|
30
|
+
problems.add(where, `${error.message} (allowed: ${error.allowed})`)
|
|
31
|
+
return null
|
|
32
|
+
}
|
|
33
|
+
throw error
|
|
34
|
+
}
|
|
23
35
|
if (attachmentOf(schema) !== null) {
|
|
24
36
|
problems.add(where, "an attachment() is a procedure's whole output, never part of a schema or an input (allowed: output: attachment({ … }))")
|
|
25
37
|
return null
|
package/src/contract/token.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
// handler the purpose's typed claims. A token is single-purpose and no credential: it opens no mount.
|
|
5
5
|
|
|
6
6
|
import { z } from 'zod/v4'
|
|
7
|
-
import type { InputSchema, NotLoose, Schema } from './define'
|
|
7
|
+
import type { InputSchema, NotLoose, Schema, SchemaInput, SchemaOutput } from './define'
|
|
8
8
|
|
|
9
9
|
const SIGNED_TOKEN = Symbol('fabrika.signedToken')
|
|
10
10
|
|
|
@@ -77,7 +77,8 @@ export type TokenPurposeOf<V> = V extends { readonly [z.core.$brand]: infer B }
|
|
|
77
77
|
/** One field as the handler holds it: a signed token as the claims of its purpose, any other field as it is. */
|
|
78
78
|
type ClaimsField<V, T> = [TokenPurposeOf<NonNullable<V>>] extends [never] ? V
|
|
79
79
|
:
|
|
80
|
-
| (TokenPurposeOf<NonNullable<V>> extends keyof T ? T[TokenPurposeOf<NonNullable<V>>] extends TokenPurpose<infer C> ?
|
|
80
|
+
| (TokenPurposeOf<NonNullable<V>> extends keyof T ? T[TokenPurposeOf<NonNullable<V>>] extends TokenPurpose<infer C> ? SchemaOutput<C> : never
|
|
81
|
+
: never)
|
|
81
82
|
| (undefined extends V ? undefined : never)
|
|
82
83
|
|
|
83
84
|
/** An input as its handler receives it: each signed token field replaced by the verified claims of its purpose. */
|
|
@@ -85,5 +86,5 @@ export type WithClaims<In, T> = [keyof In] extends [never] ? In : { readonly [F
|
|
|
85
86
|
|
|
86
87
|
/** `ctx.tokens` of a site that declares `signs`: a token of one of those purposes, valid for `days`. */
|
|
87
88
|
export interface TokenSigning<T extends TokenPurposes, S extends string> {
|
|
88
|
-
sign<const P extends S & keyof T & string>(purpose: P, claims:
|
|
89
|
+
sign<const P extends S & keyof T & string>(purpose: P, claims: SchemaInput<T[P]['claims']>, options: { readonly days: number }): string
|
|
89
90
|
}
|
package/src/from-row.ts
CHANGED
|
@@ -5,7 +5,12 @@
|
|
|
5
5
|
// `YYYY-MM-DD` text from the data layer.
|
|
6
6
|
|
|
7
7
|
import { z } from 'zod/v4'
|
|
8
|
+
import type { SchemaInput, SchemaOutput } from './contract/define'
|
|
8
9
|
import { project } from './implement/project'
|
|
10
|
+
import { type DataObject, zodOf } from './schema/data-schema'
|
|
11
|
+
|
|
12
|
+
/** An object schema: a zod one, or one held as data. */
|
|
13
|
+
type ObjectSchema = z.ZodObject | DataObject<z.core.$ZodShape, z.core.$ZodObjectConfig>
|
|
9
14
|
|
|
10
15
|
/** `companyId` → `company_id`: the column a field is read from. */
|
|
11
16
|
export type Snake<S extends string> = S extends `${infer Head}${infer Tail}`
|
|
@@ -16,7 +21,7 @@ export type Snake<S extends string> = S extends `${infer Head}${infer Tail}`
|
|
|
16
21
|
type Widened<V> = V extends string ? string | Date : V
|
|
17
22
|
|
|
18
23
|
/** The row `fromRow` takes for `S`: one column per declared field; any other column is allowed and dropped. */
|
|
19
|
-
export type RowInput<S extends
|
|
24
|
+
export type RowInput<S extends ObjectSchema> = { readonly [K in keyof SchemaInput<S> as Snake<K & string>]: Widened<SchemaInput<S>[K]> }
|
|
20
25
|
|
|
21
26
|
function camel(column: string): string {
|
|
22
27
|
return column.replace(/_([a-z0-9])/g, (_match, next: string) => next.toUpperCase())
|
|
@@ -35,19 +40,20 @@ function dateText(schema: z.ZodObject, field: string, value: Date): string {
|
|
|
35
40
|
}
|
|
36
41
|
|
|
37
42
|
/** The row as `schema`'s output; a row the schema refuses throws, as a handler's bug. */
|
|
38
|
-
export function fromRow<const S extends
|
|
43
|
+
export function fromRow<const S extends ObjectSchema>(schema: S, row: RowInput<S>): SchemaOutput<S> {
|
|
44
|
+
const object = zodOf(schema)
|
|
39
45
|
const fields: Record<string, unknown> = {}
|
|
40
46
|
for (const [column, value] of Object.entries(row)) {
|
|
41
47
|
const field = camel(column)
|
|
42
|
-
Object.defineProperty(fields, field, { value: value instanceof Date ? dateText(
|
|
48
|
+
Object.defineProperty(fields, field, { value: value instanceof Date ? dateText(object, field, value) : value, enumerable: true })
|
|
43
49
|
}
|
|
44
|
-
return z.parse(
|
|
50
|
+
return z.parse(object, project(object, fields))
|
|
45
51
|
}
|
|
46
52
|
|
|
47
53
|
/** A list's page as a page output: each row through `fromRow`, and `next` as the list answered it. */
|
|
48
|
-
export function fromPage<const S extends
|
|
54
|
+
export function fromPage<const S extends ObjectSchema>(
|
|
49
55
|
schema: S,
|
|
50
56
|
page: { readonly items: readonly RowInput<S>[]; readonly next: string | null },
|
|
51
|
-
): { items:
|
|
57
|
+
): { items: SchemaOutput<S>[]; next: string | null } {
|
|
52
58
|
return { items: page.items.map((row) => fromRow(schema, row)), next: page.next }
|
|
53
59
|
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// Validation by the approved shapes: an endpoint validates with the application's own schema (its messages and
|
|
2
|
+
// defaults), once that schema's shape is the one the approved contract holds for the endpoint. Boot checks only the
|
|
3
|
+
// contract's digest, so each endpoint's schemas are read and compared the first time it uses them.
|
|
4
|
+
|
|
5
|
+
import {
|
|
6
|
+
canonicalJson,
|
|
7
|
+
canonicalShape,
|
|
8
|
+
type EndpointRow,
|
|
9
|
+
isAttachmentShape,
|
|
10
|
+
isFileShape,
|
|
11
|
+
isRedirectShape,
|
|
12
|
+
type SchemaShape,
|
|
13
|
+
} from '@fabrika/auth-core'
|
|
14
|
+
import type { Schema } from '../contract/define'
|
|
15
|
+
import { Problems } from '../contract/problems'
|
|
16
|
+
import { describeSchema } from '../contract/schema-shape'
|
|
17
|
+
import { ServerFault } from './faults'
|
|
18
|
+
|
|
19
|
+
type Slot = 'input' | 'output'
|
|
20
|
+
|
|
21
|
+
const approved = new WeakMap<EndpointRow, Map<Slot, Schema>>()
|
|
22
|
+
|
|
23
|
+
/** `schema`, the endpoint's input, once its shape is the row's. */
|
|
24
|
+
export function approvedInput(row: EndpointRow, schema: Schema): Schema {
|
|
25
|
+
return approvedIn(row, 'input', row.input, schema)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* `schema`, the endpoint's JSON output, once its shape is the row's. A redirect's target, an attachment's rows and a
|
|
30
|
+
* file stand in the row in a form of their own, so their schemas are not compared.
|
|
31
|
+
*/
|
|
32
|
+
export function approvedOutput(row: EndpointRow, schema: Schema): Schema {
|
|
33
|
+
const output = row.output
|
|
34
|
+
if (output === null || isRedirectShape(output) || isAttachmentShape(output) || isFileShape(output)) {
|
|
35
|
+
return schema
|
|
36
|
+
}
|
|
37
|
+
return approvedIn(row, 'output', output, schema)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function approvedIn(row: EndpointRow, slot: Slot, expected: SchemaShape | null, schema: Schema): Schema {
|
|
41
|
+
const checked = approved.get(row)
|
|
42
|
+
if (checked?.get(slot) === schema) {
|
|
43
|
+
return schema
|
|
44
|
+
}
|
|
45
|
+
if (expected === null || !hasShape(schema, expected, `'${row.id}' ${slot}`)) {
|
|
46
|
+
throw new ServerFault('schema_unapproved', `'${row.id}': the ${slot} schema the application evaluated is not the one its approved contract holds`)
|
|
47
|
+
}
|
|
48
|
+
approved.set(row, (checked ?? new Map<Slot, Schema>()).set(slot, schema))
|
|
49
|
+
return schema
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Whether `schema` reads to the canonical shape `expected`; a schema outside the subset never does. */
|
|
53
|
+
export function hasShape(schema: Schema, expected: SchemaShape, where: string): boolean {
|
|
54
|
+
const problems = new Problems()
|
|
55
|
+
const actual = describeSchema(schema, where, problems)
|
|
56
|
+
return actual !== null && problems.isEmpty() && canonicalJson(canonicalShape(actual)) === canonicalJson(canonicalShape(expected))
|
|
57
|
+
}
|
|
@@ -9,6 +9,7 @@ import { attachmentOf } from '../contract/attachment'
|
|
|
9
9
|
import { ATTACHMENT_LIMITS, CSV_CONTENT_TYPE, XLSX_CONTENT_TYPE } from '../contract/defaults'
|
|
10
10
|
import type { Schema } from '../contract/define'
|
|
11
11
|
import { contentDisposition } from '../files/treatment'
|
|
12
|
+
import { zodSchemaOf } from '../schema/data-schema'
|
|
12
13
|
import { ServerFault } from './faults'
|
|
13
14
|
import { project, ProjectionRefusedError } from './project'
|
|
14
15
|
import { encodeXlsx } from './xlsx'
|
|
@@ -58,7 +59,7 @@ function validRow(endpoint: string, schema: Schema, row: unknown): unknown {
|
|
|
58
59
|
}
|
|
59
60
|
throw error
|
|
60
61
|
}
|
|
61
|
-
const parsed = z.safeParse(schema, projected)
|
|
62
|
+
const parsed = z.safeParse(zodSchemaOf(schema), projected)
|
|
62
63
|
if (!parsed.success) {
|
|
63
64
|
throw new ServerFault('output_refused', `'${endpoint}' returned a row its row schema refuses`)
|
|
64
65
|
}
|
package/src/implement/boot.ts
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
// `boot(app, { environment, iam })`: called once, by the generated entrypoint through its runtime adapter, after the
|
|
2
|
-
// adapter captured the framework's variables and scrubbed them from the process. It
|
|
3
|
-
// every handler to its endpoint and refuses to start when anything
|
|
2
|
+
// adapter captured the framework's variables and scrubbed them from the process. It reads the approved contract (the
|
|
3
|
+
// artifact the build compiled, or compiles it), binds every handler to its endpoint and refuses to start when anything
|
|
4
|
+
// declared cannot be served.
|
|
4
5
|
|
|
5
6
|
import { IamMembership } from '@fabrika/auth'
|
|
6
7
|
import {
|
|
8
|
+
canonicalArtifactDigest,
|
|
7
9
|
compileEndpointTable,
|
|
8
10
|
type ContractArtifact,
|
|
9
11
|
contractDigest,
|
|
@@ -38,6 +40,7 @@ import type { EmailProviderRegistry } from '@fabrika/email'
|
|
|
38
40
|
import { builtinEmailProviders } from '@fabrika/email/providers'
|
|
39
41
|
import { TokenVerifier } from '@fabrika/jwks'
|
|
40
42
|
import type { FileObjectStore } from '@fabrika/platform'
|
|
43
|
+
import { parseEncodedArtifact } from '../contract/artifact-schema'
|
|
41
44
|
import { compileContract } from '../contract/compile'
|
|
42
45
|
import { exportDescription } from '../contract/connect'
|
|
43
46
|
import { containersOf } from '../contract/containers'
|
|
@@ -53,6 +56,7 @@ import { type MailStandIn, resolveMailTransports } from '../jobs/mail'
|
|
|
53
56
|
import { logReporter, type OperationsReporter, operationsReporter, operationsSettings, type ReportSource } from '../jobs/report'
|
|
54
57
|
import { bindJobs, type ContractJobs } from '../jobs/runner'
|
|
55
58
|
import { environmentScrubber } from '../jobs/scrub'
|
|
59
|
+
import { hasShape } from './approved'
|
|
56
60
|
import { browserConfigs } from './browser-config'
|
|
57
61
|
import { createCapabilityIssuer, requestIsReadOnly } from './capability'
|
|
58
62
|
import type { ChallengeFetch, ChallengeWork } from './challenge'
|
|
@@ -91,6 +95,12 @@ export interface BootOptions {
|
|
|
91
95
|
/** The variables `captureEnvironment` took before the application's modules loaded. */
|
|
92
96
|
readonly environment: CapturedEnvironment
|
|
93
97
|
readonly iam: IamKeySource
|
|
98
|
+
/**
|
|
99
|
+
* The contract artifact the build compiled, as the text of its shared encoding (`fabrika/contract.generated.ts`). Boot
|
|
100
|
+
* decodes it, checks its digest against `FABRIKA_CONTRACT_DIGEST` and reads it instead of compiling the contract;
|
|
101
|
+
* without it, boot compiles.
|
|
102
|
+
*/
|
|
103
|
+
readonly approvedContract?: string
|
|
94
104
|
/** Serves the SPA mounts. Without it, a contract that declares one does not boot. */
|
|
95
105
|
readonly assets?: SpaAssets
|
|
96
106
|
/** The application's Postgres connection, which the Bun adapter opens. Without it, an application on `@fabrika/db` does not boot. */
|
|
@@ -249,10 +259,38 @@ function readFramework(framework: Readonly<Record<string, string>>, contractApp:
|
|
|
249
259
|
return { iamAppId, issuer: issuer ?? '', operationsOrigin }
|
|
250
260
|
}
|
|
251
261
|
|
|
262
|
+
/** The contract compiled from the evaluated one, which must be the approved one. */
|
|
263
|
+
function compiledArtifact(app: ContractImplementation, framework: Readonly<Record<string, string>>, problems: string[]): ContractArtifact {
|
|
264
|
+
const artifact = compileContract(app.contract, app.database?.tables ?? {})
|
|
265
|
+
checkContractDigest(framework, contractDigest(artifact), problems)
|
|
266
|
+
return artifact
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* The artifact the build compiled, decoded from its shared encoding. Decoding yields the canonical artifact with each
|
|
271
|
+
* shared shape one object, and its digest is taken as it is serialized, so neither the expanded artifact nor its text
|
|
272
|
+
* is ever built.
|
|
273
|
+
*/
|
|
274
|
+
function approvedArtifact(text: string, framework: Readonly<Record<string, string>>, problems: string[]): ContractArtifact {
|
|
275
|
+
let json: unknown
|
|
276
|
+
try {
|
|
277
|
+
json = JSON.parse(text)
|
|
278
|
+
} catch {
|
|
279
|
+
throw new BootError([...problems, 'the bundled contract is not JSON; rebuild the application with `fabrika app build`'])
|
|
280
|
+
}
|
|
281
|
+
let artifact: ContractArtifact
|
|
282
|
+
try {
|
|
283
|
+
artifact = parseEncodedArtifact(json)
|
|
284
|
+
} catch {
|
|
285
|
+
throw new BootError([...problems, 'the bundled contract is not an encoded contract artifact; rebuild the application with `fabrika app build`'])
|
|
286
|
+
}
|
|
287
|
+
checkContractDigest(framework, canonicalArtifactDigest(artifact), problems)
|
|
288
|
+
return artifact
|
|
289
|
+
}
|
|
290
|
+
|
|
252
291
|
/** The deploy was approved with one contract; this build must be that contract, or it does not start (ADR-0022 rule 5). */
|
|
253
|
-
function checkContractDigest(framework: Readonly<Record<string, string>>,
|
|
292
|
+
function checkContractDigest(framework: Readonly<Record<string, string>>, actual: string, problems: string[]): void {
|
|
254
293
|
const expected = framework[FABRIKA_CONTRACT_DIGEST]?.trim() ?? ''
|
|
255
|
-
const actual = contractDigest(artifact)
|
|
256
294
|
if (expected === '') {
|
|
257
295
|
problems.push(`${FABRIKA_CONTRACT_DIGEST} is not set; it is the digest of the contract the deploy was approved with`)
|
|
258
296
|
} else if (expected !== actual) {
|
|
@@ -719,18 +757,36 @@ function pathsOf(artifact: ContractArtifact): ReadonlyMap<string, readonly HeldP
|
|
|
719
757
|
}
|
|
720
758
|
|
|
721
759
|
/** Each approved token purpose with the claims schema the application declared for it. */
|
|
722
|
-
function runtimePurposes(contract: AnyContract, artifact: ContractArtifact): ReadonlyMap<string, RuntimePurpose> {
|
|
760
|
+
function runtimePurposes(contract: AnyContract, artifact: ContractArtifact, problems: string[]): ReadonlyMap<string, RuntimePurpose> {
|
|
723
761
|
const declared = contract.surface.tokens ?? {}
|
|
724
762
|
const purposes = new Map<string, RuntimePurpose>()
|
|
725
763
|
for (const [purpose, approved] of Object.entries(artifact.tokens ?? {})) {
|
|
726
764
|
const own = Object.hasOwn(declared, purpose) ? declared[purpose] : undefined
|
|
727
|
-
if (own
|
|
728
|
-
|
|
765
|
+
if (own === undefined) {
|
|
766
|
+
continue
|
|
767
|
+
}
|
|
768
|
+
if (!hasShape(own.claims, approved.claims, `token '${purpose}' claims`)) {
|
|
769
|
+
problems.push(unapproved(`token '${purpose}'`, 'claims schema'))
|
|
729
770
|
}
|
|
771
|
+
purposes.set(purpose, { claims: own.claims, maxDays: approved.maxDays })
|
|
730
772
|
}
|
|
731
773
|
return purposes
|
|
732
774
|
}
|
|
733
775
|
|
|
776
|
+
/**
|
|
777
|
+
* A fact the evaluated contract states again, which differs from the approved artifact. Boot reads the artifact the build
|
|
778
|
+
* compiled, so it compares what it still takes from the evaluated contract instead of compiling it.
|
|
779
|
+
*/
|
|
780
|
+
function unapproved(where: string, fact: string): string {
|
|
781
|
+
return `${where}: its ${fact} is not the approved one; this build is not the contract the deploy was approved with`
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
/** Whether two action lists hold the same actions, in any order. */
|
|
785
|
+
function sameActions(left: readonly string[], right: readonly string[]): boolean {
|
|
786
|
+
const sorted = [...right].sort()
|
|
787
|
+
return left.length === right.length && [...left].sort().every((action, index) => action === sorted[index])
|
|
788
|
+
}
|
|
789
|
+
|
|
734
790
|
export function boot(app: ContractImplementation, options: BootOptions): ContractApp {
|
|
735
791
|
const binding: Binding = { release: null }
|
|
736
792
|
try {
|
|
@@ -756,10 +812,11 @@ function bootOnce(app: ContractImplementation, options: BootOptions, binding: Bi
|
|
|
756
812
|
const terminalRpc = options.terminals === undefined ? undefined : platformFacility(options.terminals)
|
|
757
813
|
const workloadTokens = options.workloadTokens === undefined ? undefined : platformFacility(options.workloadTokens)
|
|
758
814
|
const variables = readFramework(options.environment.framework, app.contract.vocabulary.app, problems)
|
|
759
|
-
const artifact =
|
|
760
|
-
|
|
815
|
+
const artifact = options.approvedContract === undefined
|
|
816
|
+
? compiledArtifact(app, options.environment.framework, problems)
|
|
817
|
+
: approvedArtifact(options.approvedContract, options.environment.framework, problems)
|
|
761
818
|
const proxySecret = readProxySecret(options.environment.framework, options.requireProxySecret === true, problems)
|
|
762
|
-
const tokens = new SignedTokens(runtimePurposes(app.contract, artifact), readTokenKeys(options.environment.framework, artifact, problems))
|
|
819
|
+
const tokens = new SignedTokens(runtimePurposes(app.contract, artifact, problems), readTokenKeys(options.environment.framework, artifact, problems))
|
|
763
820
|
const origin = readAppOrigin(options.environment.framework, problems)
|
|
764
821
|
const url = appUrl(artifact, origin)
|
|
765
822
|
const operations = operationsSettings(options.environment.framework, problems)
|
|
@@ -834,6 +891,10 @@ function bootOnce(app: ContractImplementation, options: BootOptions, binding: Bi
|
|
|
834
891
|
endpoints.set(name, { kind: 'health', row })
|
|
835
892
|
}
|
|
836
893
|
} else if (mount.kind === 'spa') {
|
|
894
|
+
const approvedSpa = artifact.mounts[name]
|
|
895
|
+
if (approvedSpa?.kind !== 'spa' || approvedSpa.prefix !== mount.prefix || approvedSpa.dir !== mount.dir) {
|
|
896
|
+
problems.push(unapproved(`mount '${name}'`, 'prefix or directory'))
|
|
897
|
+
}
|
|
837
898
|
const row = rows.get(name)
|
|
838
899
|
const config = configs.get(name)
|
|
839
900
|
if (config !== undefined && isCredentialed(row)) {
|
|
@@ -846,7 +907,14 @@ function bootOnce(app: ContractImplementation, options: BootOptions, binding: Bi
|
|
|
846
907
|
endpoints.set(bare.id, { kind: 'spa-prefix', row: bare, prefix: mount.prefix })
|
|
847
908
|
}
|
|
848
909
|
} else if (mount.kind === 'rpc' || mount.kind === 'link') {
|
|
910
|
+
const approvedMount = artifact.mounts[name]
|
|
911
|
+
if (approvedMount?.kind !== mount.kind || approvedMount.prefix !== mount.prefix) {
|
|
912
|
+
problems.push(unapproved(`mount '${name}'`, 'kind or prefix'))
|
|
913
|
+
}
|
|
849
914
|
if (mount.kind === 'link') {
|
|
915
|
+
if (approvedMount?.kind === 'link' && approvedMount.spa !== mount.spa) {
|
|
916
|
+
problems.push(unapproved(`mount '${name}'`, 'directory'))
|
|
917
|
+
}
|
|
850
918
|
const row = rows.get(name)
|
|
851
919
|
if (row !== undefined) {
|
|
852
920
|
endpoints.set(name, { kind: 'link-spa', row, prefix: mount.prefix, dir: mount.spa })
|
|
@@ -855,6 +923,14 @@ function bootOnce(app: ContractImplementation, options: BootOptions, binding: Bi
|
|
|
855
923
|
for (const { id, path, procedure } of declaredProcedures(name, mount.procedures)) {
|
|
856
924
|
declared.add(id)
|
|
857
925
|
const row = rows.get(id)
|
|
926
|
+
if (isCredentialed(row)) {
|
|
927
|
+
if (row.kind !== procedure.type) {
|
|
928
|
+
problems.push(unapproved(`procedure '${id}'`, `kind (${procedure.type})`))
|
|
929
|
+
}
|
|
930
|
+
if ((procedure.input === null) !== (row.input === null) || (procedure.output === null) !== (row.output === null)) {
|
|
931
|
+
problems.push(unapproved(`procedure '${id}'`, 'input or output'))
|
|
932
|
+
}
|
|
933
|
+
}
|
|
858
934
|
const bound = boundHandler(path.reduce<unknown>(childAt, handlers), id, `procedure '${id}'`, procedure.type, artifact, problems)
|
|
859
935
|
if (row?.kind === 'public') {
|
|
860
936
|
const served = publicEndpoint(row, procedure, bound, artifact, workloads, options, problems)
|
|
@@ -896,7 +972,9 @@ function bootOnce(app: ContractImplementation, options: BootOptions, binding: Bi
|
|
|
896
972
|
const approved = artifact.mounts[name]
|
|
897
973
|
if (row === undefined || bound === null) {
|
|
898
974
|
problems.push(`webhook '${name}' has no handler; add handlers.${name}: ({ input, ctx }) => …`)
|
|
899
|
-
} else if (
|
|
975
|
+
} else if (approved?.kind !== 'webhook' || !sameActions(approved.actions, mount.actions)) {
|
|
976
|
+
problems.push(unapproved(`webhook '${name}'`, 'actions'))
|
|
977
|
+
} else if (credential !== undefined) {
|
|
900
978
|
endpoints.set(name, {
|
|
901
979
|
kind: 'webhook',
|
|
902
980
|
row,
|
|
@@ -904,7 +982,7 @@ function bootOnce(app: ContractImplementation, options: BootOptions, binding: Bi
|
|
|
904
982
|
scheme: approved.scheme,
|
|
905
983
|
boundTo: approved.boundTo,
|
|
906
984
|
timeoutMs: approved.timeoutMs,
|
|
907
|
-
actions:
|
|
985
|
+
actions: approved.actions,
|
|
908
986
|
input: mount.input,
|
|
909
987
|
handler: bound.handler,
|
|
910
988
|
credential,
|