@dads-framework/toolbox 0.5.0 → 0.6.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/README.md +4 -4
- package/dist/cli-migrate-commands.d.ts.map +1 -1
- package/dist/cli-migrate-commands.js +6 -2
- package/dist/cli-migrate-commands.js.map +1 -1
- package/dist/cli-route-inspection-commands.d.ts.map +1 -1
- package/dist/cli-route-inspection-commands.js +8 -4
- package/dist/cli-route-inspection-commands.js.map +1 -1
- package/dist/doctor/doctor-context.d.ts.map +1 -1
- package/dist/doctor/doctor-context.js +17 -22
- package/dist/doctor/doctor-context.js.map +1 -1
- package/dist/doctor/doctor-gate-states.d.ts.map +1 -1
- package/dist/doctor/doctor-gate-states.js +4 -2
- package/dist/doctor/doctor-gate-states.js.map +1 -1
- package/dist/doctor/doctor-gate.js +3 -2
- package/dist/doctor/doctor-gate.js.map +1 -1
- package/dist/doctor/doctor-report.d.ts +2 -0
- package/dist/doctor/doctor-report.d.ts.map +1 -1
- package/dist/doctor/doctor-report.js +10 -1
- package/dist/doctor/doctor-report.js.map +1 -1
- package/dist/doctor/signals/anxious-attachment/kind-inversions.d.ts.map +1 -1
- package/dist/doctor/signals/anxious-attachment/kind-inversions.js +33 -3
- package/dist/doctor/signals/anxious-attachment/kind-inversions.js.map +1 -1
- package/dist/doctor/signals/avoidant-attachment/responses-outside-envelope.d.ts.map +1 -1
- package/dist/doctor/signals/avoidant-attachment/responses-outside-envelope.js +2 -0
- package/dist/doctor/signals/avoidant-attachment/responses-outside-envelope.js.map +1 -1
- package/dist/doctor/signals/avoidant-attachment/routes-without-schema.d.ts.map +1 -1
- package/dist/doctor/signals/avoidant-attachment/routes-without-schema.js +2 -0
- package/dist/doctor/signals/avoidant-attachment/routes-without-schema.js.map +1 -1
- package/dist/doctor/signals/commitment-issues/denial-tests-zero.d.ts.map +1 -1
- package/dist/doctor/signals/commitment-issues/denial-tests-zero.js +23 -3
- package/dist/doctor/signals/commitment-issues/denial-tests-zero.js.map +1 -1
- package/dist/doctor/signals/commitment-issues/mutations-without-ownership.d.ts.map +1 -1
- package/dist/doctor/signals/commitment-issues/mutations-without-ownership.js +12 -1
- package/dist/doctor/signals/commitment-issues/mutations-without-ownership.js.map +1 -1
- package/dist/doctor/signals/commitment-issues/sequential-authz-writes.d.ts.map +1 -1
- package/dist/doctor/signals/commitment-issues/sequential-authz-writes.js +25 -4
- package/dist/doctor/signals/commitment-issues/sequential-authz-writes.js.map +1 -1
- package/dist/doctor/signals/commitment-issues/test-count.d.ts.map +1 -1
- package/dist/doctor/signals/commitment-issues/test-count.js +18 -2
- package/dist/doctor/signals/commitment-issues/test-count.js.map +1 -1
- package/dist/doctor/signals/its-not-you-its-my-boundaries/hooks-not-wired.d.ts.map +1 -1
- package/dist/doctor/signals/its-not-you-its-my-boundaries/hooks-not-wired.js +22 -2
- package/dist/doctor/signals/its-not-you-its-my-boundaries/hooks-not-wired.js.map +1 -1
- package/dist/doctor/signals/its-not-you-its-my-boundaries/rows-sent-whole.d.ts +1 -1
- package/dist/doctor/signals/its-not-you-its-my-boundaries/rows-sent-whole.js +2 -2
- package/dist/doctor/signals/its-not-you-its-my-boundaries/rows-sent-whole.js.map +1 -1
- package/dist/doctor/signals/scanners/git-history.d.ts +7 -1
- package/dist/doctor/signals/scanners/git-history.d.ts.map +1 -1
- package/dist/doctor/signals/scanners/git-history.js +0 -0
- package/dist/doctor/signals/scanners/git-history.js.map +1 -1
- package/dist/doctor/signals/scanners/package-graph.d.ts.map +1 -1
- package/dist/doctor/signals/scanners/package-graph.js +34 -8
- package/dist/doctor/signals/scanners/package-graph.js.map +1 -1
- package/dist/doctor/signals/scanners/route-model.d.ts.map +1 -1
- package/dist/doctor/signals/scanners/route-model.js +11 -1
- package/dist/doctor/signals/scanners/route-model.js.map +1 -1
- package/dist/doctor/signals/the-paper-wall/provider-chosen-outside-root.js +1 -1
- package/dist/doctor/signals/the-paper-wall/provider-chosen-outside-root.js.map +1 -1
- package/dist/doctor/signals/you-are-looking-for-a-father-figure/framework-in-core.d.ts.map +1 -1
- package/dist/doctor/signals/you-are-looking-for-a-father-figure/framework-in-core.js +13 -3
- package/dist/doctor/signals/you-are-looking-for-a-father-figure/framework-in-core.js.map +1 -1
- package/dist/doctor/signals/you-are-looking-for-a-father-figure/vendor-named-domain.js +1 -1
- package/dist/doctor/signals/you-are-looking-for-a-father-figure/vendor-named-domain.js.map +1 -1
- package/dist/domain-boundaries/check-domain-boundaries.d.ts.map +1 -1
- package/dist/domain-boundaries/check-domain-boundaries.js +32 -19
- package/dist/domain-boundaries/check-domain-boundaries.js.map +1 -1
- package/dist/initialize-dads-project.js +2 -1
- package/dist/initialize-dads-project.js.map +1 -1
- package/dist/migrate-v03.d.ts +1 -1
- package/dist/migrate-v03.d.ts.map +1 -1
- package/dist/migrate-v03.js +4 -1
- package/dist/migrate-v03.js.map +1 -1
- package/dist/route-inspection/read-route-source.d.ts +6 -1
- package/dist/route-inspection/read-route-source.d.ts.map +1 -1
- package/dist/route-inspection/read-route-source.js +51 -26
- package/dist/route-inspection/read-route-source.js.map +1 -1
- package/dist/route-inspection/resolve-route-references.d.ts +20 -0
- package/dist/route-inspection/resolve-route-references.d.ts.map +1 -0
- package/dist/route-inspection/resolve-route-references.js +255 -0
- package/dist/route-inspection/resolve-route-references.js.map +1 -0
- package/dist/route-inspection/route-source-facts.d.ts +1 -0
- package/dist/route-inspection/route-source-facts.d.ts.map +1 -1
- package/dist/route-inspection/route-source-facts.js.map +1 -1
- package/dist/starter-project/kit-starter.generated.d.ts.map +1 -1
- package/dist/starter-project/kit-starter.generated.js +9 -6
- package/dist/starter-project/kit-starter.generated.js.map +1 -1
- package/dist/starter-project/minimal-project-server.js +2 -2
- package/dist/starter-project/minimal-project-workbench.js +9 -0
- package/dist/starter-project/minimal-project-workbench.js.map +1 -1
- package/dist/starter-project/render-minimal-project.js +2 -2
- package/dist/starter-project/render-minimal-project.js.map +1 -1
- package/dist/starter-project/render-starter-project.d.ts.map +1 -1
- package/dist/starter-project/render-starter-project.js +24 -9
- package/dist/starter-project/render-starter-project.js.map +1 -1
- package/dist/starter-project/render-starter-verification-files.d.ts +1 -0
- package/dist/starter-project/render-starter-verification-files.d.ts.map +1 -1
- package/dist/starter-project/render-starter-verification-files.js +22 -0
- package/dist/starter-project/render-starter-verification-files.js.map +1 -1
- package/dist/toolbox.tsbuildinfo +1 -1
- package/package.json +3 -3
- package/dist/access-ir-lowering.d.ts +0 -8
- package/dist/access-ir-lowering.d.ts.map +0 -1
- package/dist/access-ir-lowering.js +0 -108
- package/dist/access-ir-lowering.js.map +0 -1
|
@@ -52,18 +52,21 @@ export const kitStarterFiles = [
|
|
|
52
52
|
{ path: "assembly/read-local-mail.mjs", content: "import { readdir, readFile, stat } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport process from \"node:process\";\nimport { z } from \"zod\";\n\nconst envelope = z.object({\n to: z.array(z.object({ address: z.string() })),\n subject: z.string(),\n text: z.string(),\n});\n\nconst spool = process.env[\"DADS_MAIL_SPOOL_DIR\"];\nif (!spool) throw new Error(\"The local mail spool is unavailable.\");\n\nasync function mailEntries(directory) {\n try {\n return await readdir(directory, { withFileTypes: true });\n } catch (fault) {\n if (typeof fault === \"object\" && fault !== null && \"code\" in fault && fault.code === \"ENOENT\") return [];\n throw fault;\n }\n}\n\nasync function readLatestMail(directory) {\n const entries = await mailEntries(directory);\n const files = entries.filter((entry) => entry.isFile() && entry.name.endsWith(\".json\"));\n const ordered = await Promise.all(\n files.map(async ({ name }) => {\n const path = join(directory, name);\n return { path, updated: (await stat(path)).mtimeMs };\n }),\n );\n ordered.sort((left, right) => right.updated - left.updated);\n return Promise.all(\n ordered.slice(0, 20).map(async ({ path }) => envelope.parse(JSON.parse(await readFile(path, \"utf8\")))),\n );\n}\n\nconst mail = await readLatestMail(spool);\nif (process.argv.includes(\"--json\")) {\n process.stdout.write(JSON.stringify({ ok: true, mail }) + \"\\n\");\n} else if (mail.length === 0) {\n process.stdout.write(\"No mail has been delivered yet.\\n\");\n} else {\n process.stdout.write(\n mail\n .map(\n ({ to, subject, text }) => `To: ${to.map(({ address }) => address).join(\", \")}\\nSubject: ${subject}\\n\\n${text}`,\n )\n .join(\"\\n\\n\") + \"\\n\",\n );\n}\n" },
|
|
53
53
|
{ path: "assembly/scim-binding-route.test.ts", content: "import { relationshipWrite } from \"@dads-framework/access/runtime\";\nimport { FakeAuthorization } from \"@dads-framework/access/testing\";\nimport { buildTestApp } from \"@dads-framework/http/testing\";\nimport { TenantUnavailableError } from \"@dads-framework/identity/tenants\";\nimport { expect, it, vi } from \"vitest\";\n\nimport { sessionSubjects } from \"./session-subjects.js\";\nimport { scimBindingRoutes } from \"../domains/tenants/index.js\";\nimport { account, tenantAccess } from \"../libraries/app-runtime/index.js\";\n\nconst origin = \"http://127.0.0.1:3000\";\nconst alpha = \"00000000-0000-4000-8000-000000000001\";\nconst beta = \"00000000-0000-4000-8000-000000000002\";\nconst scimId = \"00000000-0000-4000-8000-000000000003\";\nconst owner = { type: account.wireName, id: \"owner\" };\nconst member = { type: account.wireName, id: \"member\" };\nconst permission = tenantAccess.tenant.permissions.manage_tenant;\n\nit(\"binds an existing member only for an owner of an enabled tenant\", async () => {\n const bindScimUser = vi\n .fn<Parameters<typeof scimBindingRoutes>[0][\"bindScimUser\"]>()\n .mockImplementation((_actor, _tenant, _scimUser, account) =>\n account === member.id ? Promise.resolve() : Promise.reject(new TenantUnavailableError()),\n );\n const auth = new FakeAuthorization({\n [permission.entityWireName]: { [permission.permissionName]: [\"owner\"] },\n });\n for (const tenantId of [alpha, beta]) {\n auth.seed(relationshipWrite({ type: permission.entityWireName, id: tenantId }, \"owner\", owner));\n auth.seed(relationshipWrite({ type: permission.entityWireName, id: tenantId }, \"member\", member));\n }\n\n const readSession = vi.fn((headers: Headers) => {\n const cookie = headers.get(\"cookie\");\n if (cookie === null) return Promise.resolve(null);\n const id = cookie === \"password-owner\" ? owner.id : cookie;\n return Promise.resolve({\n account: { id, email: `${id}@example.test`, emailVerified: true },\n expiresAt: new Date(\"2099-01-01\"),\n });\n });\n const readTenantSession = vi.fn((headers: Headers, tenantId: string) =>\n tenantId === alpha && headers.get(\"cookie\") === \"password-owner\" ? Promise.resolve(null) : readSession(headers),\n );\n const app = await buildTestApp({\n routes: scimBindingRoutes({ bindScimUser }, origin, [alpha]),\n subjects: sessionSubjects(\n { handle: () => Promise.resolve(new Response(null)), readSession },\n { readTenantSession },\n ),\n authorization: auth,\n });\n\n const bind = (tenant: string, cookie?: string, requestOrigin = origin, accountId = member.id) =>\n app.inject({\n method: \"POST\",\n url: `/tenants/${tenant}/scim/users/${scimId}/bind`,\n headers: {\n origin: requestOrigin,\n ...(cookie === undefined ? {} : { cookie }),\n },\n payload: { accountId },\n });\n\n try {\n expect((await bind(alpha)).statusCode).toBe(401);\n expect((await bind(alpha, \"member\")).statusCode).toBe(404);\n expect((await bind(alpha, \"password-owner\")).statusCode).toBe(401);\n expect(readTenantSession).toHaveBeenCalledWith(expect.any(Headers), alpha);\n expect((await bind(beta, \"owner\")).statusCode).toBe(404);\n expect((await bind(alpha, \"owner\", \"https://elsewhere.example.test\")).statusCode).toBe(403);\n expect(bindScimUser).not.toHaveBeenCalled();\n expect((await bind(alpha, \"owner\", origin, \"unavailable\")).statusCode).toBe(404);\n expect((await bind(alpha, \"owner\")).statusCode).toBe(204);\n expect(bindScimUser).toHaveBeenLastCalledWith(owner.id, alpha, scimId, member.id);\n } finally {\n await app.close();\n }\n});\n" },
|
|
54
54
|
{ path: "assembly/scim.ts", content: "import { createHash, timingSafeEqual } from \"node:crypto\";\nimport { createScimHandler } from \"@dads-framework/identity/scim\";\nimport {\n createTenantScimDirectory,\n createTenantScimGroupDirectory,\n tenantIdSchema,\n type TenantsOptions,\n} from \"@dads-framework/identity/tenants\";\n\nimport type { ScimConfiguration } from \"./enterprise-config.js\";\n\nexport function configureScim(baseUrl: string, configs: readonly ScimConfiguration[], tenants: TenantsOptions) {\n if (configs.length === 0) throw new Error(\"Configure at least one SCIM credential.\");\n const digests = new Set<string>();\n const credentials = configs.map(({ tokenSha256, tenantId }) => {\n if (!/^[a-f0-9]{64}$/u.test(tokenSha256)) throw new Error(\"SCIM requires a SHA-256 bearer credential digest.\");\n if (digests.has(tokenSha256)) throw new Error(\"SCIM credential digests must be unique.\");\n digests.add(tokenSha256);\n return {\n digest: Buffer.from(tokenSha256, \"hex\"),\n tenantId: tenantIdSchema.parse(tenantId.toLowerCase()),\n };\n });\n return createScimHandler({\n baseUrl: new URL(\"/scim/v2\", baseUrl).href,\n directory: createTenantScimDirectory(tenants),\n groups: createTenantScimGroupDirectory(tenants),\n authenticate: (token) => {\n const actual = createHash(\"sha256\").update(token).digest();\n let tenantId: string | null = null;\n for (const credential of credentials) {\n if (timingSafeEqual(actual, credential.digest)) tenantId = credential.tenantId;\n }\n return Promise.resolve(tenantId);\n },\n });\n}\n" },
|
|
55
|
-
{ path: "assembly/services.ts", content: "import type { AccessModel } from \"@dads-framework/access\";\nimport { currentAuditActor } from \"@dads-framework/core/audit-actor\";\nimport { GetEffectiveFeatureState, type FeatureFlagDefinition } from \"@dads-framework/feature-flags\";\nimport { readFeatureFlagPreview } from \"@dads-framework/feature-flags/http\";\nimport { DrizzleFeatureFlagStore } from \"@dads-framework/feature-flags/postgres\";\nimport { definePlugin, providePlugin, type PluginScope, type Service } from \"@dads-framework/core/plugin\";\nimport { createPostgresConnection } from \"@dads-framework/postgres\";\nimport {\n PostgresAuthorization,\n preparePostgresChecks,\n TransactionalAccessChanges,\n} from \"@dads-framework/postgres-access\";\nimport { Tenants, type TenantsOptions } from \"@dads-framework/identity/tenants\";\n\nimport {\n databaseService,\n featureFlagsService,\n jobQueueService,\n objectStorageService,\n protectedWriteService,\n starterServices,\n tenantAccess,\n type StarterServices,\n type EnqueueStarterEmail,\n} from \"../libraries/app-runtime/index.js\";\n\nimport { createLocalMail, openLocalServices } from \"./local-services.js\";\nimport { createProtectedWrite } from \"./protected-write.js\";\nimport { openIdentityServices } from \"./identity-services.js\";\nimport type { FeaturePreviewConfiguration } from \"./feature-previews.js\";\nimport type { EnterpriseConfiguration } from \"./enterprise-config.js\";\nimport { openStaffImpersonationServices, type StaffImpersonationServices } from \"./staff-impersonation-services.js\";\n\nexport type HostServices = StarterServices &\n Awaited<ReturnType<typeof openIdentityServices>> &\n StaffImpersonationServices & {\n readonly authorization: PostgresAuthorization;\n readonly local: ReturnType<typeof openLocalServices>;\n readonly mailJobs: ReturnType<typeof createLocalMail>[\"jobs\"];\n };\n\nexport function provideServices(create: (scope: PluginScope) => Promise<HostServices>) {\n return providePlugin(\"host-services\", starterServices, create);\n}\n\nfunction projectCapability<const Name extends string, ServiceName extends string, Value>(\n name: Name,\n service: Service<ServiceName, Value>,\n select: (services: StarterServices) => Value,\n) {\n return definePlugin<Name, readonly [typeof starterServices], Value, never, never, never, ServiceName>({\n name,\n requires: [starterServices],\n implements: service,\n setup: ({ use }) => ({ provides: select(use(starterServices)) }),\n });\n}\n\nexport const capabilityServices = [\n projectCapability(\"database-capability\", databaseService, ({ db }) => db),\n projectCapability(\"feature-flags-capability\", featureFlagsService, ({ flags }) => flags),\n projectCapability(\"object-storage-capability\", objectStorageService, ({ files }) => files),\n projectCapability(\"job-queue-capability\", jobQueueService, ({ jobs }) => jobs),\n projectCapability(\n \"protected-write-capability\",\n protectedWriteService,\n ({ writeWithPermission }) => writeWithPermission,\n ),\n];\n\nexport type ServiceProvider = ReturnType<typeof provideServices>;\n\nexport type ServiceConfiguration = {\n readonly databaseUrl: string;\n readonly baseUrl: string;\n readonly secret: string;\n readonly enterprise?: EnterpriseConfiguration;\n readonly featurePreview?: FeaturePreviewConfiguration;\n readonly preparePermissionChecks?: boolean;\n readonly enqueueEmail?: EnqueueStarterEmail;\n readonly fileStorageDirectory?: string;\n readonly mailSpoolDirectory?: string;\n};\n\nexport async function openServices(\n scope: PluginScope,\n config: ServiceConfiguration,\n model: AccessModel,\n definitions: readonly FeatureFlagDefinition[],\n enableStaffImpersonation = false,\n) {\n const connection = openDatabase(scope, config.databaseUrl);\n const local = openLocalServices(scope, config, connection.drizzle);\n const mail =\n config.mailSpoolDirectory === undefined\n ? undefined\n : createLocalMail(connection.drizzle, local.queue, config.mailSpoolDirectory);\n const enqueueEmail = config.enqueueEmail ?? mail?.enqueueEmail;\n if (enqueueEmail === undefined) throw new Error(\"Configure an email sender before starting the app.\");\n const authorization = new PostgresAuthorization({\n model,\n namespace: \"starter\",\n executor: config.preparePermissionChecks ? preparePostgresChecks(connection.pool) : connection.pool,\n });\n const tenantOptions: TenantsOptions = {\n database: connection.drizzle,\n access: tenantAccess,\n authorizationAt: (tx) => authorization.inDrizzleTransaction(tx),\n changes: new TransactionalAccessChanges(authorization, connection.drizzle),\n };\n const tenants = new Tenants(tenantOptions);\n const identity = await openIdentityServices(\n {\n database: connection,\n baseUrl: config.baseUrl,\n secret: config.secret,\n enqueueEmail,\n canInvite: () => Promise.resolve(false),\n },\n config.enterprise,\n tenantOptions,\n );\n return {\n db: connection.drizzle,\n local,\n mailJobs: mail?.jobs ?? [],\n files: local.storage,\n jobs: local.queue,\n writeWithPermission: createProtectedWrite(connection.drizzle, authorization),\n tenants,\n ...identity,\n ...(enableStaffImpersonation\n ? openStaffImpersonationServices(connection.pool, config, identity, tenants)\n : { staffImpersonation: undefined }),\n invitationOrigin: new URL(config.baseUrl).origin,\n enqueueTenantInvitation: tenantInvitationMailer(config.baseUrl, enqueueEmail),\n authorization,\n flags: new GetEffectiveFeatureState(\n definitions,\n new DrizzleFeatureFlagStore(connection.drizzle),\n readFeatureFlagPreview,\n ),\n };\n}\n\nfunction openDatabase(scope: PluginScope, connectionString: string) {\n const connection = createPostgresConnection(\n { schema: {}, connectionString, auditActorSource: currentAuditActor },\n {\n error: (_fault, message) => {\n process.stderr.write(\n `${message ?? \"Could not close the database connection.\"}\n`,\n );\n },\n },\n );\n scope.onDispose(connection.close);\n return connection;\n}\n\nfunction tenantInvitationMailer(\n baseUrl: string,\n enqueueEmail: EnqueueStarterEmail,\n): StarterServices[\"enqueueTenantInvitation\"] {\n return (email, token) => {\n const url = new URL(\"/accept-tenant-invitation\", baseUrl);\n url.hash = new URLSearchParams({ token }).toString();\n return enqueueEmail({\n kind: \"tenant-invitation\",\n to: email,\n url: url.href,\n });\n };\n}\n" },
|
|
55
|
+
{ path: "assembly/services.ts", content: "import type { AccessModel } from \"@dads-framework/access\";\nimport { DrizzleAuditLogReader } from \"@dads-framework/audit\";\nimport { currentAuditActor } from \"@dads-framework/core/audit-actor\";\nimport { GetEffectiveFeatureState, type FeatureFlagDefinition } from \"@dads-framework/feature-flags\";\nimport { readFeatureFlagPreview } from \"@dads-framework/feature-flags/http\";\nimport { DrizzleFeatureFlagStore } from \"@dads-framework/feature-flags/postgres\";\nimport { definePlugin, providePlugin, type PluginScope, type Service } from \"@dads-framework/core/plugin\";\nimport { createPostgresConnection } from \"@dads-framework/postgres\";\nimport {\n PostgresAuthorization,\n preparePostgresChecks,\n TransactionalAccessChanges,\n} from \"@dads-framework/postgres-access\";\nimport { Tenants, type TenantsOptions } from \"@dads-framework/identity/tenants\";\n\nimport {\n databaseService,\n featureFlagsService,\n jobQueueService,\n objectStorageService,\n protectedWriteService,\n starterServices,\n tenantAccess,\n type StarterServices,\n type EnqueueStarterEmail,\n} from \"../libraries/app-runtime/index.js\";\n\nimport { createLocalMail, openLocalServices } from \"./local-services.js\";\nimport { createProtectedWrite } from \"./protected-write.js\";\nimport { openIdentityServices } from \"./identity-services.js\";\nimport type { FeaturePreviewConfiguration } from \"./feature-previews.js\";\nimport type { EnterpriseConfiguration } from \"./enterprise-config.js\";\nimport { openStaffImpersonationServices, type StaffImpersonationServices } from \"./staff-impersonation-services.js\";\n\nexport type HostServices = StarterServices &\n Awaited<ReturnType<typeof openIdentityServices>> &\n StaffImpersonationServices & {\n readonly authorization: PostgresAuthorization;\n readonly local: ReturnType<typeof openLocalServices>;\n readonly mailJobs: ReturnType<typeof createLocalMail>[\"jobs\"];\n };\n\nexport function provideServices(create: (scope: PluginScope) => Promise<HostServices>) {\n return providePlugin(\"host-services\", starterServices, create);\n}\n\nfunction projectCapability<const Name extends string, ServiceName extends string, Value>(\n name: Name,\n service: Service<ServiceName, Value>,\n select: (services: StarterServices) => Value,\n) {\n return definePlugin<Name, readonly [typeof starterServices], Value, never, never, never, ServiceName>({\n name,\n requires: [starterServices],\n implements: service,\n setup: ({ use }) => ({ provides: select(use(starterServices)) }),\n });\n}\n\nexport const capabilityServices = [\n projectCapability(\"database-capability\", databaseService, ({ db }) => db),\n projectCapability(\"feature-flags-capability\", featureFlagsService, ({ flags }) => flags),\n projectCapability(\"object-storage-capability\", objectStorageService, ({ files }) => files),\n projectCapability(\"job-queue-capability\", jobQueueService, ({ jobs }) => jobs),\n projectCapability(\n \"protected-write-capability\",\n protectedWriteService,\n ({ writeWithPermission }) => writeWithPermission,\n ),\n];\n\nexport type ServiceProvider = ReturnType<typeof provideServices>;\n\nexport type ServiceConfiguration = {\n readonly databaseUrl: string;\n readonly baseUrl: string;\n readonly secret: string;\n readonly enterprise?: EnterpriseConfiguration;\n readonly featurePreview?: FeaturePreviewConfiguration;\n readonly preparePermissionChecks?: boolean;\n readonly enqueueEmail?: EnqueueStarterEmail;\n readonly fileStorageDirectory?: string;\n readonly mailSpoolDirectory?: string;\n};\n\nexport async function openServices(\n scope: PluginScope,\n config: ServiceConfiguration,\n model: AccessModel,\n definitions: readonly FeatureFlagDefinition[],\n enableStaffImpersonation = false,\n) {\n const connection = openDatabase(scope, config.databaseUrl);\n const local = openLocalServices(scope, config, connection.drizzle);\n const mail =\n config.mailSpoolDirectory === undefined\n ? undefined\n : createLocalMail(connection.drizzle, local.queue, config.mailSpoolDirectory);\n const enqueueEmail = config.enqueueEmail ?? mail?.enqueueEmail;\n if (enqueueEmail === undefined) throw new Error(\"Configure an email sender before starting the app.\");\n const authorization = new PostgresAuthorization({\n model,\n namespace: \"starter\",\n executor: config.preparePermissionChecks ? preparePostgresChecks(connection.pool) : connection.pool,\n });\n const tenantOptions: TenantsOptions = {\n database: connection.drizzle,\n access: tenantAccess,\n authorizationAt: (tx) => authorization.inDrizzleTransaction(tx),\n changes: new TransactionalAccessChanges(authorization, connection.drizzle),\n };\n const tenants = new Tenants(tenantOptions);\n const identity = await openIdentityServices(\n {\n database: connection,\n baseUrl: config.baseUrl,\n secret: config.secret,\n enqueueEmail,\n canInvite: () => Promise.resolve(false),\n },\n config.enterprise,\n tenantOptions,\n );\n return {\n db: connection.drizzle,\n auditLogReader: new DrizzleAuditLogReader(connection.drizzle),\n local,\n mailJobs: mail?.jobs ?? [],\n files: local.storage,\n jobs: local.queue,\n writeWithPermission: createProtectedWrite(connection.drizzle, authorization),\n tenants,\n ...identity,\n ...(enableStaffImpersonation\n ? openStaffImpersonationServices(connection.pool, config, identity, tenants)\n : { staffImpersonation: undefined }),\n invitationOrigin: new URL(config.baseUrl).origin,\n enqueueTenantInvitation: tenantInvitationMailer(config.baseUrl, enqueueEmail),\n authorization,\n flags: new GetEffectiveFeatureState(\n definitions,\n new DrizzleFeatureFlagStore(connection.drizzle),\n readFeatureFlagPreview,\n ),\n };\n}\n\nfunction openDatabase(scope: PluginScope, connectionString: string) {\n const connection = createPostgresConnection(\n { schema: {}, connectionString, auditActorSource: currentAuditActor },\n {\n error: (_fault, message) => {\n process.stderr.write(\n `${message ?? \"Could not close the database connection.\"}\n`,\n );\n },\n },\n );\n scope.onDispose(connection.close);\n return connection;\n}\n\nfunction tenantInvitationMailer(\n baseUrl: string,\n enqueueEmail: EnqueueStarterEmail,\n): StarterServices[\"enqueueTenantInvitation\"] {\n return (email, token) => {\n const url = new URL(\"/accept-tenant-invitation\", baseUrl);\n url.hash = new URLSearchParams({ token }).toString();\n return enqueueEmail({\n kind: \"tenant-invitation\",\n to: email,\n url: url.href,\n });\n };\n}\n" },
|
|
56
56
|
{ path: "assembly/session-subjects.ts", content: "import type { SubjectResolver } from \"@dads-framework/http\";\nimport type { Identity } from \"@dads-framework/identity\";\nimport type { EnterpriseBetterAuthIdentity } from \"@dads-framework/identity/better-auth\";\nimport { tenantIdSchema } from \"@dads-framework/identity/tenants\";\n\nimport { account } from \"../libraries/app-runtime/index.js\";\n\nexport function sessionSubjects(\n identity: Identity,\n enterprise?: Pick<EnterpriseBetterAuthIdentity, \"readTenantSession\">,\n): SubjectResolver {\n return {\n async resolve({ headers, params }) {\n const normalized = new Headers();\n for (const [name, header] of Object.entries(headers)) {\n if (typeof header === \"string\") normalized.set(name, header);\n }\n const tenantId = tenantFromParams(params);\n if (tenantId === null) return null;\n const session =\n enterprise !== undefined && tenantId !== undefined\n ? await enterprise.readTenantSession(normalized, tenantId)\n : await identity.readSession(normalized);\n return session === null ? null : { type: account.wireName, id: session.account.id };\n },\n };\n}\n\n/** Undefined is unscoped. Null means the matched tenant parameter is invalid. */\nexport function tenantFromParams(params: unknown): string | null | undefined {\n if (typeof params !== \"object\" || params === null || !(\"tenantId\" in params)) return undefined;\n const tenant = tenantIdSchema.safeParse(params.tenantId);\n return tenant.success ? tenant.data.toLowerCase() : null;\n}\n" },
|
|
57
57
|
{ path: "assembly/sign-in-options-route.ts", content: "import { getRoute, routeGroup } from \"@dads-framework/http\";\nimport { signInOptions, signInOptionsRoute } from \"../libraries/sign-in-options/index.js\";\n\nexport function createSignInOptionsRoutes(enterpriseSso: boolean) {\n return routeGroup(\"Sign-in\", [\n getRoute({\n route: signInOptionsRoute,\n summary: \"Read the sign-in methods available on this API\",\n access: { kind: \"public\" },\n response: signInOptions,\n handler: () => ({ enterpriseSso }),\n }),\n ]);\n}\n" },
|
|
58
58
|
{ path: "assembly/staff-impersonation-services.ts", content: "import type { Identity } from \"@dads-framework/identity\";\nimport { createImpersonation, type ImpersonationOptions } from \"@dads-framework/identity/impersonation\";\nimport type { EnterpriseBetterAuthIdentity } from \"@dads-framework/identity/better-auth\";\nimport { createPostgresImpersonationStore } from \"@dads-framework/identity/better-auth/impersonation-store\";\nimport type { createPostgresConnection } from \"@dads-framework/postgres\";\nimport type { Tenants } from \"@dads-framework/identity/tenants\";\n\nimport {\n configureStaffImpersonation,\n readTenantAsTarget,\n staffImpersonationConfiguration,\n type StaffImpersonationConfiguration,\n} from \"../domains/support/index.js\";\nimport type { ServiceConfiguration } from \"./services.js\";\n\nexport type StaffImpersonationServices = {\n readonly staffImpersonation: ReturnType<typeof configureStaffImpersonation> | undefined;\n};\n\nexport function openStaffImpersonationServices(\n pool: ReturnType<typeof createPostgresConnection>[\"pool\"],\n config: ServiceConfiguration,\n {\n identity,\n enterpriseIdentity,\n }: {\n readonly identity: Identity;\n readonly enterpriseIdentity: EnterpriseBetterAuthIdentity | undefined;\n },\n tenants: Tenants,\n): StaffImpersonationServices {\n if (config.enterprise?.staffImpersonation === undefined) return { staffImpersonation: undefined };\n const configuration = staffImpersonationConfiguration.parse(config.enterprise.staffImpersonation);\n const { tenantId } = configuration;\n const persistence = createPostgresImpersonationStore(pool);\n const impersonation = createImpersonation({\n ...persistence,\n store: {\n ...persistence.store,\n async read(id) {\n const stored = await persistence.store.read(id);\n return stored?.tenantId === tenantId ? stored : null;\n },\n },\n identity:\n enterpriseIdentity === undefined\n ? identity\n : {\n readSession: (headers) => enterpriseIdentity.readTenantSession(headers, tenantId),\n },\n lifetimeMs: 5 * 60 * 1000,\n authorize: staffSupportPolicy(configuration, tenants),\n });\n return {\n staffImpersonation: configureStaffImpersonation({\n baseUrl: config.baseUrl,\n tenantId,\n impersonation,\n tenants,\n }),\n };\n}\n\nfunction staffSupportPolicy(\n { tenantId, staffAccountIds, revokerAccountIds }: StaffImpersonationConfiguration,\n tenants: Tenants,\n): ImpersonationOptions[\"authorize\"] {\n const staff = new Set(staffAccountIds);\n const revokers = new Set(revokerAccountIds);\n return async (scope) => {\n if (scope.tenantId !== tenantId) return false;\n if (scope.action === \"revoke\") return revokers.has(scope.actorAccountId);\n if (!staff.has(scope.actorAccountId)) return false;\n return (await readTenantAsTarget(tenants, scope.effectiveAccountId, tenantId)) !== null;\n };\n}\n" },
|
|
59
59
|
{ path: "assembly/start-app.ts", content: "import { compileAccess } from \"@dads-framework/access\";\nimport { anonymousActor } from \"@dads-framework/core/audit-actor\";\nimport { startHttpHost, type HttpProtocolMount } from \"@dads-framework/http\";\nimport type { TelemetryRuntime } from \"@dads-framework/http/telemetry\";\nimport { IDENTITY_PATH } from \"@dads-framework/identity/better-auth\";\nimport { sql } from \"drizzle-orm\";\n\nimport { scimBindingRoutes } from \"../domains/tenants/index.js\";\nimport { tenantAccess } from \"../libraries/app-runtime/index.js\";\nimport { apiEntrypoints, type ApiName } from \"./api-entrypoints.js\";\nimport { configureFeaturePreviews } from \"./feature-previews.js\";\nimport { openServices, provideServices, type HostServices, type ServiceConfiguration } from \"./services.js\";\nimport { sessionSubjects } from \"./session-subjects.js\";\nimport { createSignInOptionsRoutes } from \"./sign-in-options-route.js\";\n\nexport async function startApp(name: ApiName, config: ServiceConfiguration, telemetry?: TelemetryRuntime) {\n const provider = provideServices((scope) => openServices(scope, config, model, composed.flags, name === \"staff\"));\n const composed = apiEntrypoints[name](provider);\n const model = compileAccess(composed.access, { allowLookupResourcesOn: [tenantAccess.tenant] });\n const running = await composed.start();\n try {\n const services = running.read(provider);\n const { authorization, identity, enterpriseIdentity, scimHandler, tenants, invitationOrigin, db, flags, local } =\n services;\n const featureState =\n name === \"customer\" && config.featurePreview !== undefined\n ? configureFeaturePreviews({\n configuration: config.featurePreview,\n definitions: composed.flags,\n flags,\n authorization,\n })\n : undefined;\n await local.prepareFiles();\n local.queue.register([...services.mailJobs, ...running.jobs]);\n await local.queue.start();\n const scimRoutes =\n name === \"customer\" && scimHandler !== undefined\n ? scimBindingRoutes(tenants, invitationOrigin, config.enterprise?.scim?.map(({ tenantId }) => tenantId) ?? [])\n : [];\n return await startHttpHost({\n baseUrl: config.baseUrl,\n diagnostics: local.diagnostics,\n requestLog: () => local.requestLog,\n ...(telemetry === undefined ? {} : { telemetry }),\n mounts: buildProtocolMounts(name, services),\n health: {\n pingDatabase: async () => {\n await db.execute(sql`select 1`);\n },\n pingCriticalServices: async () => {\n await Promise.all([local.queue.inspect(), local.checkFiles()]);\n },\n },\n routes: [...running.routes, ...scimRoutes, ...createSignInOptionsRoutes(enterpriseIdentity !== undefined)],\n accessModel: model,\n subjects: sessionSubjects(identity, enterpriseIdentity),\n authorization,\n ...(featureState === undefined ? {} : { featureState }),\n auditActorForSubject: ({ subject, requestId }) =>\n subject === null ? anonymousActor(requestId) : { kind: \"account\", id: subject.id, requestId },\n onClose: () => running.stop(),\n });\n } catch (fault) {\n await running.stop();\n throw fault;\n }\n}\n\nfunction buildProtocolMounts(\n name: ApiName,\n services: Pick<HostServices, \"identity\" | \"scimHandler\" | \"staffImpersonation\">,\n): readonly HttpProtocolMount[] {\n const mounts: HttpProtocolMount[] = [{ prefix: IDENTITY_PATH, handler: services.identity.handle }];\n if (name === \"customer\" && services.scimHandler !== undefined) {\n mounts.push({\n prefix: \"/scim/v2\",\n handler: services.scimHandler,\n options: { methods: [\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"] },\n });\n }\n if (name === \"staff\" && services.staffImpersonation !== undefined) {\n mounts.push({\n prefix: \"/api/staff/impersonation\",\n handler: services.staffImpersonation,\n options: { methods: [\"POST\"], servePrefixRoot: true, bodyLimitBytes: 1024 },\n });\n }\n return mounts;\n}\n" },
|
|
60
|
-
{ path: "dads.project.json", content: "{\n \"schemaVersion\": 1,\n \"packages\": [\n {\n \"name\": \"starter-app\",\n \"root\": \"apps\",\n \"kind\": \"application\",\n \"responsibility\": \"Selects domain routes for each named API.\",\n \"allowedDependencies\": [\n \"@dads-framework/access\",\n \"@dads-framework/audit\",\n \"@dads-framework/client\",\n \"@dads-framework/core\",\n \"@dads-framework/feature-flags\",\n \"@dads-framework/http\",\n \"@dads-framework/identity\",\n \"@dads-framework/postgres\",\n \"@dads-framework/postgres-access\",\n \"@dads-framework/ui\",\n \"drizzle-orm\",\n \"node-pg-migrate\",\n \"react\",\n \"react-dom\",\n \"tsx\",\n \"zod\"\n ],\n \"verification\": [\"npm run verify\"],\n \"skills\": []\n },\n {\n \"name\": \"assembly\",\n \"root\": \"assembly\",\n \"kind\": \"
|
|
60
|
+
{ path: "dads.project.json", content: "{\n \"schemaVersion\": 1,\n \"packages\": [\n {\n \"name\": \"starter-app\",\n \"root\": \"apps\",\n \"kind\": \"application\",\n \"responsibility\": \"Selects domain routes for each named API.\",\n \"allowedDependencies\": [\n \"@dads-framework/access\",\n \"@dads-framework/audit\",\n \"@dads-framework/client\",\n \"@dads-framework/core\",\n \"@dads-framework/feature-flags\",\n \"@dads-framework/http\",\n \"@dads-framework/identity\",\n \"@dads-framework/postgres\",\n \"@dads-framework/postgres-access\",\n \"@dads-framework/ui\",\n \"drizzle-orm\",\n \"node-pg-migrate\",\n \"react\",\n \"react-dom\",\n \"tsx\",\n \"zod\"\n ],\n \"verification\": [\"npm run verify\"],\n \"skills\": []\n },\n {\n \"name\": \"assembly\",\n \"root\": \"assembly\",\n \"kind\": \"composition\",\n \"responsibility\": \"Builds the runtime and applies registered migrations.\",\n \"allowedDependencies\": [\n \"@dads-framework/access\",\n \"@dads-framework/audit\",\n \"@dads-framework/core\",\n \"@dads-framework/documents\",\n \"@dads-framework/email\",\n \"@dads-framework/feature-flags\",\n \"@dads-framework/http\",\n \"@dads-framework/identity\",\n \"@dads-framework/job-queue\",\n \"@dads-framework/object-storage\",\n \"@dads-framework/postgres\",\n \"@dads-framework/postgres-access\",\n \"@dads-framework/ui\",\n \"drizzle-orm\",\n \"marked\",\n \"node-pg-migrate\",\n \"react\",\n \"tsx\",\n \"vite\",\n \"zod\"\n ],\n \"verification\": [\"npm run verify\"],\n \"skills\": []\n },\n {\n \"name\": \"domains-notes\",\n \"root\": \"domains/notes\",\n \"kind\": \"core\",\n \"responsibility\": \"Owns the notes contracts and routes.\",\n \"allowedDependencies\": [\n \"@dads-framework/access\",\n \"@dads-framework/audit\",\n \"@dads-framework/client\",\n \"@dads-framework/core\",\n \"@dads-framework/documents\",\n \"@dads-framework/feature-flags\",\n \"@dads-framework/http\",\n \"@dads-framework/identity\",\n \"@dads-framework/job-queue\",\n \"@dads-framework/postgres\",\n \"@dads-framework/postgres-access\",\n \"@dads-framework/ui\",\n \"drizzle-orm\",\n \"node-pg-migrate\",\n \"tsx\",\n \"zod\"\n ],\n \"verification\": [\"npm run verify\"],\n \"skills\": []\n },\n {\n \"name\": \"domains-tenants\",\n \"root\": \"domains/tenants\",\n \"kind\": \"core\",\n \"responsibility\": \"Owns the tenant HTTP surface.\",\n \"allowedDependencies\": [\n \"@dads-framework/access\",\n \"@dads-framework/audit\",\n \"@dads-framework/client\",\n \"@dads-framework/core\",\n \"@dads-framework/feature-flags\",\n \"@dads-framework/http\",\n \"@dads-framework/identity\",\n \"@dads-framework/postgres\",\n \"@dads-framework/postgres-access\",\n \"@dads-framework/ui\",\n \"drizzle-orm\",\n \"node-pg-migrate\",\n \"tsx\",\n \"zod\"\n ],\n \"verification\": [\"npm run verify\"],\n \"skills\": []\n },\n {\n \"name\": \"libraries-app-runtime\",\n \"root\": \"libraries/app-runtime\",\n \"kind\": \"core\",\n \"responsibility\": \"Holds the app runtime service token and account types.\",\n \"allowedDependencies\": [\n \"@dads-framework/access\",\n \"@dads-framework/audit\",\n \"@dads-framework/core\",\n \"@dads-framework/feature-flags\",\n \"@dads-framework/http\",\n \"@dads-framework/identity\",\n \"@dads-framework/job-queue\",\n \"@dads-framework/object-storage\",\n \"@dads-framework/postgres\",\n \"@dads-framework/postgres-access\",\n \"drizzle-orm\",\n \"node-pg-migrate\",\n \"tsx\",\n \"zod\"\n ],\n \"verification\": [\"npm run verify\"],\n \"skills\": []\n },\n {\n \"name\": \"domains-support\",\n \"root\": \"domains/support\",\n \"kind\": \"core\",\n \"responsibility\": \"Owns the staff impersonation HTTP surface.\",\n \"allowedDependencies\": [\"@dads-framework/identity\", \"zod\"],\n \"verification\": [\"npm run verify\"],\n \"skills\": []\n },\n {\n \"name\": \"libraries-sign-in-options\",\n \"root\": \"libraries/sign-in-options\",\n \"kind\": \"core\",\n \"responsibility\": \"Owns the sign-in availability route contract.\",\n \"allowedDependencies\": [\"@dads-framework/core\", \"zod\"],\n \"verification\": [\"npm run verify\"],\n \"skills\": []\n },\n {\n \"name\": \"migrations\",\n \"root\": \"migrations\",\n \"kind\": \"binding\",\n \"responsibility\": \"Installs the app schema and audit triggers.\",\n \"allowedDependencies\": [\n \"@dads-framework/access\",\n \"@dads-framework/audit\",\n \"@dads-framework/core\",\n \"@dads-framework/feature-flags\",\n \"@dads-framework/http\",\n \"@dads-framework/identity\",\n \"@dads-framework/postgres\",\n \"@dads-framework/postgres-access\",\n \"drizzle-orm\",\n \"node-pg-migrate\",\n \"tsx\",\n \"zod\"\n ],\n \"verification\": [\"npm run verify\"],\n \"skills\": []\n }\n ],\n \"domainBoundaries\": {\n \"domains\": [\"src/domains/*\", \"domains/*\"],\n \"libraries\": [\"libraries/*\"],\n \"workflows\": [\"workflows/*\"],\n \"integrations\": [\"integrations/*\"],\n \"composition\": [\"src/composition\", \"apps/*\", \"assembly\"]\n }\n}\n" },
|
|
61
|
+
{ path: "dads.testing.json", content: "{\n \"schemaVersion\": 1,\n \"workspace\": {\n \"root\": \".\",\n \"fullFallback\": {\n \"taskIds\": [\n \"assembly:unit\",\n \"dads-fixture-kit-workbench:integration\",\n \"dads-fixture-kit-workbench:typecheck\",\n \"dads-fixture-kit-workbench:unit\",\n \"domains-notes:unit\"\n ]\n }\n },\n \"projects\": [\n {\n \"id\": \"assembly\",\n \"root\": \"assembly\",\n \"fallbackDependencies\": [\n \"domains-notes\",\n \"domains-support\",\n \"domains-tenants\",\n \"libraries-app-runtime\",\n \"libraries-sign-in-options\",\n \"migrations\"\n ]\n },\n {\n \"id\": \"dads-fixture-kit-workbench\",\n \"root\": \".\",\n \"fallbackDependencies\": [\n \"assembly\",\n \"domains-notes\",\n \"domains-support\",\n \"domains-tenants\",\n \"libraries-app-runtime\",\n \"libraries-sign-in-options\",\n \"migrations\",\n \"starter-app\"\n ]\n },\n {\n \"id\": \"domains-notes\",\n \"root\": \"domains/notes\",\n \"fallbackDependencies\": [\"libraries-app-runtime\", \"libraries-sign-in-options\"]\n },\n {\n \"id\": \"domains-support\",\n \"root\": \"domains/support\",\n \"fallbackDependencies\": [\"libraries-app-runtime\", \"libraries-sign-in-options\"]\n },\n {\n \"id\": \"domains-tenants\",\n \"root\": \"domains/tenants\",\n \"fallbackDependencies\": [\"libraries-app-runtime\", \"libraries-sign-in-options\"]\n },\n {\n \"id\": \"libraries-app-runtime\",\n \"root\": \"libraries/app-runtime\",\n \"fallbackDependencies\": []\n },\n {\n \"id\": \"libraries-sign-in-options\",\n \"root\": \"libraries/sign-in-options\",\n \"fallbackDependencies\": []\n },\n {\n \"id\": \"migrations\",\n \"root\": \"migrations\",\n \"fallbackDependencies\": []\n },\n {\n \"id\": \"starter-app\",\n \"root\": \"apps\",\n \"fallbackDependencies\": [\n \"domains-notes\",\n \"domains-support\",\n \"domains-tenants\",\n \"libraries-app-runtime\",\n \"libraries-sign-in-options\",\n \"migrations\"\n ]\n }\n ],\n \"tasks\": [\n {\n \"id\": \"assembly:unit\",\n \"project\": \"assembly\",\n \"kind\": \"test\",\n \"execution\": {\n \"executable\": \"npx\",\n \"args\": [\n \"vitest\",\n \"run\",\n \"--dir\",\n \"assembly\",\n \"--exclude\",\n \"**/*.integration.test.*\",\n \"--exclude\",\n \"**/*.integration.spec.*\"\n ],\n \"fileNarrowing\": {\n \"suffixes\": [\n \".test.ts\",\n \".test.tsx\",\n \".test.mts\",\n \".test.js\",\n \".test.mjs\",\n \".spec.ts\",\n \".spec.tsx\",\n \".spec.mts\"\n ],\n \"excludeSuffixes\": [\n \".integration.test.ts\",\n \".integration.test.tsx\",\n \".integration.test.mts\",\n \".integration.test.js\",\n \".integration.test.mjs\",\n \".integration.spec.ts\",\n \".integration.spec.tsx\"\n ],\n \"setupFiles\": [\"vite.config.ts\"]\n }\n },\n \"dependsOn\": [\"dads-fixture-kit-workbench:typecheck\"],\n \"impact\": {\n \"mode\": \"reachability\",\n \"paths\": []\n }\n },\n {\n \"id\": \"dads-fixture-kit-workbench:integration\",\n \"project\": \"dads-fixture-kit-workbench\",\n \"kind\": \"test\",\n \"execution\": {\n \"executable\": \"npx\",\n \"args\": [\"vitest\", \"run\"],\n \"fileNarrowing\": {\n \"suffixes\": [\n \".integration.test.ts\",\n \".integration.test.tsx\",\n \".integration.test.mts\",\n \".integration.test.js\",\n \".integration.test.mjs\",\n \".integration.spec.ts\",\n \".integration.spec.tsx\"\n ],\n \"setupFiles\": [\"vite.config.ts\"]\n }\n },\n \"dependsOn\": [\"dads-fixture-kit-workbench:typecheck\"],\n \"impact\": {\n \"mode\": \"reachability\",\n \"paths\": []\n }\n },\n {\n \"id\": \"dads-fixture-kit-workbench:typecheck\",\n \"project\": \"dads-fixture-kit-workbench\",\n \"kind\": \"typecheck\",\n \"execution\": {\n \"executable\": \"npm\",\n \"args\": [\"run\", \"typecheck\"]\n },\n \"dependsOn\": [],\n \"impact\": {\n \"mode\": \"reachability\",\n \"paths\": []\n }\n },\n {\n \"id\": \"dads-fixture-kit-workbench:unit\",\n \"project\": \"dads-fixture-kit-workbench\",\n \"kind\": \"test\",\n \"execution\": {\n \"executable\": \"npx\",\n \"args\": [\"vitest\", \"run\", \"--exclude\", \"**/*.integration.test.*\", \"--exclude\", \"**/*.integration.spec.*\"],\n \"fileNarrowing\": {\n \"suffixes\": [\n \".test.ts\",\n \".test.tsx\",\n \".test.mts\",\n \".test.js\",\n \".test.mjs\",\n \".spec.ts\",\n \".spec.tsx\",\n \".spec.mts\"\n ],\n \"excludeSuffixes\": [\n \".integration.test.ts\",\n \".integration.test.tsx\",\n \".integration.test.mts\",\n \".integration.test.js\",\n \".integration.test.mjs\",\n \".integration.spec.ts\",\n \".integration.spec.tsx\"\n ],\n \"setupFiles\": [\"vite.config.ts\"]\n }\n },\n \"dependsOn\": [\"dads-fixture-kit-workbench:typecheck\"],\n \"impact\": {\n \"mode\": \"reachability\",\n \"paths\": []\n }\n },\n {\n \"id\": \"domains-notes:unit\",\n \"project\": \"domains-notes\",\n \"kind\": \"test\",\n \"execution\": {\n \"executable\": \"npx\",\n \"args\": [\n \"vitest\",\n \"run\",\n \"--dir\",\n \"domains/notes\",\n \"--exclude\",\n \"**/*.integration.test.*\",\n \"--exclude\",\n \"**/*.integration.spec.*\"\n ],\n \"fileNarrowing\": {\n \"suffixes\": [\n \".test.ts\",\n \".test.tsx\",\n \".test.mts\",\n \".test.js\",\n \".test.mjs\",\n \".spec.ts\",\n \".spec.tsx\",\n \".spec.mts\"\n ],\n \"excludeSuffixes\": [\n \".integration.test.ts\",\n \".integration.test.tsx\",\n \".integration.test.mts\",\n \".integration.test.js\",\n \".integration.test.mjs\",\n \".integration.spec.ts\",\n \".integration.spec.tsx\"\n ],\n \"setupFiles\": [\"vite.config.ts\"]\n }\n },\n \"dependsOn\": [\"dads-fixture-kit-workbench:typecheck\"],\n \"impact\": {\n \"mode\": \"reachability\",\n \"paths\": []\n }\n }\n ]\n}\n" },
|
|
61
62
|
{ path: "domains/notes/access/index.ts", content: "import { fromParam, requires } from \"@dads-framework/http\";\nimport { tenantAccess } from \"../../../libraries/app-runtime/index.js\";\nimport { noteIdSchema } from \"../contract/wire.js\";\n\n/** Notes inherit visibility from their parent tenant and require a branded NoteId. */\nexport const note = tenantAccess.tenant.child(\"note\", {\n id: noteIdSchema,\n inherit: [\"view\"],\n});\n\nexport const notesPermission = tenantAccess.tenant.permissions.view;\n\n/** Notes are visible only inside a tenant the account can view. */\nexport const notesAccess = requires(notesPermission, fromParam(\"tenantId\"));\n" },
|
|
63
|
+
{ path: "domains/notes/access/note-access.dst.test.ts", content: "import { createAccessClient } from \"@dads-framework/access/runtime\";\nimport { FakeAuthorization } from \"@dads-framework/access/testing\";\nimport { tenantIdSchema } from \"@dads-framework/identity/tenants\";\nimport {\n createExpiringTokenStore,\n createFaultyEventStream,\n defineSimAction,\n defineSimulation,\n runSimulation,\n type StreamSubscriber,\n} from \"@dads-framework/testing/dst\";\nimport { describe, expect, it } from \"vitest\";\nimport { account, tenantAccess } from \"../../../libraries/app-runtime/index.js\";\nimport { noteIdSchema } from \"../contract/wire.js\";\nimport { note } from \"./index.js\";\n\ndescribe(\"note-access DST simulation\", () => {\n it(\"enforces denial, token TTL expiry, and mid-stream SSE revocation across random interleavings\", async () => {\n type NoteEvent = { readonly noteId: string; readonly issuedAtMs: number };\n\n type State = {\n readonly client: ReturnType<typeof createAccessClient>;\n readonly tenantId: ReturnType<typeof tenantIdSchema.parse>;\n readonly accounts: readonly string[];\n readonly activeMembers: Set<string>;\n readonly revokedMembers: Set<string>;\n readonly tokens: ReturnType<typeof createExpiringTokenStore<{ readonly accountId: string }>>;\n readonly tokenIdsByAccount: Map<string, string[]>;\n readonly stream: ReturnType<typeof createFaultyEventStream<NoteEvent>>;\n readonly subscribers: Map<string, StreamSubscriber<NoteEvent>>;\n readonly revokedAtCursor: Map<string, number>;\n };\n\n const spec = defineSimulation<State>({\n name: \"note-access-revocation-dst\",\n createState: (world) => {\n const fake = new FakeAuthorization({\n [tenantAccess.tenant.wireName]: { view: [\"member\"] },\n });\n const tenantId = tenantIdSchema.parse(world.nextUuidV7());\n return {\n client: createAccessClient(fake),\n tenantId,\n accounts: [\"acct-a\", \"acct-b\", \"acct-c\", \"outsider\"],\n activeMembers: new Set(),\n revokedMembers: new Set(),\n tokens: createExpiringTokenStore(world),\n tokenIdsByAccount: new Map(),\n stream: createFaultyEventStream(world),\n subscribers: new Map(),\n revokedAtCursor: new Map(),\n };\n },\n actions: [\n defineSimAction({\n name: \"grant-member\",\n weight: 3,\n generate: (_state, world) => world.rng.pick([\"acct-a\", \"acct-b\", \"acct-c\"]),\n execute: async (state, accountId) => {\n if (state.activeMembers.has(accountId) || state.revokedMembers.has(accountId)) return;\n await state.client.add(account(accountId), tenantAccess.tenant(state.tenantId).member);\n state.activeMembers.add(accountId);\n const token = state.tokens.issue({ accountId }, 30_000);\n const list = state.tokenIdsByAccount.get(accountId) ?? [];\n list.push(token.id);\n state.tokenIdsByAccount.set(accountId, list);\n state.subscribers.set(accountId, state.stream.subscribe(accountId));\n },\n }),\n defineSimAction({\n name: \"publish-note\",\n weight: 4,\n generate: (_state, world) => world.nextUuidV7(),\n execute: async (state, rawNoteId, world) => {\n const noteId = noteIdSchema.parse(rawNoteId);\n await state.client.add(tenantAccess.tenant(state.tenantId), note(noteId).tenant);\n state.stream.publish({ noteId, issuedAtMs: world.clock.nowMs() });\n },\n }),\n defineSimAction({\n name: \"revoke-member\",\n weight: 2,\n enabled: (state) => state.activeMembers.size > 0,\n generate: (state, world) => world.rng.pick([...state.activeMembers]),\n execute: async (state, accountId) => {\n await state.client.remove(account(accountId), tenantAccess.tenant(state.tenantId).member);\n state.activeMembers.delete(accountId);\n state.revokedMembers.add(accountId);\n for (const tokenId of state.tokenIdsByAccount.get(accountId) ?? []) {\n state.tokens.revoke(tokenId);\n }\n const sub = state.subscribers.get(accountId);\n if (sub !== undefined) {\n sub.revoke();\n state.revokedAtCursor.set(accountId, sub.received.length);\n }\n },\n }),\n defineSimAction({\n name: \"advance-clock\",\n weight: 2,\n generate: (_state, world) => world.rng.int(5_000, 40_000),\n execute: (_state, deltaMs, world) => {\n world.clock.advance(deltaMs);\n },\n }),\n ],\n invariants: [\n {\n name: \"outsider-and-revoked-always-denied\",\n check: async (state) => {\n expect(await state.client.can(account(\"outsider\"), tenantAccess.tenant(state.tenantId).view)).toBe(false);\n for (const revokedId of state.revokedMembers) {\n expect(await state.client.can(account(revokedId), tenantAccess.tenant(state.tenantId).view)).toBe(false);\n for (const tokenId of state.tokenIdsByAccount.get(revokedId) ?? []) {\n expect(state.tokens.verify(tokenId)).toBeUndefined();\n }\n }\n },\n },\n {\n name: \"revoked-stream-receives-zero-future-events\",\n check: (state) => {\n for (const [accountId, countAtRevoke] of state.revokedAtCursor.entries()) {\n const sub = state.subscribers.get(accountId);\n expect(sub?.revoked).toBe(true);\n expect(sub?.received.length).toBe(countAtRevoke);\n expect(sub?.reconnect()).toBe(false);\n }\n },\n },\n ],\n });\n\n const report = await runSimulation(spec, { seeds: 15, steps: 35 });\n expect(report.ok).toBe(true);\n });\n});\n" },
|
|
62
64
|
{ path: "domains/notes/access/note-access.test.ts", content: "import { compileAccess, emitZed } from \"@dads-framework/access\";\nimport { createAccessClient } from \"@dads-framework/access/runtime\";\nimport { FakeAuthorization } from \"@dads-framework/access/testing\";\nimport { mintEntityId } from \"@dads-framework/core/contract\";\nimport { tenantIdSchema } from \"@dads-framework/identity/tenants\";\nimport { describe, expect, expectTypeOf, it } from \"vitest\";\n\nimport { account, accountAccess, tenantAccess } from \"../../../libraries/app-runtime/index.js\";\nimport { noteIdSchema, type NoteId } from \"../contract/wire.js\";\nimport { note } from \"./index.js\";\n\ndescribe(\"note access resource\", () => {\n it(\"enforces branded NoteId on note(id) and compiles under tenant\", () => {\n const noteId = mintEntityId(noteIdSchema);\n const tenantId = tenantIdSchema.parse(\"0194f4a0-1234-7000-8000-000000000002\");\n const noteRef = note(noteId);\n const tenantRef = tenantAccess.tenant(tenantId);\n\n expectTypeOf(noteRef.id).toEqualTypeOf<NoteId>();\n expectTypeOf(note).parameter(0).toEqualTypeOf<NoteId>();\n expect(note.idSchema).toBe(noteIdSchema);\n expect(noteRef.id).toBe(noteId);\n expect(noteRef.view.resource).toEqual({ type: \"note\", id: noteId });\n expect(tenantRef.id).toBe(tenantId);\n\n const model = compileAccess([accountAccess, tenantAccess.tenant, note], {\n allowLookupResourcesOn: [tenantAccess.tenant],\n });\n const zed = emitZed(model);\n expect(zed).toContain(\"definition note {\");\n expect(zed).toContain(\"relation tenant: tenants/tenant\");\n expect(zed).toContain(\"permission view = tenant->view\");\n });\n\n it(\"links a branded note to its parent tenant and denies unrelated accounts\", async () => {\n const noteId = mintEntityId(noteIdSchema);\n const tenantId = tenantIdSchema.parse(\"0194f4a0-1234-7000-8000-000000000002\");\n const fake = new FakeAuthorization({\n [tenantAccess.tenant.wireName]: { view: [\"member\"] },\n });\n const client = createAccessClient(fake);\n\n await client.add(tenantAccess.tenant(tenantId), note(noteId).tenant);\n await client.add(account(\"member-1\"), tenantAccess.tenant(tenantId).member);\n\n expect(await client.can(account(\"member-1\"), tenantAccess.tenant(tenantId).view)).toBe(true);\n expect(await client.can(account(\"outsider-1\"), tenantAccess.tenant(tenantId).view)).toBe(false);\n expect(await client.listDirect(note(noteId).tenant)).toEqual([\n { type: tenantAccess.tenant.wireName, id: tenantId },\n ]);\n });\n});\n" },
|
|
63
65
|
{ path: "domains/notes/contract/index.ts", content: "import { tenantIdSchema } from \"@dads-framework/identity/tenants\";\nimport { z } from \"zod\";\n\nexport * from \"./wire.js\";\n\nexport const inTenant = z.object({ tenantId: tenantIdSchema });\n" },
|
|
64
66
|
{ path: "domains/notes/contract/wire.ts", content: "import {\n entityIdSchema,\n getOperation,\n listOperation,\n paginationQuerySchema,\n postOperation,\n} from \"@dads-framework/core/contract\";\nimport { z } from \"zod\";\n\nexport const noteIdSchema = entityIdSchema(\"NoteId\", \"Note identifier.\");\nexport type NoteId = z.infer<typeof noteIdSchema>;\n\nexport const noteInput = z.object({ text: z.string().trim().min(1).max(2000) });\nexport const note = noteInput.extend({\n id: noteIdSchema,\n tenantId: z.uuid(),\n});\n\nexport const notesExport = \"notes.export\";\n\nexport const noteFeatures = z.object({\n features: z.array(z.string()),\n stateHash: z.string(),\n});\n\nexport const noteExportFormat = z.enum([\"csv\", \"pdf\"]);\nexport const noteExportFile = z.strictObject({\n contentType: z.enum([\"application/pdf\", \"text/csv\"]),\n base64: z.base64(),\n});\n\nconst tenantPathParams = z.object({ tenantId: z.uuid() });\nexport const noteIdParamSchema = tenantPathParams.extend({\n noteId: noteIdSchema,\n});\nconst noteExportParams = noteIdParamSchema.extend({\n format: noteExportFormat,\n});\n\nexport const readNoteFeaturesOp = getOperation({\n path: \"/tenants/:tenantId/notes/features\",\n params: tenantPathParams,\n response: noteFeatures,\n});\n\nexport const listNotesOp = listOperation({\n path: \"/tenants/:tenantId/notes\",\n params: tenantPathParams,\n query: paginationQuerySchema,\n item: note,\n});\n\nexport const createNoteOp = postOperation({\n path: \"/tenants/:tenantId/notes\",\n params: tenantPathParams,\n body: noteInput,\n response: note,\n});\n\nexport const exportNoteOp = getOperation({\n path: \"/tenants/:tenantId/notes/:noteId/exports/:format\",\n params: noteExportParams,\n response: noteExportFile,\n});\n" },
|
|
65
67
|
{ path: "domains/notes/copy/flag-metadata.ts", content: "import { defineCopy } from \"@dads-framework/ui/copy\";\n\nexport const noteFlagCopy = defineCopy({\n \"notes.export.description\": {\n en: \"Advertise whether the notes export capability is available.\",\n },\n});\n" },
|
|
66
68
|
{ path: "domains/notes/index.ts", content: "export { noteIdSchema, type NoteId } from \"./contract/index.js\";\nexport { notesAttachmentWorker, notesPlugin } from \"./server/plugin.js\";\n" },
|
|
69
|
+
{ path: "domains/notes/pure/note-rules.dst.test.ts", content: "import {\n createFaultyDeliveryQueue,\n createFaultyTransactionRunner,\n defineSimAction,\n defineSimulation,\n runSimulation,\n} from \"@dads-framework/testing/dst\";\nimport { describe, expect, it } from \"vitest\";\nimport { noteIdSchema } from \"../contract/wire.js\";\nimport {\n buildNoteExportFilename,\n createNoteRecord,\n escapeCsvFormulaCell,\n type NoteExportFormat,\n type NoteRecord,\n} from \"./note-rules.js\";\n\ndescribe(\"note-rules DST simulation\", () => {\n it(\"preserves normalization, idempotency, and CSV safety under 40001 retries and duplicate delivery\", async () => {\n type NoteCommand = {\n readonly opId: string;\n readonly noteId: string;\n readonly tenantId: string;\n readonly rawText: string;\n };\n\n type State = {\n readonly tx: ReturnType<typeof createFaultyTransactionRunner>;\n readonly queue: ReturnType<typeof createFaultyDeliveryQueue<NoteCommand>>;\n readonly notes: Map<string, NoteRecord>;\n readonly appliedOps: Set<string>;\n readonly tenantIds: readonly string[];\n };\n\n const sampleTexts = [\n \" Hello\\r\\nworld \",\n \"=SUM(A1:A5)\",\n \" +cmd\\rnext line\",\n \"-flag\\r\\nbody\",\n \"@mention\\tvalue \",\n \"Ordinary note text\",\n ];\n\n const spec = defineSimulation<State>({\n name: \"notes-pure-idempotent-dst\",\n createState: (world) => ({\n tx: createFaultyTransactionRunner(world, { serializationFailureRate: 0.3, deadlockRate: 0.05, maxAttempts: 8 }),\n queue: createFaultyDeliveryQueue<NoteCommand>(world, {\n duplicateRate: 0.45,\n dropRate: 0,\n reorderRate: 0.5,\n maxDelayMs: 120,\n }),\n notes: new Map(),\n appliedOps: new Set(),\n tenantIds: [world.nextUuidV7(), world.nextUuidV7()],\n }),\n actions: [\n defineSimAction({\n name: \"enqueue-note\",\n weight: 4,\n generate: (state, world) => ({\n opId: world.nextUuidV7(),\n noteId: world.nextUuidV7(),\n tenantId: world.rng.pick(state.tenantIds),\n rawText: world.rng.pick(sampleTexts),\n }),\n execute: (state, cmd) => {\n state.queue.enqueue(cmd, cmd.opId);\n },\n }),\n defineSimAction({\n name: \"deliver-batch\",\n weight: 3,\n enabled: (state) => state.queue.pendingCount() > 0,\n generate: (_state, world) => world.rng.int(10, 150),\n execute: async (state, advanceMs, world) => {\n world.clock.advance(advanceMs);\n await state.queue.deliverNext(async (envelope) => {\n await state.tx.run(() => {\n if (state.appliedOps.has(envelope.messageId)) return;\n const parsedId = noteIdSchema.parse(envelope.payload.noteId);\n const record = createNoteRecord({\n id: parsedId,\n tenantId: envelope.payload.tenantId,\n text: envelope.payload.rawText,\n });\n state.appliedOps.add(envelope.messageId);\n state.notes.set(record.id, record);\n });\n });\n },\n }),\n ],\n invariants: [\n {\n name: \"normalized-and-csv-safe\",\n check: (state) => {\n for (const record of state.notes.values()) {\n expect(noteIdSchema.safeParse(record.id).success).toBe(true);\n expect(record.text).not.toContain(\"\\r\");\n expect(record.text).toBe(record.text.trim());\n\n const escaped = escapeCsvFormulaCell(record.text);\n expect(/^[\\s]*[=+\\-@]/u.test(escaped)).toBe(false);\n\n for (const format of [\"csv\", \"pdf\"] satisfies readonly NoteExportFormat[]) {\n expect(buildNoteExportFilename(record.id, format)).toMatch(/^note-[a-z0-9]{1,8}\\.(csv|pdf)$/u);\n }\n }\n },\n },\n {\n name: \"idempotent-apply-count\",\n check: (state) => {\n expect(state.notes.size).toBe(state.appliedOps.size);\n },\n },\n ],\n });\n\n const report = await runSimulation(spec, { seeds: 15, steps: 35 });\n expect(report.ok).toBe(true);\n });\n});\n" },
|
|
67
70
|
{ path: "domains/notes/pure/note-rules.test.ts", content: "import { mintEntityId } from \"@dads-framework/core/contract\";\nimport { describe, expect, it } from \"vitest\";\nimport { noteIdSchema } from \"../contract/wire.js\";\nimport { buildNoteExportFilename, createNoteRecord, escapeCsvFormulaCell, normalizeNoteText } from \"./note-rules.js\";\n\ndescribe(\"note-rules\", () => {\n it(\"normalizes whitespace and line endings deterministically\", () => {\n expect(normalizeNoteText(\" first line\\r\\nsecond line\\rthird line \")).toBe(\"first line\\nsecond line\\nthird line\");\n expect(normalizeNoteText(\"\\n single line \\t\")).toBe(\"single line\");\n });\n\n it(\"creates a normalized note record from explicit inputs\", () => {\n const id = noteIdSchema.parse(\"0194f4a0-1234-7000-8000-000000000001\");\n const record = createNoteRecord({\n id,\n tenantId: \"0194f4a0-1234-7000-8000-000000000002\",\n text: \" Hello\\r\\nworld \",\n });\n expect(record).toEqual({\n id,\n tenantId: \"0194f4a0-1234-7000-8000-000000000002\",\n text: \"Hello\\nworld\",\n });\n });\n\n it(\"accepts freshly minted UUIDv7 note ids\", () => {\n const id = mintEntityId(noteIdSchema);\n const record = createNoteRecord({\n id,\n tenantId: \"0194f4a0-1234-7000-8000-000000000002\",\n text: \" Fresh note \",\n });\n expect(record.id).toBe(id);\n expect(noteIdSchema.safeParse(record.id).success).toBe(true);\n expect(record.text).toBe(\"Fresh note\");\n });\n\n it(\"escapes CSV formula prefixes and preserves ordinary text\", () => {\n expect(escapeCsvFormulaCell(\"=SUM(A1:A2)\")).toBe(\"'=SUM(A1:A2)\");\n expect(escapeCsvFormulaCell(\" +1+1\")).toBe(\"' +1+1\");\n expect(escapeCsvFormulaCell(\"-cmd\")).toBe(\"'-cmd\");\n expect(escapeCsvFormulaCell(\"@mention\")).toBe(\"'@mention\");\n expect(escapeCsvFormulaCell(\"Alpha's note\")).toBe(\"Alpha's note\");\n });\n\n it(\"builds deterministic export filenames\", () => {\n expect(buildNoteExportFilename(\"0194F4A0-1234-7000-8000-000000000001\", \"csv\")).toBe(\"note-0194f4a0.csv\");\n expect(buildNoteExportFilename(\"0194F4A0-1234-7000-8000-000000000001\", \"pdf\")).toBe(\"note-0194f4a0.pdf\");\n expect(buildNoteExportFilename(\" --- \", \"csv\")).toBe(\"note.csv\");\n });\n});\n" },
|
|
68
71
|
{ path: "domains/notes/pure/note-rules.ts", content: "import type { NoteId } from \"../contract/wire.js\";\n\nexport type NoteExportFormat = \"csv\" | \"pdf\";\n\nexport type NoteRecord = {\n readonly id: NoteId;\n readonly tenantId: string;\n readonly text: string;\n};\n\n/** Normalize line endings and surrounding whitespace before persisting a note. */\nexport function normalizeNoteText(text: string): string {\n return text.replace(/\\r\\n?/gu, \"\\n\").trim();\n}\n\n/** Build a normalized note record from explicit inputs without ambient ID or clock access. */\nexport function createNoteRecord(input: {\n readonly id: NoteId;\n readonly tenantId: string;\n readonly text: string;\n}): NoteRecord {\n return {\n id: input.id,\n tenantId: input.tenantId,\n text: normalizeNoteText(input.text),\n };\n}\n\n/** Neutralize spreadsheet formula prefixes before serializing note text to CSV. */\nexport function escapeCsvFormulaCell(text: string): string {\n return /^[\\s]*[=+\\-@]/u.test(text) ? `'${text}` : text;\n}\n\n/** Build a deterministic, filesystem-safe download filename for a note export. */\nexport function buildNoteExportFilename(noteId: string, format: NoteExportFormat): string {\n const shortId = noteId\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]/gu, \"\")\n .slice(0, 8);\n const stem = shortId.length > 0 ? `note-${shortId}` : \"note\";\n return `${stem}.${format}`;\n}\n" },
|
|
69
72
|
{ path: "domains/notes/server/attachments.ts", content: "import { createHash, randomUUID } from \"node:crypto\";\nimport { notFound } from \"@dads-framework/core/errors\";\nimport { getRoute, routeGroup, postRoute } from \"@dads-framework/http\";\nimport { defineJob } from \"@dads-framework/job-queue/core\";\nimport { and, eq } from \"drizzle-orm\";\nimport { z } from \"zod\";\n\nimport type { StarterServices } from \"../../../libraries/app-runtime/index.js\";\nimport { notesAccess, notesPermission } from \"../access/index.js\";\nimport { inTenant, noteIdSchema } from \"../contract/index.js\";\nimport { noteTable } from \"./tables.js\";\n\ntype Files = Pick<StarterServices, \"files\" | \"jobs\" | \"writeWithPermission\">;\nconst attachmentJobName = \"notes.inspect-attachment\";\nconst notePath = inTenant.extend({ noteId: noteIdSchema });\nconst filePath = notePath.extend({ fileId: z.uuid() });\nconst digest = z.strictObject({\n bytes: z.number().int(),\n sha256: z.string().length(64),\n});\n\nexport function noteAttachmentJobs({ files }: Pick<StarterServices, \"files\">) {\n return [\n defineJob({\n name: attachmentJobName,\n payload: filePath,\n retry: { attempts: 3, backoffMs: 300 },\n schedules: [],\n run: async (params) => {\n const key = objectKey(params);\n const stored = await files.get(key);\n if (!stored) return;\n const facts = {\n bytes: stored.body.byteLength,\n sha256: createHash(\"sha256\").update(stored.body).digest(\"hex\"),\n };\n await files.put(`${key}.facts`, JSON.stringify(facts), \"application/json\");\n },\n }),\n ];\n}\n\nexport function noteAttachmentRoutes(services: Files) {\n return routeGroup(\"Notes\", [\n postRoute({\n route: {\n method: \"POST\",\n template: \"/tenants/:tenantId/notes/:noteId/attachments\",\n },\n summary: \"Attach a short UTF-8 text file to a note\",\n access: notesAccess,\n params: notePath,\n body: z.strictObject({ text: z.string().min(1).max(16_384) }),\n response: z.strictObject({ fileId: z.uuid() }),\n handler: ({ body, params, subject }) => storeNoteAttachment(services, params, subject, body.text),\n }),\n getRoute({\n route: {\n method: \"GET\",\n template: \"/tenants/:tenantId/notes/:noteId/attachments/:fileId\",\n },\n summary: \"Read a note attachment and its inspected byte digest\",\n access: notesAccess,\n params: filePath,\n response: z.strictObject({\n text: z.string(),\n inspection: digest.nullable(),\n }),\n handler: ({ params }) => readNoteAttachment(services, params),\n }),\n ]);\n}\n\nasync function storeNoteAttachment(\n { files, jobs, writeWithPermission }: Files,\n params: z.infer<typeof notePath>,\n subject: Parameters<StarterServices[\"writeWithPermission\"]>[0][\"subject\"],\n text: string,\n) {\n const fileId = randomUUID();\n const uploaded = { ...params, fileId };\n const key = objectKey(uploaded);\n try {\n await writeWithPermission({ subject, permission: notesPermission, resourceId: params.tenantId }, async (tx) => {\n const [note] = await tx\n .select({ id: noteTable.id })\n .from(noteTable)\n .where(and(eq(noteTable.id, params.noteId), eq(noteTable.tenantId, params.tenantId)))\n .limit(1);\n if (!note) throw notFound(\"NOT_FOUND\", \"Note not found\");\n await files.put(key, text, \"text/plain\");\n });\n } catch (error) {\n await files.delete(key).catch(() => undefined);\n throw error;\n }\n await jobs.enqueue(attachmentJobName, uploaded);\n return { fileId };\n}\n\nasync function readNoteAttachment({ files }: Files, params: z.infer<typeof filePath>) {\n const key = objectKey(params);\n const [stored, inspected] = await Promise.all([files.get(key), files.get(`${key}.facts`)]);\n if (!stored) throw notFound(\"NOT_FOUND\", \"Attachment not found\");\n const decode = new TextDecoder();\n return {\n text: decode.decode(stored.body),\n inspection: inspected ? digest.parse(JSON.parse(decode.decode(inspected.body))) : null,\n };\n}\n\nfunction objectKey({ tenantId, noteId, fileId }: z.infer<typeof filePath>): string {\n return `notes/${tenantId}/${noteId}/${fileId}`;\n}\n" },
|
|
@@ -85,7 +88,7 @@ export const kitStarterFiles = [
|
|
|
85
88
|
{ path: "domains/tenants/copy/invitation-openapi.ts", content: "import { defineCopy } from \"@dads-framework/ui/copy\";\n\nexport const tenantInvitationOpenApiCopy = defineCopy({\n \"tenants.invitation.joined\": { en: \"Tenant joined\" },\n});\n" },
|
|
86
89
|
{ path: "domains/tenants/copy/scim-binding-copy.ts", content: "import { defineCopy } from \"@dads-framework/ui/copy\";\n\nexport const scimBindingCopy = defineCopy({\n \"tenants.scimBinding.tag\": { en: \"Tenant directory\" },\n \"tenants.scimBinding.summary\": {\n en: \"Link a directory user to an existing workspace membership\",\n },\n \"tenants.scimBinding.success\": { en: \"The directory user is linked.\" },\n \"tenants.scimBinding.origin\": { en: \"The request origin is not allowed.\" },\n \"tenants.scimBinding.invalid\": { en: \"Supply a directory user and account.\" },\n \"tenants.scimBinding.unavailable\": { en: \"Resource not found\" },\n});\n" },
|
|
87
90
|
{ path: "domains/tenants/index.ts", content: "export { tenantPermissionsPlugin, tenantsPlugin } from \"./server/plugin.js\";\nexport { tenantAuditExportPlugin } from \"./server/audit-export.js\";\nexport { scimBindingRoutes } from \"./server/scim-binding-route.js\";\n" },
|
|
88
|
-
{ path: "domains/tenants/server/audit-export.ts", content: "import { createAuditLogExporter,
|
|
91
|
+
{ path: "domains/tenants/server/audit-export.ts", content: "import { createAuditLogExporter, type AuditLogCursor } from \"@dads-framework/audit\";\nimport { notFound, validation } from \"@dads-framework/core/errors\";\nimport { defineRawRoute, fromParam, requires, routeGroup } from \"@dads-framework/http\";\nimport { definePlugin } from \"@dads-framework/core/plugin\";\nimport { tenantIdSchema } from \"@dads-framework/identity/tenants/contract\";\nimport { z } from \"zod\";\n\nimport { starterServices, tenantAccess, type StarterServices } from \"../../../libraries/app-runtime/index.js\";\nimport { auditExportCopy } from \"../copy/audit-export-openapi.js\";\n\nconst tenantParams = z.strictObject({ tenantId: tenantIdSchema });\nconst positiveInteger = z\n .string()\n .regex(/^[1-9]\\d*$/u)\n .transform(Number);\nconst pageSize = positiveInteger.pipe(z.int().max(500)).default(100);\nconst querySchema = z.union([\n z.strictObject({ pageSize }),\n z.strictObject({\n pageSize,\n beforeRecordedAt: z.iso.datetime({ precision: 6 }),\n beforePosition: positiveInteger.pipe(z.int()),\n }),\n]);\nconst auditExportPath = \"/tenants/:tenantId/audit-log/export\";\nconst nextLinkRelation = 'rel=\"next\"';\nconst permission = tenantAccess.tenant.permissions.manage_tenant;\n\nexport const tenantAuditExportPlugin = definePlugin({\n name: \"tenant-audit-export\",\n requires: [starterServices],\n setup: ({ use }) => ({\n routes: tenantAuditExportRoutes(use(starterServices)),\n }),\n});\n\nfunction tenantAuditExportRoutes({\n auditLogReader,\n authorization,\n}: Pick<StarterServices, \"auditLogReader\" | \"authorization\">) {\n if (auditLogReader === undefined) {\n throw new Error(\"Audit log export requires StarterServices.auditLogReader to be configured in assembly.\");\n }\n const reader = auditLogReader;\n return routeGroup(auditExportCopy[\"tenants.auditExport.tag\"].en, [\n defineRawRoute({\n method: \"GET\",\n path: auditExportPath,\n summary: auditExportCopy[\"tenants.auditExport.summary\"].en,\n access: requires(permission, fromParam(\"tenantId\")),\n openapi: {\n parameters: [\n {\n name: \"tenantId\",\n in: \"path\",\n required: true,\n schema: { type: \"string\", format: \"uuid\" },\n },\n {\n name: \"pageSize\",\n in: \"query\",\n schema: { type: \"integer\", minimum: 1, maximum: 500, default: 100 },\n },\n {\n name: \"beforeRecordedAt\",\n in: \"query\",\n schema: { type: \"string\", format: \"date-time\" },\n description: auditExportCopy[\"tenants.auditExport.beforeRecordedAt\"].en,\n },\n {\n name: \"beforePosition\",\n in: \"query\",\n schema: { type: \"integer\", minimum: 1 },\n description: auditExportCopy[\"tenants.auditExport.beforePosition\"].en,\n },\n ],\n responses: {\n \"200\": {\n description: auditExportCopy[\"tenants.auditExport.success\"].en,\n headers: {\n Link: {\n description: auditExportCopy[\"tenants.auditExport.continuation\"].en,\n schema: { type: \"string\" },\n },\n },\n content: { \"application/x-ndjson\": { schema: { type: \"string\" } } },\n },\n \"400\": {\n description: auditExportCopy[\"tenants.auditExport.invalidInput\"].en,\n },\n \"401\": {\n description: auditExportCopy[\"tenants.auditExport.authenticationRequired\"].en,\n },\n \"404\": {\n description: auditExportCopy[\"tenants.auditExport.tenantUnavailable\"].en,\n },\n },\n },\n handler: async ({ request, reply, subject, authenticatedSubject }) => {\n const params = tenantParams.safeParse(request.params);\n const query = querySchema.safeParse(request.query);\n if (!params.success || !query.success)\n throw validation(\"INVALID_AUDIT_EXPORT\", \"Supply a tenant and a valid export page.\");\n const { tenantId } = params.data;\n const exportPage = createAuditLogExporter({\n reader,\n tenantDimension: \"tenant_id\",\n authorize: (id) => {\n if (\n subject === null ||\n authenticatedSubject === null ||\n subject.type !== authenticatedSubject.type ||\n subject.id !== authenticatedSubject.id\n )\n return false;\n return authorization.check({\n subject: authenticatedSubject,\n resource: { type: permission.entityWireName, id },\n permission: permission.permissionName,\n });\n },\n });\n const input = query.data;\n const page = await exportPage({\n tenantId,\n pageSize: input.pageSize,\n ...(\"beforePosition\" in input\n ? {\n olderThan: {\n position: input.beforePosition,\n recordedAt: input.beforeRecordedAt,\n },\n }\n : {}),\n });\n if (page.kind === \"denied\") throw notFound(\"RESOURCE_NOT_FOUND\", \"Resource not found\");\n if (page.nextCursor !== null)\n void reply.header(\"link\", nextPageLink(tenantId, input.pageSize, page.nextCursor));\n await reply\n .header(\"cache-control\", \"no-store\")\n .header(\"content-disposition\", 'attachment; filename=\"audit-log.ndjson\"')\n .type(page.contentType)\n .send(page.body);\n },\n }),\n ]);\n}\n\nfunction nextPageLink(tenantId: string, pageSize: number, next: AuditLogCursor): string {\n const query = new URLSearchParams({\n pageSize: String(pageSize),\n beforePosition: String(next.position),\n beforeRecordedAt: next.recordedAt,\n });\n const tenantPath = auditExportPath.replace(\":tenantId\", encodeURIComponent(tenantId));\n const nextUrl = `/api${tenantPath}?${query}`;\n return `<${nextUrl}>; ${nextLinkRelation}`;\n}\n" },
|
|
89
92
|
{ path: "domains/tenants/server/invitation-routes.ts", content: "import { apiResponseSchema } from \"@dads-framework/core/contract\";\nimport { forbidden, notFound, unauthorized, validation } from \"@dads-framework/core/errors\";\nimport { defineRawRoute, fromParam, postRoute, requireSession, requires, routeGroup } from \"@dads-framework/http\";\nimport {\n TenantInvitationUnavailableError,\n TenantUnavailableError,\n type TenantId,\n} from \"@dads-framework/identity/tenants\";\n\nimport { tenantAccess, type StarterServices } from \"../../../libraries/app-runtime/index.js\";\nimport {\n tenantInvitationAcceptance,\n tenantInvitationAccepted,\n tenantInvitationInput,\n tenantInvitationIssued,\n tenantInvitationParams,\n} from \"../contract/index.js\";\nimport { tenantInvitationOpenApiCopy } from \"../copy/invitation-openapi.js\";\n\ntype InvitationServices = Pick<\n StarterServices,\n \"tenants\" | \"identity\" | \"readTenantSessionPolicy\" | \"invitationOrigin\" | \"enqueueTenantInvitation\"\n>;\n\nconst permission = tenantAccess.tenant.permissions.manage_members;\n\nexport function tenantInvitationRoutes(services: InvitationServices) {\n return routeGroup(\"Tenant invitations\", [\n postRoute({\n route: { method: \"POST\", template: \"/tenants/:tenantId/invitations\" },\n summary: \"Invite a verified email address to this tenant\",\n access: requires(permission, fromParam(\"tenantId\")),\n params: tenantInvitationParams,\n body: tenantInvitationInput,\n response: tenantInvitationIssued,\n handler: async ({ body, params, subject }) => {\n const issued = await requestInvitation(services, subject.id, params.tenantId, body.email);\n try {\n await services.enqueueTenantInvitation(body.email, issued.token);\n } catch {\n throw new Error(\"Tenant invitation delivery is unavailable.\");\n }\n return { expiresAt: issued.expiresAt.toISOString() };\n },\n }),\n acceptRoute(services),\n ]);\n}\n\nasync function requestInvitation({ tenants }: InvitationServices, actor: string, tenant: TenantId, email: string) {\n try {\n return await tenants.invitations.issue(actor, tenant, email);\n } catch (error) {\n if (error instanceof TenantUnavailableError) {\n throw notFound(\"TENANT_UNAVAILABLE\", \"The tenant is unavailable.\");\n }\n throw error;\n }\n}\n\nfunction acceptRoute({ tenants, identity, invitationOrigin, readTenantSessionPolicy }: InvitationServices) {\n // Acceptance re-reads the verified identity from its cookie. Typed route\n // handlers intentionally receive an authorization subject, not headers.\n return defineRawRoute({\n method: \"POST\",\n path: \"/tenants/invitations/accept\",\n summary: \"Accept an invitation addressed to the current verified account\",\n access: requireSession(),\n openapi: {\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: { $ref: \"#/components/schemas/TenantInvitationAcceptance\" },\n },\n },\n },\n responses: {\n \"200\": {\n description: tenantInvitationOpenApiCopy[\"tenants.invitation.joined\"].en,\n content: {\n \"application/json\": {\n schema: { $ref: \"#/components/schemas/TenantInvitationAccepted\" },\n },\n },\n },\n },\n },\n openapiComponents: {\n TenantInvitationAcceptance: tenantInvitationAcceptance,\n TenantInvitationAccepted: apiResponseSchema(tenantInvitationAccepted),\n },\n handler: async ({ request, reply, subject }) => {\n if (request.headers.origin !== invitationOrigin)\n throw forbidden(\"INVITATION_ORIGIN\", \"The request origin is not allowed.\");\n const policy = await invitationSession(identity, readTenantSessionPolicy, request.headers.cookie);\n const signedIn = policy?.session ?? null;\n if (signedIn === null || !signedIn.account.emailVerified || signedIn.account.id !== subject?.id) {\n throw unauthorized(\"IDENTITY_REQUIRED\", \"Sign in with a verified account.\");\n }\n const input = tenantInvitationAcceptance.safeParse(request.body);\n if (!input.success) throw validation(\"INVALID_INVITATION_INPUT\", \"Supply an invitation token.\");\n const tenantId = await redeemInvitation(tenants, input.data.token, signedIn.account, ({ tenantId }) =>\n Promise.resolve(policy?.allowsTenant(tenantId) === true),\n );\n await reply.header(\"cache-control\", \"no-store\").send({ data: { tenantId } });\n },\n });\n}\n\nasync function invitationSession(\n identity: InvitationServices[\"identity\"],\n readTenantSessionPolicy: InvitationServices[\"readTenantSessionPolicy\"],\n cookie: string | string[] | undefined,\n) {\n if (typeof cookie !== \"string\") return null;\n const headers = new Headers({ cookie });\n if (readTenantSessionPolicy !== undefined) return readTenantSessionPolicy(headers);\n const session = await identity.readSession(headers);\n return session === null ? null : { session, allowsTenant: () => true };\n}\n\nasync function redeemInvitation(\n tenants: InvitationServices[\"tenants\"],\n token: string,\n account: Parameters<InvitationServices[\"tenants\"][\"invitations\"][\"accept\"]>[1],\n authorize: Parameters<InvitationServices[\"tenants\"][\"invitations\"][\"accept\"]>[2],\n) {\n try {\n return await tenants.invitations.accept(token, account, authorize);\n } catch (error) {\n if (error instanceof TenantInvitationUnavailableError) {\n throw notFound(\"TENANT_INVITATION_UNAVAILABLE\", \"The invitation is unavailable.\");\n }\n throw error;\n }\n}\n" },
|
|
90
93
|
{ path: "domains/tenants/server/permission-routes.ts", content: "import { paginationQuerySchema } from \"@dads-framework/core/contract\";\nimport { notFound } from \"@dads-framework/core/errors\";\nimport { fromParam, getRoute, listRoute, requires, routeGroup } from \"@dads-framework/http\";\nimport { TenantUnavailableError, tenantIdSchema, type Tenants } from \"@dads-framework/identity/tenants\";\nimport { z } from \"zod\";\nimport { tenantAccess } from \"../../../libraries/app-runtime/index.js\";\nimport {\n memberPermissions,\n memberPermissionsRoute,\n permissionAccountId,\n permissionMember,\n permissionRosterRoute,\n} from \"../contract/permissions-wire.js\";\n\nconst tenantParams = z.strictObject({ tenantId: tenantIdSchema });\nconst memberParams = tenantParams.extend({ accountId: permissionAccountId });\nconst access = requires(tenantAccess.tenant.permissions.manage_members, fromParam(\"tenantId\"));\n\nexport function tenantPermissionRoutes(tenants: Tenants) {\n return routeGroup(\"Tenant permissions\", [\n listRoute({\n route: permissionRosterRoute,\n summary: \"List accounts with membership in this tenant\",\n access,\n params: tenantParams,\n query: paginationQuerySchema,\n item: permissionMember,\n handler: async ({ params, query, subject }) => {\n const roster = await tenantRead(() => tenants.memberships.roster(subject.id, params.tenantId));\n const first = (query.page - 1) * query.perPage;\n return {\n items: roster.slice(first, first + query.perPage).map(({ accountId, role }) => ({ accountId, role })),\n total: roster.length,\n };\n },\n }),\n getRoute({\n route: memberPermissionsRoute,\n summary: \"Check a member's effective permissions for this tenant\",\n access,\n params: memberParams,\n response: memberPermissions,\n handler: ({ params, subject }) =>\n tenantRead(() => tenants.memberships.permissions(subject.id, params.tenantId, params.accountId)),\n }),\n ]);\n}\n\nasync function tenantRead<Result>(read: () => Promise<Result>): Promise<Result> {\n try {\n return await read();\n } catch (error) {\n if (error instanceof TenantUnavailableError) throw notFound(\"RESOURCE_NOT_FOUND\", \"Resource not found\");\n throw error;\n }\n}\n" },
|
|
91
94
|
{ path: "domains/tenants/server/plugin.ts", content: "import { definePlugin } from \"@dads-framework/core/plugin\";\nimport { starterServices } from \"../../../libraries/app-runtime/index.js\";\nimport { tenantInvitationRoutes } from \"./invitation-routes.js\";\nimport { tenantPermissionRoutes } from \"./permission-routes.js\";\nimport { tenantRoutes } from \"./routes.js\";\n\nexport const tenantsPlugin = definePlugin({\n name: \"tenant-routes\",\n requires: [starterServices],\n setup: ({ use }) => {\n const services = use(starterServices);\n return {\n routes: [...tenantRoutes(services.tenants), ...tenantInvitationRoutes(services)],\n };\n },\n});\n\nexport const tenantPermissionsPlugin = definePlugin({\n name: \"tenant-permissions-routes\",\n requires: [starterServices],\n setup: ({ use }) => ({\n routes: tenantPermissionRoutes(use(starterServices).tenants),\n }),\n});\n" },
|
|
@@ -104,7 +107,7 @@ export const kitStarterFiles = [
|
|
|
104
107
|
{ path: "examples/staff-impersonation.md", content: "# View a tenant as a member from the staff API\n\n## How the starter implements it\n\n[assembly/staff-impersonation-services.ts](../assembly/staff-impersonation-services.ts)\ncreates a Postgres-backed grant service and applies the configured tenant's\nSSO policy to the staff session. Its authorization callback checks the\noperator allowlist and the target account's current ability to view the\nworkspace. [domains/support/server/impersonation.ts](../domains/support/server/impersonation.ts)\nhandles the commands; [assembly/start-app.ts](../assembly/start-app.ts)\nmounts them on the staff API when enabled.\n\n<!-- dads:excerpt {\"path\":\"assembly/staff-impersonation-services.ts\",\"language\":\"ts\",\"from\":\" const staff = new Set(staffAccountIds);\",\"through\":\" return (await readTenantAsTarget(tenants, scope.effectiveAccountId, tenantId)) !== null;\"} -->\n\n## Try it\n\nRun the staff impersonation test from the generated project with Docker running:\n\n```sh\nnpm test -- tests/staff-impersonation.integration.test.ts\n```\n\n[The test](../tests/staff-impersonation.integration.test.ts) starts the\ncustomer and staff APIs with a temporary database. An approved staff\nsession receives HTTP 201 when it starts a grant. Viewing the tenant with\nthe grant returns HTTP 200 with both account IDs and the tenant. A second\nsession for that staff account gets HTTP 404. Stop the grant from its\noriginal session and the next view also gets HTTP 404. The audit entries\nrecord the authorized and denied attempts.\n\nSee [staff support impersonation](../DEPLOY.md#staff-support-impersonation)\nfor the configuration and request fields for a running app.\n" },
|
|
105
108
|
{ path: "examples/standalone-storage.ts", content: "import { createObjectStorage } from \"@dads-framework/object-storage\";\n\nconst storage = createObjectStorage({ driver: \"memory\" });\nawait storage.put(\"notes/hello.txt\", \"Hello from Dads\", \"text/plain\");\nconst note = await storage.get(\"notes/hello.txt\");\nif (note) process.stdout.write(new TextDecoder().decode(note.body) + \"\\n\");\n" },
|
|
106
109
|
{ path: "index.html", content: "<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <meta name=\"referrer\" content=\"same-origin\" />\n <title>Dads Workbench</title>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"module\" src=\"/apps/web/main.tsx\"></script>\n </body>\n</html>\n" },
|
|
107
|
-
{ path: "libraries/app-runtime/index.ts", content: "import type { Authorization, SubjectRef } from \"@dads-framework/access/runtime\";\nimport { actor, type PermissionToken } from \"@dads-framework/access\";\nimport type { GetEffectiveFeatureState } from \"@dads-framework/feature-flags\";\nimport type { Identity, IdentityEmail, IdentitySession } from \"@dads-framework/identity\";\nimport { jobQueueService, type JobQueue } from \"@dads-framework/job-queue/core\";\nimport type { ObjectStorage } from \"@dads-framework/object-storage/core\";\nimport { defineService } from \"@dads-framework/core/plugin\";\nimport { databaseService, type DrizzleHandle } from \"@dads-framework/postgres\";\nimport { createTenantAccess, type TenantId, type Tenants } from \"@dads-framework/identity/tenants\";\n\nexport { databaseService, jobQueueService };\n\nexport const account = actor(\"account\");\nexport const accountAccess = account;\nexport const tenantAccess = createTenantAccess(account);\n\ntype WriteTransaction =
|
|
110
|
+
{ path: "libraries/app-runtime/index.ts", content: "import type { Authorization, SubjectRef } from \"@dads-framework/access/runtime\";\nimport { actor, type PermissionToken } from \"@dads-framework/access\";\nimport type { AuditLogReader } from \"@dads-framework/audit\";\nimport type { GetEffectiveFeatureState } from \"@dads-framework/feature-flags\";\nimport type { Identity, IdentityEmail, IdentitySession } from \"@dads-framework/identity\";\nimport { jobQueueService, type JobQueue } from \"@dads-framework/job-queue/core\";\nimport type { ObjectStorage } from \"@dads-framework/object-storage/core\";\nimport { defineService } from \"@dads-framework/core/plugin\";\nimport { databaseService, type DrizzleHandle } from \"@dads-framework/postgres\";\nimport type { DrizzleTransaction } from \"@dads-framework/postgres-access\";\nimport { createTenantAccess, type TenantId, type Tenants } from \"@dads-framework/identity/tenants\";\n\nexport { databaseService, jobQueueService };\n\nexport const account = actor(\"account\");\nexport const accountAccess = account;\nexport const tenantAccess = createTenantAccess(account);\n\ntype WriteTransaction = DrizzleTransaction<DrizzleHandle>;\n\nexport type WriteWithPermission = <Result>(\n check: {\n readonly subject: SubjectRef;\n readonly permission: PermissionToken;\n readonly resourceId: string;\n },\n write: (transaction: WriteTransaction, authorization: Authorization) => Promise<Result>,\n) => Promise<Result>;\n\nexport type StarterServices = {\n readonly db: DrizzleHandle;\n readonly auditLogReader?: AuditLogReader;\n readonly authorization: Pick<Authorization, \"check\">;\n readonly files: ObjectStorage;\n readonly jobs: JobQueue;\n readonly writeWithPermission: WriteWithPermission;\n readonly identity: Identity;\n readonly readTenantSessionPolicy?: (headers: Headers) => Promise<{\n readonly session: IdentitySession;\n readonly allowsTenant: (tenantId: TenantId) => boolean;\n } | null>;\n readonly invitationOrigin: string;\n readonly enqueueTenantInvitation: (email: string, token: string) => Promise<void>;\n readonly flags: GetEffectiveFeatureState;\n readonly tenants: Tenants;\n};\n\nexport const starterServices = defineService(\"starter-services\").ofType<StarterServices>();\nexport const featureFlagsService = defineService(\"feature-flags\").ofType<GetEffectiveFeatureState>();\nexport const objectStorageService = defineService(\"object-storage\").ofType<ObjectStorage>();\nexport const protectedWriteService = defineService(\"protected-write\").ofType<WriteWithPermission>();\n\nexport type StarterEmail =\n | IdentityEmail\n | {\n readonly kind: \"tenant-invitation\";\n readonly to: string;\n readonly url: string;\n };\n\nexport type EnqueueStarterEmail = (message: StarterEmail) => Promise<void>;\n" },
|
|
108
111
|
{ path: "libraries/sign-in-options/index.ts", content: "import { defineRoute } from \"@dads-framework/core/contract\";\nimport { z } from \"zod\";\n\nexport const signInOptionsRoute = defineRoute(\"GET\", \"/sign-in-options\", () => \"/sign-in-options\");\n\nexport const signInOptions = z.strictObject({ enterpriseSso: z.boolean() });\n" },
|
|
109
112
|
{ path: "migrations/20261120080000_starter.migration.ts", content: "import {\n configureAuditTriggers,\n installAuditSchemaV1,\n} from \"@dads-framework/audit\";\nimport { installFeatureFlagSchemaV1 } from \"@dads-framework/feature-flags-postgres\";\nimport { installIdentitySchemaV1 } from \"@dads-framework/identity/better-auth\";\nimport { relationshipSchemaMigration } from \"@dads-framework/postgres-access\";\nimport {\n installTenantSchemaV1,\n tenantAuditConfiguration,\n} from \"@dads-framework/identity/tenants\";\nimport type { MigrationBuilder } from \"node-pg-migrate\";\n\nexport function up(pgm: MigrationBuilder): void {\n pgm.sql(relationshipSchemaMigration.sql);\n installIdentitySchemaV1(pgm);\n installTenantSchemaV1(pgm);\n installFeatureFlagSchemaV1(pgm);\n installAuditSchemaV1(pgm);\n pgm.sql(`\n CREATE TABLE starter_note (\n id uuid PRIMARY KEY,\n tenant_id uuid NOT NULL REFERENCES tenant(id),\n text text NOT NULL,\n CHECK (length(text) BETWEEN 1 AND 2000)\n );\n CREATE INDEX starter_note_tenant ON starter_note (tenant_id);\n `);\n configureAuditTriggers(pgm, {\n ...tenantAuditConfiguration,\n tables: {\n ...tenantAuditConfiguration.tables,\n starter_note: {\n keyColumns: [\"id\"],\n scopeColumns: { tenant_id: \"tenant_id\" },\n },\n },\n });\n}\n\n/** Bootstrap migrations only move forward. */\nexport const down = false;\n" },
|
|
110
113
|
{ path: "migrations/20261120080100_email_delivery.migration.ts", content: "import { installEmailDeliverySchemaV1 } from \"@dads-framework/email/delivery\";\nimport type { MigrationBuilder } from \"node-pg-migrate\";\n\nexport function up(pgm: MigrationBuilder): void {\n installEmailDeliverySchemaV1(pgm);\n}\n\nexport const down = false;\n" },
|
|
@@ -112,7 +115,7 @@ export const kitStarterFiles = [
|
|
|
112
115
|
{ path: "migrations/20261120080300_enterprise_identity.migration.ts", content: "import {\n installIdentityEnterpriseSsoSchema,\n installIdentitySigningKeyMetadataSchema,\n} from \"@dads-framework/identity/better-auth\";\nimport {\n installTenantScimGroupSchemaV1,\n installTenantScimSchemaV1,\n} from \"@dads-framework/identity/tenants\";\nimport type { MigrationBuilder } from \"node-pg-migrate\";\n\nexport function up(pgm: MigrationBuilder): void {\n installIdentitySigningKeyMetadataSchema(pgm);\n installIdentityEnterpriseSsoSchema(pgm);\n installTenantScimSchemaV1(pgm);\n installTenantScimGroupSchemaV1(pgm);\n}\n\n/** Keep provisioned users and enterprise session provenance on rollback. */\nexport const down = false;\n" },
|
|
113
116
|
{ path: "migrations/20261120080400_staff_impersonation.migration.ts", content: "import { installStaffImpersonationSchemaV1 } from \"@dads-framework/identity/better-auth/impersonation-store\";\nimport type { MigrationBuilder } from \"node-pg-migrate\";\n\nexport function up(pgm: MigrationBuilder): void {\n installStaffImpersonationSchemaV1(pgm);\n}\n\n/** Keep the staff impersonation audit trail on rollback. */\nexport const down = false;\n" },
|
|
114
117
|
{ path: "migrations/support/feature-flags.ts", content: "export { installFeatureFlagSchemaV1 } from \"@dads-framework/feature-flags/postgres\";\n" },
|
|
115
|
-
{ path: "package.json", content: "{\n \"name\": \"@dads-fixture/kit-workbench\",\n \"version\": \"0.
|
|
118
|
+
{ path: "package.json", content: "{\n \"name\": \"@dads-fixture/kit-workbench\",\n \"version\": \"0.6.0\",\n \"private\": true,\n \"type\": \"module\",\n \"engines\": {\n \"node\": \">=22.22\"\n },\n \"scripts\": {\n \"dev\": \"tsx watch assembly/main.ts\",\n \"start\": \"tsx assembly/main.ts\",\n \"migrate\": \"tsx assembly/migrate.ts\",\n \"typecheck\": \"tsc -p tsconfig.json --noEmit\",\n \"test\": \"vitest run --reporter=default --reporter=json --outputFile.json=node_modules/.dads/vitest-report.json\",\n \"verify\": \"npm run typecheck && npm test\",\n \"dev:web\": \"vite --host 127.0.0.1\",\n \"build:web\": \"vite build\",\n \"dev:up\": \"node assembly/dev.mjs up\",\n \"dev:down\": \"node assembly/dev.mjs down\",\n \"dev:mail\": \"node assembly/dev.mjs mail\",\n \"dev:status\": \"node assembly/dev.mjs status\",\n \"dev:restart\": \"node assembly/dev.mjs restart\",\n \"start:api\": \"tsx assembly/main.ts\",\n \"examples:setup\": \"node examples/setup.mjs\"\n },\n \"dependencies\": {\n \"@better-auth/core\": \"1.7.26\",\n \"@better-auth/sso\": \"1.7.26\",\n \"@dads-framework/access\": \"0.6.0\",\n \"@dads-framework/audit\": \"0.6.0\",\n \"@dads-framework/client\": \"0.6.0\",\n \"@dads-framework/core\": \"0.6.0\",\n \"@dads-framework/documents\": \"0.6.0\",\n \"@dads-framework/email\": \"0.6.0\",\n \"@dads-framework/feature-flags\": \"0.6.0\",\n \"@dads-framework/http\": \"0.6.0\",\n \"@dads-framework/identity\": \"0.6.0\",\n \"@dads-framework/job-queue\": \"0.6.0\",\n \"@dads-framework/object-storage\": \"0.6.0\",\n \"@dads-framework/postgres\": \"0.6.0\",\n \"@dads-framework/postgres-access\": \"0.6.0\",\n \"@dads-framework/spicedb-access\": \"0.6.0\",\n \"@dads-framework/ui\": \"0.6.0\",\n \"@opentelemetry/api\": \"^1.9.0\",\n \"@opentelemetry/exporter-trace-otlp-proto\": \"^0.222.0\",\n \"@opentelemetry/instrumentation\": \"^0.222.0\",\n \"@opentelemetry/instrumentation-http\": \"^0.222.0\",\n \"@opentelemetry/instrumentation-pg\": \"^0.74.0\",\n \"@opentelemetry/resources\": \"^2.11.0\",\n \"@opentelemetry/sdk-node\": \"^0.222.0\",\n \"@opentelemetry/sdk-trace\": \"^2.11.0\",\n \"@react-email/components\": \"^1.0.12\",\n \"@react-email/render\": \"^2.1.0\",\n \"better-auth\": \"1.7.26\",\n \"drizzle-orm\": \"^0.45.2\",\n \"kysely\": \"0.28.17\",\n \"node-pg-migrate\": \"^9.0.0\",\n \"pdfmake\": \"^0.3.11\",\n \"react\": \"^19.3.1\",\n \"react-dom\": \"^19.3.1\",\n \"tsx\": \"^4.20.5\",\n \"zod\": \"^4.4.3\"\n },\n \"devDependencies\": {\n \"@dads-framework/testing\": \"0.6.0\",\n \"@dads-framework/toolbox\": \"0.6.0\",\n \"@tailwindcss/vite\": \"^4.3.3\",\n \"@testcontainers/postgresql\": \"^12.0.4\",\n \"@types/node\": \"^24.3.0\",\n \"@types/react\": \"^19.3.0\",\n \"@types/react-dom\": \"^19.3.0\",\n \"marked\": \"15.0.12\",\n \"typescript\": \"6.0.3\",\n \"vite\": \"^8.2.2\",\n \"vitest\": \"^4.1.0\"\n }\n}\n" },
|
|
116
119
|
{ path: "tests/audit-export.test-support.ts", content: "import { expect } from \"vitest\";\nimport { z } from \"zod\";\n\nimport type { startApp } from \"../assembly/start-app.js\";\n\ntype Http = Awaited<ReturnType<typeof startApp>>;\n\nconst auditLine = z.object({\n position: z.int().positive(),\n tableName: z.string(),\n operation: z.enum([\"insert\", \"update\", \"delete\"]),\n});\n\ntype AuditProof = {\n readonly customer: Http;\n readonly staff: Http;\n readonly owner: Record<string, string>;\n readonly member: Record<string, string>;\n readonly tenantId: string;\n readonly otherTenantId: string;\n};\n\nexport async function proveAuditExport(proof: AuditProof) {\n const { customer, staff, owner, member, tenantId, otherTenantId } = proof;\n const url = `/api/tenants/${tenantId}/audit-log/export`;\n const betaNote = await customer.inject({\n method: \"POST\",\n url: `/api/tenants/${otherTenantId}/notes`,\n headers: member,\n payload: { text: \"Beta's private note\" },\n });\n expect(betaNote.statusCode).toBe(201);\n\n await proveAuditExportAccess(proof, url);\n await proveAuditExportPages(staff, url, owner, member);\n await proveAuditExportMetadata(staff, url, owner);\n}\n\nasync function proveAuditExportAccess({ customer, staff, owner, member, otherTenantId }: AuditProof, url: string) {\n expect((await staff.inject({ url })).statusCode).toBe(401);\n expect((await customer.inject({ url, headers: owner })).statusCode).toBe(404);\n const denied = await staff.inject({ url, headers: member });\n expect(denied.statusCode).toBe(404);\n expect(denied.headers[\"content-type\"]).toMatch(/^application\\/json/u);\n expect(\n (\n await staff.inject({\n url: `/api/tenants/${otherTenantId}/audit-log/export`,\n headers: owner,\n })\n ).statusCode,\n ).toBe(404);\n expect((await staff.inject({ url: `${url}?beforePosition=1`, headers: owner })).statusCode).toBe(400);\n}\n\nasync function proveAuditExportPages(\n staff: Http,\n url: string,\n owner: AuditProof[\"owner\"],\n member: AuditProof[\"member\"],\n) {\n const first = await staff.inject({\n url: `${url}?pageSize=1`,\n headers: owner,\n });\n expect(first.statusCode).toBe(200);\n expect(first.headers[\"content-type\"]).toMatch(/^application\\/x-ndjson\\b/u);\n expect(first.headers[\"cache-control\"]).toBe(\"no-store\");\n expect(first.headers[\"content-disposition\"]).toBe('attachment; filename=\"audit-log.ndjson\"');\n const link = first.headers[\"link\"];\n const next = /^<([^>]+)>; rel=\"next\"$/u.exec(typeof link === \"string\" ? link : \"\")?.[1];\n if (next === undefined) throw new Error(\"Expected a continuation link\");\n expect(next.startsWith(`${url}?`)).toBe(true);\n expect((await staff.inject({ url: next, headers: member })).statusCode).toBe(404);\n const nextPage = await staff.inject({ url: next, headers: owner });\n expect(nextPage.statusCode).toBe(200);\n expect(first.body).not.toBe(nextPage.body);\n}\n\nasync function proveAuditExportMetadata(staff: Http, url: string, owner: AuditProof[\"owner\"]) {\n const complete = await staff.inject({ url, headers: owner });\n expect(complete.statusCode).toBe(200);\n const audit = complete.body\n .trimEnd()\n .split(\"\\n\")\n .map((line) => auditLine.parse(JSON.parse(line)));\n expect(audit.filter(({ tableName }) => tableName === \"starter_note\")).toHaveLength(1);\n expect(complete.body).not.toContain(\"rowAfter\");\n expect(complete.body).not.toContain(\"Alpha's note\");\n expect(complete.body).not.toContain(\"Beta's private note\");\n}\n" },
|
|
117
120
|
{ path: "tests/dns-txt.test-support.ts", content: "import { createSocket, type Socket } from \"node:dgram\";\nimport { getServers, setServers } from \"node:dns/promises\";\nimport { syncBuiltinESMExports } from \"node:module\";\n\nconst loopback = \"127.0.0.1\";\nconst headerBytes = 12;\nconst txtIn = Buffer.from([0, 16, 0, 1]);\n\n/** Exercise actual TXT lookups from installed packages, including packed consumers. */\nexport async function withDnsTxtRecord<Result>(\n { name, value }: { name: string; value: string },\n run: () => Promise<Result>,\n): Promise<Result> {\n const question = encodeQuestion(name);\n const answer = encodeAnswer(value);\n const socket = createSocket(\"udp4\");\n socket.on(\"message\", (query, remote) => {\n if (!query.subarray(headerBytes, headerBytes + question.length).equals(question)) return;\n const header = Buffer.alloc(headerBytes);\n query.copy(header, 0, 0, 2); // Transaction ID.\n header.writeUInt16BE(0x8180, 2); // Successful response to a recursive query.\n header.writeUInt16BE(1, 4); // One question.\n header.writeUInt16BE(1, 6); // One answer.\n socket.send([header, question, answer], remote.port, remote.address);\n });\n\n const previousServers = getServers();\n try {\n await listen(socket);\n // setServers replaces the default resolver. Refresh resolved ESM imports\n // so packages that imported resolveTxt before the fixture use that resolver.\n replaceServers([`${loopback}:${String(socket.address().port)}`]);\n return await run();\n } finally {\n try {\n replaceServers(previousServers);\n } finally {\n await new Promise<void>((resolve) => socket.close(resolve));\n }\n }\n}\n\nfunction listen(socket: Socket): Promise<void> {\n return new Promise((resolve, reject) => {\n socket.once(\"error\", reject);\n socket.bind(0, loopback, () => {\n socket.off(\"error\", reject);\n resolve();\n });\n });\n}\n\nfunction encodeQuestion(name: string): Buffer {\n const labels = name.split(\".\").map((label) => Buffer.from(label, \"ascii\"));\n return Buffer.concat([\n ...labels.map((label) => Buffer.concat([Buffer.from([label.length]), label])),\n Buffer.from([0]),\n txtIn,\n ]);\n}\n\nfunction encodeAnswer(text: string): Buffer {\n const value = Buffer.from(text, \"utf8\");\n if (value.length > 255) throw new Error(\"The fixture TXT record is too long.\");\n const data = Buffer.concat([Buffer.from([value.length]), value]);\n const length = Buffer.alloc(2);\n length.writeUInt16BE(data.length);\n return Buffer.concat([\n Buffer.from([0xc0, headerBytes]), // Owner name points to the question.\n txtIn,\n Buffer.alloc(4), // Zero TTL.\n length,\n data,\n ]);\n}\n\nfunction replaceServers(servers: string[]): void {\n setServers(servers);\n syncBuiltinESMExports();\n}\n" },
|
|
118
121
|
{ path: "tests/enterprise-config.test.ts", content: "import { readEnterpriseConfiguration } from \"../assembly/enterprise-config.js\";\nimport { expect, it } from \"vitest\";\n\nit(\"ignores absent configuration and fails closed on incomplete configuration\", () => {\n expect(readEnterpriseConfiguration({})).toEqual({});\n expect(() => readEnterpriseConfiguration({ DADS_ENTERPRISE_SCIM: \"{}\" })).toThrow(\n \"Invalid DADS_ENTERPRISE_SCIM configuration.\",\n );\n expect(() =>\n readEnterpriseConfiguration({\n DADS_ENTERPRISE_SSO_PROVIDERS: \"private fixture text\",\n }),\n ).toThrow(/^Invalid DADS_ENTERPRISE_SSO_PROVIDERS configuration\\.$/u);\n});\n" },
|
|
@@ -128,6 +131,6 @@ export const kitStarterFiles = [
|
|
|
128
131
|
{ path: "tests/staff-impersonation.integration.test.ts", content: "import { connectPostgresClient } from \"@dads-framework/postgres\";\nimport { PostgreSqlContainer } from \"@testcontainers/postgresql\";\nimport { tenantIdSchema } from \"@dads-framework/identity/tenants\";\nimport { expect, it } from \"vitest\";\nimport { z } from \"zod\";\n\nimport { migrate } from \"../assembly/migrations.js\";\nimport { startApp } from \"../assembly/start-app.js\";\nimport type { StarterEmail } from \"../libraries/app-runtime/index.js\";\n\nconst origin = \"http://127.0.0.1:3000\";\nconst password = \"starter-test-password-1\";\nconst endpoint = \"/api/staff/impersonation\";\ntype Http = Awaited<ReturnType<typeof startApp>>;\n\nit(\"restricts and audits staff support across real sessions and named APIs\", { timeout: 90_000 }, async () => {\n const postgres = await new PostgreSqlContainer(\"postgres:16-alpine\").start();\n const apps: Http[] = [];\n try {\n const databaseUrl = postgres.getConnectionUri();\n await migrate(databaseUrl);\n const emails: StarterEmail[] = [];\n const config = {\n databaseUrl,\n baseUrl: origin,\n secret: \"fixture-signing-key-with-forty-characters\",\n enqueueEmail: (message: StarterEmail) => {\n emails.push(message);\n return Promise.resolve();\n },\n };\n const disabled = await startApp(\"staff\", config);\n apps.push(disabled);\n const operator = await createAccount(disabled, emails, \"operator\");\n const target = await createAccount(disabled, emails, \"target\");\n const outsider = await createAccount(disabled, emails, \"outsider\");\n const created = await disabled.inject({\n method: \"POST\",\n url: \"/api/tenants\",\n headers: { origin, cookie: target.cookie },\n payload: { name: \"Customer tenant\" },\n });\n expect(created.statusCode).toBe(201);\n const tenant = z.object({ data: z.object({ id: tenantIdSchema }) }).parse(created.json()).data;\n const enterprise = {\n staffImpersonation: {\n tenantId: tenant.id,\n staffAccountIds: [operator.id],\n revokerAccountIds: [outsider.id],\n },\n };\n const customer = await startApp(\"customer\", { ...config, enterprise });\n apps.push(customer);\n const staff = await startApp(\"staff\", { ...config, enterprise });\n apps.push(staff);\n const start = { action: \"start\", effectiveAccountId: target.id };\n expect((await command(disabled, operator.cookie, start)).statusCode).toBe(404);\n expect((await command(customer, operator.cookie, start)).statusCode).toBe(404);\n expect((await command(staff, undefined, start)).statusCode).toBe(404);\n expect((await command(staff, target.cookie, start)).statusCode).toBe(404);\n expect(\n (\n await command(staff, operator.cookie, {\n ...start,\n effectiveAccountId: outsider.id,\n })\n ).statusCode,\n ).toBe(404);\n expect(\n (\n await command(staff, operator.cookie, {\n ...start,\n tenantId: tenant.id,\n })\n ).statusCode,\n ).toBe(400);\n\n const crossOrigin = await staff.inject({\n method: \"POST\",\n url: endpoint,\n headers: {\n origin: \"https://elsewhere.example\",\n cookie: operator.cookie,\n },\n payload: start,\n });\n expect(crossOrigin.statusCode).toBe(403);\n\n const first = await issue(staff, operator.cookie, start);\n const view = { action: \"view-tenant\", grantId: first };\n const otherSession = await signIn(staff, \"operator\", \"198.51.100.2\");\n expect((await command(staff, otherSession, view)).statusCode).toBe(404);\n const viewed = await command(staff, operator.cookie, view);\n expect(viewed.statusCode).toBe(200);\n expect(viewed.headers[\"cache-control\"]).toBe(\"no-store\");\n expect(viewed.json()).toEqual({\n staffAccountId: operator.id,\n effectiveAccountId: target.id,\n tenant: { id: tenant.id, name: \"Customer tenant\" },\n });\n\n const ordinaryAccess = await customer.inject({\n url: `/api/tenants/${tenant.id}/notes`,\n headers: { origin, cookie: operator.cookie },\n });\n expect(ordinaryAccess.statusCode).toBe(404);\n\n const stop = { action: \"stop\", grantId: first };\n expect((await command(staff, otherSession, stop)).statusCode).toBe(404);\n expect((await command(staff, operator.cookie, stop)).statusCode).toBe(200);\n expect((await command(staff, operator.cookie, view)).statusCode).toBe(404);\n\n const second = await issue(staff, operator.cookie, start);\n const revoke = { action: \"revoke\", grantId: second };\n expect((await command(staff, operator.cookie, revoke)).statusCode).toBe(404);\n expect((await command(staff, outsider.cookie, revoke)).statusCode).toBe(200);\n expect((await command(staff, operator.cookie, { ...view, grantId: second })).statusCode).toBe(404);\n\n expect(await readAuditEvents(databaseUrl)).toEqual(\n expect.arrayContaining([\n audit(\"start\", \"authorized\", first, operator.id),\n audit(\"use\", \"authorized\", first, operator.id),\n audit(\"use\", \"denied\", first, operator.id),\n audit(\"stop\", \"authorized\", first, operator.id),\n audit(\"revoke\", \"authorized\", second, outsider.id),\n ]),\n );\n function audit(action: string, outcome: string, grantId: string, actorAccountId: string) {\n const event: unknown = expect.objectContaining({\n action,\n outcome,\n grantId,\n actorAccountId,\n staffAccountId: operator.id,\n effectiveAccountId: target.id,\n tenantId: tenant.id,\n });\n return { event };\n }\n } finally {\n await Promise.all(apps.map((app) => app.close()));\n await postgres.stop();\n }\n});\n\nasync function createAccount(app: Http, emails: StarterEmail[], name: string) {\n const email = `${name}@example.test`;\n const created = await app.inject({\n method: \"POST\",\n url: \"/api/auth/sign-up/email\",\n headers: { origin },\n payload: { email, name, password },\n });\n expect(created.statusCode).toBe(200);\n const verify = emails.find((entry) => entry.to === email && entry.kind === \"verify-email\");\n if (verify === undefined) throw new Error(\"Missing verification email.\");\n const link = new URL(verify.url);\n const verified = await app.inject({\n url: link.pathname + link.search,\n headers: { origin },\n });\n expect([200, 302]).toContain(verified.statusCode);\n const cookie = await signIn(app, name);\n const session = await app.inject({\n url: \"/api/auth/get-session\",\n headers: { origin, cookie },\n });\n const { account } = z.object({ account: z.object({ id: z.string() }) }).parse(session.json());\n return { id: account.id, cookie };\n}\n\nasync function signIn(app: Http, name: string, ip = \"198.51.100.1\") {\n const signedIn = await app.inject({\n method: \"POST\",\n url: \"/api/auth/sign-in/email\",\n headers: { origin, \"x-forwarded-for\": ip },\n payload: { email: `${name}@example.test`, password },\n });\n expect(signedIn.statusCode).toBe(200);\n const raw = signedIn.headers[\"set-cookie\"];\n const cookies = Array.isArray(raw) ? raw : [raw];\n const cookie = cookies.flatMap((value) => value?.split(\";\")[0] ?? []).join(\"; \");\n expect(cookie).not.toBe(\"\");\n return cookie;\n}\n\nfunction command(app: Http, cookie: string | undefined, payload: object) {\n return app.inject({\n method: \"POST\",\n url: endpoint,\n headers: { origin, ...(cookie === undefined ? {} : { cookie }) },\n payload,\n });\n}\n\nasync function issue(app: Http, cookie: string, payload: object) {\n const response = await command(app, cookie, payload);\n expect(response.statusCode).toBe(201);\n expect(response.headers[\"set-cookie\"]).toBeUndefined();\n return z.object({ id: z.uuid() }).parse(response.json()).id;\n}\n\nasync function readAuditEvents(databaseUrl: string) {\n const client = await connectPostgresClient(databaseUrl);\n try {\n const result = await client.query<{ event: unknown }>(\"SELECT event FROM identity_staff_impersonation_audit\");\n return result.rows;\n } finally {\n await client.end();\n }\n}\n" },
|
|
129
132
|
{ path: "tests/starter.integration.test.ts", content: "import { mkdtemp, readdir, readFile, rm } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { enterpriseSsoDomainChallenge } from \"@dads-framework/identity/better-auth\";\nimport { PostgreSqlContainer } from \"@testcontainers/postgresql\";\nimport { connectPostgresClient } from \"@dads-framework/postgres\";\nimport { expect, it, vi } from \"vitest\";\nimport { z } from \"zod\";\n\nimport { migrate } from \"../assembly/migrations.js\";\nimport { startApp } from \"../assembly/start-app.js\";\nimport { proveAuditExport } from \"./audit-export.test-support.js\";\nimport { withDnsTxtRecord } from \"./dns-txt.test-support.js\";\nimport { proveNoteArtifacts } from \"./note-artifacts.test-support.js\";\nimport { provePermissionsAfterInvite, provePermissionsBeforeInvite } from \"./permissions-dashboard.test-support.js\";\nimport type { StarterEmail } from \"../libraries/app-runtime/index.js\";\n\nconst origin = \"http://127.0.0.1:3000\";\nconst secret = \"fixture-signing-key-with-forty-characters\";\nconst password = \"starter-test-password-1\";\nconst responseId = z.object({ data: z.object({ id: z.uuid() }) });\ntype Http = Awaited<ReturnType<typeof startApp>>;\n\nfunction requestHeaders(cookie?: string) {\n return {\n origin,\n host: new URL(origin).host,\n ...(cookie === undefined ? {} : { cookie }),\n };\n}\n\nasync function createAccount(http: Http, emails: StarterEmail[], email: string) {\n const signUp = await http.inject({\n method: \"POST\",\n url: \"/api/auth/sign-up/email\",\n headers: requestHeaders(),\n payload: { email, password, name: email },\n });\n expect(signUp.statusCode).toBe(200);\n const mail = emails.find((message) => message.to === email && message.kind === \"verify-email\");\n if (mail === undefined) throw new Error(\"Verification email was not enqueued.\");\n const link = new URL(mail.url);\n const verified = await http.inject({\n method: \"GET\",\n url: link.pathname + link.search,\n headers: requestHeaders(),\n });\n expect([200, 302]).toContain(verified.statusCode);\n const session = await http.inject({\n method: \"POST\",\n url: \"/api/auth/sign-in/email\",\n headers: requestHeaders(),\n payload: { email, password },\n });\n expect(session.statusCode).toBe(200);\n const header = session.headers[\"set-cookie\"];\n const cookies = Array.isArray(header) ? header : [header];\n const cookie = cookies\n .map((value) => value?.split(\";\")[0])\n .filter(Boolean)\n .join(\"; \");\n expect(cookie.length).toBeGreaterThan(0);\n return cookie;\n}\n\nasync function createTenant(http: Http, cookie: string, name: string) {\n const response = await http.inject({\n method: \"POST\",\n url: \"/api/tenants\",\n headers: requestHeaders(cookie),\n payload: { name },\n });\n expect(response.statusCode).toBe(201);\n const parsed: unknown = JSON.parse(response.body);\n return responseId.parse(parsed).data.id;\n}\n\nit(\"migrates Postgres and isolates two signed-in tenants across named APIs\", { timeout: 90_000 }, async () => {\n const postgres = await new PostgreSqlContainer(\"postgres:16-alpine\").start();\n const state = await mkdtemp(join(tmpdir(), \"dads-starter-services-\"));\n try {\n const databaseUrl = postgres.getConnectionUri();\n await migrate(databaseUrl);\n await migrate(databaseUrl);\n await proveLocalMail(databaseUrl, join(state, \"mail\"));\n const emails: StarterEmail[] = [];\n const config = {\n databaseUrl,\n baseUrl: origin,\n fileStorageDirectory: join(state, \"files\"),\n secret,\n enqueueEmail: (message: StarterEmail) => {\n emails.push(message);\n return Promise.resolve();\n },\n };\n const customer = await startApp(\"customer\", {\n ...config,\n preparePermissionChecks: true,\n });\n const staff = await startApp(\"staff\", config);\n try {\n const alpha = await createAccount(customer, emails, \"alpha@example.test\");\n const beta = await createAccount(customer, emails, \"beta@example.test\");\n const alphaTenant = await createTenant(customer, alpha, \"Alpha\");\n const betaTenant = await createTenant(customer, beta, \"Beta\");\n const alphaNotes = `/api/tenants/${alphaTenant}/notes`;\n const betaNotes = `/api/tenants/${betaTenant}/notes`;\n\n const created = await customer.inject({\n method: \"POST\",\n url: alphaNotes,\n headers: requestHeaders(alpha),\n payload: { text: \"Alpha's note\" },\n });\n expect(created.statusCode).toBe(201);\n const noteId = responseId.parse(created.json()).data.id;\n await proveNoteArtifacts(customer, `${alphaNotes}/${noteId}`, requestHeaders(alpha), requestHeaders(beta));\n const alphaRead = await customer.inject({\n method: \"GET\",\n url: alphaNotes,\n headers: requestHeaders(alpha),\n });\n expect(alphaRead.statusCode).toBe(200);\n expect(alphaRead.body).toContain(\"Alpha's note\");\n const betaRead = await customer.inject({\n method: \"GET\",\n url: betaNotes,\n headers: requestHeaders(beta),\n });\n expect(betaRead.statusCode).toBe(200);\n expect(betaRead.body).not.toContain(\"Alpha's note\");\n expect(\n (\n await customer.inject({\n method: \"GET\",\n url: alphaNotes,\n headers: requestHeaders(beta),\n })\n ).statusCode,\n ).toBe(404);\n expect((await customer.inject({ method: \"GET\", url: alphaNotes })).statusCode).toBe(401);\n expect(\n (\n await staff.inject({\n method: \"GET\",\n url: alphaNotes,\n headers: requestHeaders(alpha),\n })\n ).statusCode,\n ).toBe(404);\n expect(\n (\n await customer.inject({\n method: \"GET\",\n url: alphaNotes + \"/features\",\n headers: requestHeaders(alpha),\n })\n ).statusCode,\n ).toBe(200);\n const betaAccount = await provePermissionsBeforeInvite(customer, betaTenant, beta, alpha, requestHeaders);\n await provePermissionsBeforeInvite(customer, alphaTenant, alpha, beta, requestHeaders);\n const crossTenantAccount = await customer.inject({\n method: \"GET\",\n url: `/api/tenants/${alphaTenant}/members/${encodeURIComponent(betaAccount)}/permissions`,\n headers: requestHeaders(alpha),\n });\n expect(crossTenantAccount.statusCode).toBe(404);\n await proveInvitation({\n customer,\n emails,\n issuerCookie: alpha,\n recipientCookie: beta,\n tenantId: alphaTenant,\n databaseUrl,\n config,\n });\n await provePermissionsAfterInvite(customer, alphaTenant, alpha, beta, requestHeaders);\n await proveAuditExport({\n customer,\n staff,\n owner: requestHeaders(alpha),\n member: requestHeaders(beta),\n tenantId: alphaTenant,\n otherTenantId: betaTenant,\n });\n } finally {\n await Promise.all([customer.close(), staff.close()]);\n }\n } finally {\n await postgres.stop();\n await rm(state, { recursive: true, force: true });\n }\n});\n\ntype InvitationProof = {\n readonly customer: Http;\n readonly emails: StarterEmail[];\n readonly issuerCookie: string;\n readonly recipientCookie: string;\n readonly tenantId: string;\n readonly databaseUrl: string;\n readonly config: Parameters<typeof startApp>[1];\n};\n\nasync function proveInvitation(proof: InvitationProof) {\n const { customer, issuerCookie, recipientCookie, tenantId, databaseUrl } = proof;\n const target = \"beta@example.test\";\n const issue = `/api/tenants/${tenantId}/invitations`;\n const denied = await customer.inject({\n method: \"POST\",\n url: issue,\n headers: requestHeaders(recipientCookie),\n payload: { email: target },\n });\n expect(denied.statusCode).toBe(404);\n\n const token = await invite(proof, target);\n expect((await accept(customer, token)).statusCode).toBe(401);\n expect((await accept(customer, token, issuerCookie)).statusCode).toBe(404);\n const wrongOrigin = await customer.inject({\n method: \"POST\",\n url: \"/api/tenants/invitations/accept\",\n headers: {\n ...requestHeaders(recipientCookie),\n origin: \"https://other.example.test\",\n },\n payload: { token },\n });\n expect(wrongOrigin.statusCode).toBe(403);\n\n await proveRequiredSsoInvitation(proof, token);\n\n const joined = await accept(customer, token, recipientCookie);\n expect(joined.statusCode).toBe(200);\n expect(joined.json()).toEqual({ data: { tenantId } });\n expect((await accept(customer, token, recipientCookie)).statusCode).toBe(404);\n\n const notes = await customer.inject({\n method: \"GET\",\n url: `/api/tenants/${tenantId}/notes`,\n headers: requestHeaders(recipientCookie),\n });\n expect(notes.statusCode).toBe(200);\n\n const expired = await invite(proof, target);\n const client = await connectPostgresClient(databaseUrl);\n try {\n await client.query(\n \"UPDATE tenant_invitation SET expires_at = now() - interval '1 second' WHERE tenant_id = $1 AND recipient_email = $2 AND accepted_at IS NULL\",\n [tenantId, target],\n );\n } finally {\n await client.end();\n }\n expect((await accept(customer, expired, recipientCookie)).statusCode).toBe(404);\n}\n\nasync function proveRequiredSsoInvitation(\n { config, recipientCookie, issuerCookie, tenantId }: InvitationProof,\n token: string,\n) {\n const domain = \"company.example.test\";\n const challenge = enterpriseSsoDomainChallenge(secret, tenantId, domain);\n const required = await withDnsTxtRecord(challenge, () =>\n startApp(\"customer\", {\n ...config,\n enterprise: {\n ssoProviders: [\n {\n id: \"sso-fixture\",\n tenantId,\n domain,\n mode: \"required\",\n protocol: \"oidc\",\n issuer: origin,\n clientId: \"fixture\",\n clientSecret: \"fixture-secret\",\n authorizationEndpoint: `${origin}/authorize`,\n tokenEndpoint: `${origin}/token`,\n jwksEndpoint: `${origin}/keys`,\n },\n ],\n },\n }),\n );\n try {\n const owner = await required.inject({\n url: `/api/tenants/${tenantId}/notes`,\n headers: requestHeaders(issuerCookie),\n });\n expect(owner.statusCode).toBe(401);\n expect((await accept(required, token, recipientCookie)).statusCode).toBe(404);\n } finally {\n await required.close();\n }\n}\n\nasync function invite({ customer, emails, issuerCookie, tenantId }: InvitationProof, email: string) {\n const response = await customer.inject({\n method: \"POST\",\n url: `/api/tenants/${tenantId}/invitations`,\n headers: requestHeaders(issuerCookie),\n payload: { email },\n });\n expect(response.statusCode).toBe(201);\n const body: unknown = response.json();\n z.strictObject({\n data: z.strictObject({ expiresAt: z.iso.datetime() }),\n }).parse(body);\n const message = emails.findLast((mail) => mail.kind === \"tenant-invitation\" && mail.to === email);\n if (message === undefined) throw new Error(\"Expected a tenant invitation email.\");\n const link = new URL(message.url);\n expect(link.search).toBe(\"\");\n const token = new URLSearchParams(link.hash.slice(1)).get(\"token\");\n if (token === null) throw new Error(\"Expected the token in the URL fragment.\");\n return token;\n}\n\nfunction accept(customer: Http, token: string, cookie?: string) {\n return customer.inject({\n method: \"POST\",\n url: \"/api/tenants/invitations/accept\",\n headers: requestHeaders(cookie),\n payload: { token },\n });\n}\n\nasync function proveLocalMail(databaseUrl: string, directory: string): Promise<void> {\n const app = await startApp(\"customer\", {\n databaseUrl,\n baseUrl: origin,\n secret,\n mailSpoolDirectory: directory,\n });\n try {\n const signup = await app.inject({\n method: \"POST\",\n url: \"/api/auth/sign-up/email\",\n headers: requestHeaders(),\n payload: {\n email: \"local-mail@example.test\",\n password,\n name: \"Local mail\",\n },\n });\n expect(signup.statusCode).toBe(200);\n await vi.waitFor(async () => {\n const message = (await readdir(directory)).find((file) => file.endsWith(\".json\"));\n if (!message) throw new Error(\"Expected a verification message in the local spool.\");\n const envelope = await readFile(join(directory, message), \"utf8\");\n expect(envelope).toContain(\"local-mail@example.test\");\n expect(envelope).toContain(\"/api/auth/verify-email\");\n });\n } finally {\n await app.close();\n }\n}\n" },
|
|
130
133
|
{ path: "tsconfig.json", content: "{\n \"compilerOptions\": {\n \"target\": \"ES2023\",\n \"lib\": [\"ES2023\", \"DOM\", \"DOM.Iterable\"],\n \"module\": \"NodeNext\",\n \"jsx\": \"react-jsx\",\n \"moduleResolution\": \"NodeNext\",\n \"paths\": {\n \"@dads-framework/feature-flags-postgres\": [\"./migrations/support/feature-flags.ts\"]\n },\n \"strict\": true,\n \"noUncheckedIndexedAccess\": true,\n \"exactOptionalPropertyTypes\": true,\n \"noImplicitOverride\": true,\n \"noImplicitReturns\": true,\n \"noFallthroughCasesInSwitch\": true,\n \"noPropertyAccessFromIndexSignature\": true,\n \"useUnknownInCatchVariables\": true,\n \"verbatimModuleSyntax\": true,\n \"skipLibCheck\": true,\n \"types\": [\"node\", \"vite/client\"]\n },\n \"include\": [\n \"apps/**/*.ts\",\n \"apps/**/*.tsx\",\n \"assembly/**/*.ts\",\n \"domains/**/*.ts\",\n \"libraries/**/*.ts\",\n \"migrations/**/*.ts\",\n \"tests/**/*.ts\",\n \"vite.config.ts\"\n ]\n}\n" },
|
|
131
|
-
{ path: "vite.config.ts", content: "import { readFile, readdir } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join, posix, resolve } from \"node:path\";\nimport tailwindcss from \"@tailwindcss/vite\";\nimport { defineConfig, type Plugin } from \"vite\";\nimport { bundledExamplesPage } from \"./assembly/examples-page.js\";\n\nconst apiTarget = process.env[\"DADS_DEV_API_URL\"] ?? \"http://127.0.0.1:3000\";\n\nasync function installedNotices() {\n const require = createRequire(import.meta.url);\n const styles = require.resolve(\"@dads-framework/ui/styles/fonts.css\");\n const resolveFromStyles = createRequire(styles);\n const fonts = [\"ibm-plex-sans\", \"ibm-plex-mono\"].map((font) => ({\n fileName: `licenses/${font}.txt`,\n source: join(dirname(resolveFromStyles.resolve(`@fontsource/${font}`)), \"LICENSE\"),\n }));\n const ui = resolve(dirname(require.resolve(\"@dads-framework/ui/elements\")), \"../..\");\n const uiLicenses = await readdir(join(ui, \"third-party-licenses\"));\n const uiNotices = [\"THIRD_PARTY_NOTICES.md\", ...uiLicenses.map((name) => posix.join(\"third-party-licenses\", name))];\n return [\n ...fonts,\n ...uiNotices.map((name) => ({\n fileName: `licenses/dads-ui/${name}`,\n source: join(ui, name),\n })),\n ];\n}\n\n// The browser build redistributes font binaries and adapted UI source notices.\nfunction bundledAssetLicenses(): Plugin {\n return {\n name: \"workbench-asset-licenses\",\n apply: \"build\",\n async generateBundle() {\n for (const notice of await installedNotices()) {\n this.emitFile({\n type: \"asset\",\n fileName: notice.fileName,\n source: await readFile(notice.source),\n });\n }\n },\n };\n}\n\nexport default defineConfig({\n plugins: [tailwindcss(), bundledAssetLicenses(), bundledExamplesPage()],\n build: {\n license: { fileName: \"THIRD_PARTY_LICENSES.md\" },\n rolldownOptions: {\n input: { workbench: \"index.html\", examples: \"examples.html\" },\n },\n },\n server: {\n strictPort: true,\n fs: {\n // Keep Vite's default denials and protect the local example sessions.\n deny: [\".env\", \".env.*\", \"*.{crt,pem,key,p12,pfx,cer,der}\", \".npmrc\", \".yarnrc.yml\", \"**/.git/**\", \"**/.dads/**\"],\n },\n proxy: { \"/api\": { target: apiTarget } },\n },\n preview: {\n proxy: { \"/api\": { target: apiTarget } },\n },\n});\n" },
|
|
134
|
+
{ path: "vite.config.ts", content: "import { readFile, readdir } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join, posix, resolve } from \"node:path\";\nimport tailwindcss from \"@tailwindcss/vite\";\nimport { defineConfig, type Plugin } from \"vite\";\nimport { bundledExamplesPage } from \"./assembly/examples-page.js\";\n\nconst apiTarget = process.env[\"DADS_DEV_API_URL\"] ?? \"http://127.0.0.1:3000\";\n\nasync function installedNotices() {\n const require = createRequire(import.meta.url);\n const styles = require.resolve(\"@dads-framework/ui/styles/fonts.css\");\n const resolveFromStyles = createRequire(styles);\n const fonts = [\"ibm-plex-sans\", \"ibm-plex-mono\"].map((font) => ({\n fileName: `licenses/${font}.txt`,\n source: join(dirname(resolveFromStyles.resolve(`@fontsource/${font}`)), \"LICENSE\"),\n }));\n const ui = resolve(dirname(require.resolve(\"@dads-framework/ui/elements\")), \"../..\");\n const uiLicenses = await readdir(join(ui, \"third-party-licenses\"));\n const uiNotices = [\"THIRD_PARTY_NOTICES.md\", ...uiLicenses.map((name) => posix.join(\"third-party-licenses\", name))];\n return [\n ...fonts,\n ...uiNotices.map((name) => ({\n fileName: `licenses/dads-ui/${name}`,\n source: join(ui, name),\n })),\n ];\n}\n\n// The browser build redistributes font binaries and adapted UI source notices.\nfunction bundledAssetLicenses(): Plugin {\n return {\n name: \"workbench-asset-licenses\",\n apply: \"build\",\n async generateBundle() {\n for (const notice of await installedNotices()) {\n this.emitFile({\n type: \"asset\",\n fileName: notice.fileName,\n source: await readFile(notice.source),\n });\n }\n },\n };\n}\n\nexport default defineConfig({\n plugins: [tailwindcss(), bundledAssetLicenses(), bundledExamplesPage()],\n build: {\n license: { fileName: \"THIRD_PARTY_LICENSES.md\" },\n rolldownOptions: {\n input: { workbench: \"index.html\", examples: \"examples.html\" },\n onwarn(warning, warn) {\n if (warning.code === \"MODULE_LEVEL_DIRECTIVE\" && warning.message.includes(\"use client\")) {\n return;\n }\n warn(warning);\n },\n },\n },\n server: {\n strictPort: true,\n fs: {\n // Keep Vite's default denials and protect the local example sessions.\n deny: [\".env\", \".env.*\", \"*.{crt,pem,key,p12,pfx,cer,der}\", \".npmrc\", \".yarnrc.yml\", \"**/.git/**\", \"**/.dads/**\"],\n },\n proxy: { \"/api\": { target: apiTarget } },\n },\n preview: {\n proxy: { \"/api\": { target: apiTarget } },\n },\n});\n" },
|
|
132
135
|
];
|
|
133
136
|
//# sourceMappingURL=kit-starter.generated.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"kit-starter.generated.js","sourceRoot":"","sources":["../../src/starter-project/kit-starter.generated.ts"],"names":[],"mappings":"AAAA,mDAAmD;AACnD,kBAAkB;AAClB,MAAM,CAAC,MAAM,eAAe,GAAG;IAC7B,EAAE,IAAI,EAAE,oCAAoC,EAAE,OAAO,EAAE,wYAAwY,EAAE;IACjc,EAAE,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,kEAAkE,EAAE;IACnG,EAAE,IAAI,EAAE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AE,0jBAA0jB,EAAE;IACxnB,EAAE,IAAI,EAAE,iCAAiC,EAAE,OAAO,EAAE,y3CAAy3C,EAAE;IAC/6C,EAAE,IAAI,EAAE,wBAAwB,EAAE,OAAO,EAAE,w5EAAw5E,EAAE;IACr8E,EAAE,IAAI,EAAE,4BAA4B,EAAE,OAAO,EAAE,sxEAAsxE,EAAE;IACv0E,EAAE,IAAI,EAAE,0BAA0B,EAAE,OAAO,EAAE,6tDAA6tD,EAAE;IAC5wD,EAAE,IAAI,EAAE,kBAAkB,EAAE,OAAO,EAAE,w9DAAw9D,EAAE;IAC//D,EAAE,IAAI,EAAE,qBAAqB,EAAE,OAAO,EAAE,4IAA4I,EAAE;IACtL,EAAE,IAAI,EAAE,wBAAwB,EAAE,OAAO,EAAE,otBAAotB,EAAE;IACjwB,EAAE,IAAI,EAAE,mBAAmB,EAAE,OAAO,EAAE,waAAwa,EAAE;IAChd,EAAE,IAAI,EAAE,6BAA6B,EAAE,OAAO,EAAE,42CAA42C,EAAE;IAC95C,EAAE,IAAI,EAAE,8BAA8B,EAAE,OAAO,EAAE,gwDAAgwD,EAAE;IACnzD,EAAE,IAAI,EAAE,qCAAqC,EAAE,OAAO,EAAE,+nHAA+nH,EAAE;IACzrH,EAAE,IAAI,EAAE,kBAAkB,EAAE,OAAO,EAAE,qkDAAqkD,EAAE;IAC5mD,EAAE,IAAI,EAAE,sBAAsB,EAAE,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"kit-starter.generated.js","sourceRoot":"","sources":["../../src/starter-project/kit-starter.generated.ts"],"names":[],"mappings":"AAAA,mDAAmD;AACnD,kBAAkB;AAClB,MAAM,CAAC,MAAM,eAAe,GAAG;IAC7B,EAAE,IAAI,EAAE,oCAAoC,EAAE,OAAO,EAAE,wYAAwY,EAAE;IACjc,EAAE,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,kEAAkE,EAAE;IACnG,EAAE,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,m+EAAm+E,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AAE,IAAI,EAAE,gBAAgB,EAAE,OAAO,EAAE,gmFAAgmF,EAAE;CACtoF,CAAC"}
|
|
@@ -95,7 +95,7 @@ function starterMigrationFile() {
|
|
|
95
95
|
installAuditSchemaV1,
|
|
96
96
|
} from "@dads-framework/audit";
|
|
97
97
|
import { installFeatureFlagSchemaV1 } from "@dads-framework/feature-flags-postgres";
|
|
98
|
-
import {
|
|
98
|
+
import { installIdentitySchemaV2 } from "@dads-framework/identity/better-auth";
|
|
99
99
|
import { relationshipSchemaMigration } from "@dads-framework/postgres-access";
|
|
100
100
|
import {
|
|
101
101
|
installTenantSchemaV1,
|
|
@@ -105,7 +105,7 @@ import type { MigrationBuilder } from "node-pg-migrate";
|
|
|
105
105
|
|
|
106
106
|
export function up(pgm: MigrationBuilder): void {
|
|
107
107
|
pgm.sql(relationshipSchemaMigration.sql);
|
|
108
|
-
|
|
108
|
+
installIdentitySchemaV2(pgm);
|
|
109
109
|
installTenantSchemaV1(pgm);
|
|
110
110
|
installFeatureFlagSchemaV1(pgm);
|
|
111
111
|
installAuditSchemaV1(pgm);
|
|
@@ -344,6 +344,15 @@ export default defineConfig({
|
|
|
344
344
|
license: { fileName: "THIRD_PARTY_LICENSES.md" },
|
|
345
345
|
rolldownOptions: {
|
|
346
346
|
input: { workbench: "index.html" },
|
|
347
|
+
onwarn(warning, warn) {
|
|
348
|
+
if (
|
|
349
|
+
warning.code === "MODULE_LEVEL_DIRECTIVE" &&
|
|
350
|
+
warning.message.includes("use client")
|
|
351
|
+
) {
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
warn(warning);
|
|
355
|
+
},
|
|
347
356
|
},
|
|
348
357
|
},
|
|
349
358
|
server: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"minimal-project-workbench.js","sourceRoot":"","sources":["../../src/starter-project/minimal-project-workbench.ts"],"names":[],"mappings":"AAEA,+EAA+E;AAC/E,MAAM,UAAU,2BAA2B;IACzC,OAAO,CAAC,iBAAiB,EAAE,EAAE,qBAAqB,EAAE,EAAE,cAAc,EAAE,CAAC,CAAC;AAC1E,CAAC;AAED,SAAS,iBAAiB;IACxB,OAAO;QACL,IAAI,EAAE,wBAAwB;QAC9B,OAAO,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6IZ;KACE,CAAC;AACJ,CAAC;AAED,SAAS,qBAAqB;IAC5B,OAAO;QACL,IAAI,EAAE,iCAAiC;QACvC,OAAO,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8HZ;KACE,CAAC;AACJ,CAAC;AAED,SAAS,cAAc;IACrB,OAAO;QACL,IAAI,EAAE,gBAAgB;QACtB,OAAO,EAAE
|
|
1
|
+
{"version":3,"file":"minimal-project-workbench.js","sourceRoot":"","sources":["../../src/starter-project/minimal-project-workbench.ts"],"names":[],"mappings":"AAEA,+EAA+E;AAC/E,MAAM,UAAU,2BAA2B;IACzC,OAAO,CAAC,iBAAiB,EAAE,EAAE,qBAAqB,EAAE,EAAE,cAAc,EAAE,CAAC,CAAC;AAC1E,CAAC;AAED,SAAS,iBAAiB;IACxB,OAAO;QACL,IAAI,EAAE,wBAAwB;QAC9B,OAAO,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6IZ;KACE,CAAC;AACJ,CAAC;AAED,SAAS,qBAAqB;IAC5B,OAAO;QACL,IAAI,EAAE,iCAAiC;QACvC,OAAO,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8HZ;KACE,CAAC;AACJ,CAAC;AAED,SAAS,cAAc;IACrB,OAAO;QACL,IAAI,EAAE,gBAAgB;QACtB,OAAO,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0FZ;KACE,CAAC;AACJ,CAAC"}
|
|
@@ -4,7 +4,7 @@ import { renderMinimalDocsAndTestFiles } from "./minimal-project-docs-and-tests.
|
|
|
4
4
|
import { renderMinimalServerFiles } from "./minimal-project-server.js";
|
|
5
5
|
import { renderMinimalWebFiles } from "./minimal-project-web.js";
|
|
6
6
|
import { renderMinimalWorkbenchFiles } from "./minimal-project-workbench.js";
|
|
7
|
-
import { renderStarterVerificationFiles } from "./render-starter-verification-files.js";
|
|
7
|
+
import { renderStarterVerificationFiles, withStarterScriptsPackage } from "./render-starter-verification-files.js";
|
|
8
8
|
const PROJECT_NAME_PATTERN = /^[a-z0-9][a-z0-9._-]*$/;
|
|
9
9
|
/** Explicit allowlist of shared framework files copied from the kit starter. */
|
|
10
10
|
const KEPT_BASE_PATHS = new Set([
|
|
@@ -116,7 +116,7 @@ function minimalPackageManifest(content, projectName) {
|
|
|
116
116
|
return `${JSON.stringify(next, null, 2)}\n`;
|
|
117
117
|
}
|
|
118
118
|
function minimalProjectManifest(content) {
|
|
119
|
-
const parsed = JSON.parse(content);
|
|
119
|
+
const parsed = JSON.parse(withStarterScriptsPackage(content));
|
|
120
120
|
if (!isRecord(parsed) || !Array.isArray(parsed["packages"])) {
|
|
121
121
|
throw new Error("Starter dads.project.json must declare packages.");
|
|
122
122
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"render-minimal-project.js","sourceRoot":"","sources":["../../src/starter-project/render-minimal-project.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC9C,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,6BAA6B,EAAE,MAAM,qCAAqC,CAAC;AACpF,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AACvE,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EAAE,2BAA2B,EAAE,MAAM,gCAAgC,CAAC;AAE7E,OAAO,EAAE,8BAA8B,EAAE,MAAM,wCAAwC,CAAC;
|
|
1
|
+
{"version":3,"file":"render-minimal-project.js","sourceRoot":"","sources":["../../src/starter-project/render-minimal-project.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC9C,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,6BAA6B,EAAE,MAAM,qCAAqC,CAAC;AACpF,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AACvE,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EAAE,2BAA2B,EAAE,MAAM,gCAAgC,CAAC;AAE7E,OAAO,EAAE,8BAA8B,EAAE,yBAAyB,EAAE,MAAM,wCAAwC,CAAC;AAEnH,MAAM,oBAAoB,GAAG,wBAAwB,CAAC;AAEtD,gFAAgF;AAChF,MAAM,eAAe,GAAG,IAAI,GAAG,CAAS;IACtC,oCAAoC;IACpC,YAAY;IACZ,WAAW;IACX,WAAW;IACX,qBAAqB;IACrB,yBAAyB;IACzB,qBAAqB;IACrB,uBAAuB;IACvB,6BAA6B;IAC7B,sBAAsB;IACtB,oBAAoB;IACpB,+BAA+B;IAC/B,sBAAsB;IACtB,kBAAk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,CAAC,kBAAkB,CAAC,CAAC;SACpD,IAAI,CAAC,IAAI,CAAC;SACV,OAAO,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;AAC/B,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc,EAAE,QAA6B;IAC7D,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC;IAChC,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;AACzF,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"render-starter-project.d.ts","sourceRoot":"","sources":["../../src/starter-project/render-starter-project.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,qCAAqC,CAAC;AAK/E,MAAM,MAAM,kBAAkB,GAAG;IAC/B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,UAAU,CAAC,EAAE,IAAI,CAAC;CAC5B,CAAC;AAEF,kFAAkF;AAClF,wBAAgB,yBAAyB,CAAC,OAAO,EAAE;IACjD,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,QAAQ,CAAC,EAAE,mBAAmB,CAAC;CACzC,GAAG,SAAS,kBAAkB,EAAE,
|
|
1
|
+
{"version":3,"file":"render-starter-project.d.ts","sourceRoot":"","sources":["../../src/starter-project/render-starter-project.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,qCAAqC,CAAC;AAK/E,MAAM,MAAM,kBAAkB,GAAG;IAC/B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,UAAU,CAAC,EAAE,IAAI,CAAC;CAC5B,CAAC;AAEF,kFAAkF;AAClF,wBAAgB,yBAAyB,CAAC,OAAO,EAAE;IACjD,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,QAAQ,CAAC,EAAE,mBAAmB,CAAC;CACzC,GAAG,SAAS,kBAAkB,EAAE,CAmChC"}
|