From c7e2160b10ecce055285bd3f1ca60f7d89ed39ea Mon Sep 17 00:00:00 2001 From: mihir Date: Tue, 29 Sep 2026 00:30:05 +0530 Subject: [PATCH 1/3] feat(production): track batches against active BOM revisions --- README.md | 1 + docs/production-batches-api.md | 18 ++ docs/roadmap.md | 1 + prisma/bom.prisma | 1 + prisma/migration-checksums.json | 3 +- .../migration.sql | 95 +++++++ prisma/production.prisma | 57 +++++ prisma/schema.prisma | 6 + src/app.module.ts | 2 + src/common/errors/commerce-errors.ts | 55 +++++ src/identity/permissions.ts | 2 + src/production/batch-quantity.ts | 18 ++ src/production/batch.schemas.ts | 45 ++++ src/production/batch.store.ts | 212 ++++++++++++++++ src/production/batches.controller.ts | 87 +++++++ src/production/production.module.ts | 12 + test/batch-quantity.spec.ts | 14 ++ test/production-batches.spec.ts | 232 ++++++++++++++++++ 18 files changed, 860 insertions(+), 1 deletion(-) create mode 100644 docs/production-batches-api.md create mode 100644 prisma/migrations/20260928183508_production_batches/migration.sql create mode 100644 prisma/production.prisma create mode 100644 src/production/batch-quantity.ts create mode 100644 src/production/batch.schemas.ts create mode 100644 src/production/batch.store.ts create mode 100644 src/production/batches.controller.ts create mode 100644 src/production/production.module.ts create mode 100644 test/batch-quantity.spec.ts create mode 100644 test/production-batches.spec.ts diff --git a/README.md b/README.md index d979b44..6b18704 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ Phase 2D adds [supplier invoice matching and voids](docs/supplier-invoices-api.m Phase 2E adds [supplier payment records and reversals](docs/supplier-payments-api.md). Material stock movements and production remain later milestones. Phase 2F adds [private versioned supplier documents and review](docs/supplier-documents-api.md). Phase 2G adds [versioned product bills of materials](docs/bom-api.md). +Phase 2H adds [production batches](docs/production-batches-api.md). ### Swagger UI diff --git a/docs/production-batches-api.md b/docs/production-batches-api.md new file mode 100644 index 0000000..1b639f3 --- /dev/null +++ b/docs/production-batches-api.md @@ -0,0 +1,18 @@ +# Production batches (Phase 2H) + +A batch records a planned number of finished pieces against one active BOM revision. Creation requires an active product variant and a planned quantity divisible by the BOM yield. The response includes planned material quantities scaled with exact decimal arithmetic from the immutable BOM lines. If that BOM is later superseded, the batch retains its original revision. + +| Method | Path | Permission | Purpose | +| ------ | -------------------------------------------------------------- | ------------------- | --------------------------------------------- | +| GET | `/api/v1/production-batches?status=&variantId=&limit=&offset=` | `production.read` | List scoped batch metadata | +| GET | `/api/v1/production-batches/:id` | `production.read` | Read batch, BOM, planned materials and events | +| POST | `/api/v1/production-batches` | `production.manage` | Create a draft | +| POST | `/api/v1/production-batches/:id/start` | `production.manage` | Start a draft | +| POST | `/api/v1/production-batches/:id/complete` | `production.manage` | Record good and rejected output | +| POST | `/api/v1/production-batches/:id/cancel` | `production.manage` | Cancel a draft or started batch | + +Create body: `{ "bomId": "", "reference": "BATCH-001", "plannedQuantity": 20, "scheduledDate": "2026-10-01" }`. The date is optional. References are unique per organization, uppercase and at most 32 characters. Planned quantity is 1–100,000 pieces. + +Completion body: `{ "goodQuantity": 18, "rejectedQuantity": 2, "rejectionReason": "Surface defects" }`. Good and rejected quantities must total the plan. A nonzero rejected quantity requires a reason. Cancellation body: `{ "reason": "Production halted" }`. + +The permitted lifecycle is `DRAFT → IN_PROGRESS → COMPLETED` or `DRAFT/IN_PROGRESS → CANCELLED`. Every transition is audited. Completion and cancellation records are immutable. Database checks and triggers enforce state transitions, event reconciliation, organization scope and unique references. A batch does **not** adjust finished-goods stock or consume material; those require stock-location, consumption and QC decisions in later milestones. diff --git a/docs/roadmap.md b/docs/roadmap.md index 06996b5..ffa82a9 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -21,6 +21,7 @@ Suppliers, material/urli classification and compatibility, procurement, purchase - 2E (implemented): external supplier payment records, partial balances, idempotent retries, and auditable reversals. Bank reconciliation and proof documents remain separate milestones. - 2F (implemented): private PDF versions for supplier documents, independent validation, and gated downloads. Retention and malware scanning remain deployment decisions. - 2G (implemented): versioned, organization-scoped product BOM drafts and activation with material snapshots. Production batches, consumption, wastage, packaging BOM and costing remain later milestones. +- 2H (implemented): production batch planning, lifecycle, yield reconciliation and immutable completion/cancellation records. Material consumption, stock posting, wastage, packaging BOM and costing remain later milestones. ## Phase 3: B2B and white label diff --git a/prisma/bom.prisma b/prisma/bom.prisma index 19873de..f109d48 100644 --- a/prisma/bom.prisma +++ b/prisma/bom.prisma @@ -18,6 +18,7 @@ model ProductBom { variant ProductVariant @relation(fields: [variantId, organizationId], references: [id, organizationId], onDelete: Restrict) createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict) lines ProductBomLine[] + batches ProductionBatch[] @@unique([variantId, revision]) @@unique([id, organizationId]) @@index([organizationId, variantId, createdAt, id]) diff --git a/prisma/migration-checksums.json b/prisma/migration-checksums.json index c3c78ba..4e740f1 100644 --- a/prisma/migration-checksums.json +++ b/prisma/migration-checksums.json @@ -20,5 +20,6 @@ "20260928130714_supplier_invoices": "63945cff1725929e90fe73ade79348480e04a36976dbdb2a021a574569c35049", "20260928145745_supplier_payments": "012ff1c33c1afa8e6fd883925616f014e7cfdac258fac37ac2ae56739e95bf6d", "20260928151912_supplier_documents": "65ec974aa6bd0e8f85dc0dbde00f5ef5d9ab81811aba17d89299b6464d4ee6c1", - "20260928153219_product_boms": "b548e6e5c2f11b52374ba0ad3eedbc127244b2752f07cdcd8bf951641d4525a1" + "20260928153219_product_boms": "b548e6e5c2f11b52374ba0ad3eedbc127244b2752f07cdcd8bf951641d4525a1", + "20260928183508_production_batches": "53b3fbabe17d3270ae3c5d74393a07abb28858ca2af8d3a1aa19c92686c84a0a" } diff --git a/prisma/migrations/20260928183508_production_batches/migration.sql b/prisma/migrations/20260928183508_production_batches/migration.sql new file mode 100644 index 0000000..20b3481 --- /dev/null +++ b/prisma/migrations/20260928183508_production_batches/migration.sql @@ -0,0 +1,95 @@ +CREATE TYPE "ProductionBatchStatus" AS ENUM ('DRAFT', 'IN_PROGRESS', 'COMPLETED', 'CANCELLED'); + +CREATE TABLE "production_batches" ( + "id" UUID NOT NULL, + "organization_id" UUID NOT NULL, + "bom_id" UUID NOT NULL, + "created_by_id" UUID NOT NULL, + "reference" VARCHAR(32) NOT NULL, + "planned_quantity" INTEGER NOT NULL, + "status" "ProductionBatchStatus" NOT NULL DEFAULT 'DRAFT', + "scheduled_date" DATE, + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "started_at" TIMESTAMPTZ(3), + CONSTRAINT "production_batches_pkey" PRIMARY KEY ("id"), + CONSTRAINT "production_batches_values" CHECK ("reference" ~ '^[A-Z0-9][A-Z0-9_-]{0,31}$' AND "planned_quantity" BETWEEN 1 AND 100000), + CONSTRAINT "production_batches_started" CHECK (("status" = 'DRAFT' AND "started_at" IS NULL) OR ("status" IN ('IN_PROGRESS', 'COMPLETED') AND "started_at" IS NOT NULL) OR "status" = 'CANCELLED') +); +CREATE UNIQUE INDEX "production_batches_organization_id_reference_key" ON "production_batches"("organization_id", "reference"); +CREATE UNIQUE INDEX "production_batches_id_organization_id_key" ON "production_batches"("id", "organization_id"); +CREATE INDEX "production_batches_organization_id_status_created_at_id_idx" ON "production_batches"("organization_id", "status", "created_at", "id"); +CREATE INDEX "production_batches_organization_id_bom_id_idx" ON "production_batches"("organization_id", "bom_id"); +ALTER TABLE "production_batches" ADD CONSTRAINT "production_batches_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE "production_batches" ADD CONSTRAINT "production_batches_bom_id_organization_id_fkey" FOREIGN KEY ("bom_id", "organization_id") REFERENCES "product_boms"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE "production_batches" ADD CONSTRAINT "production_batches_created_by_id_organization_id_fkey" FOREIGN KEY ("created_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE; + +CREATE TABLE "production_batch_completions" ( + "batch_id" UUID NOT NULL, + "organization_id" UUID NOT NULL, + "completed_by_id" UUID NOT NULL, + "good_quantity" INTEGER NOT NULL, + "rejected_quantity" INTEGER NOT NULL, + "rejection_reason" VARCHAR(500), + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "production_batch_completions_pkey" PRIMARY KEY ("batch_id"), + CONSTRAINT "production_batch_completions_values" CHECK ("good_quantity" >= 0 AND "rejected_quantity" >= 0 AND ("rejected_quantity" = 0 OR ("rejection_reason" IS NOT NULL AND LENGTH(TRIM("rejection_reason")) > 0))) +); +CREATE UNIQUE INDEX "production_batch_completions_batch_id_organization_id_key" ON "production_batch_completions"("batch_id", "organization_id"); +ALTER TABLE "production_batch_completions" ADD CONSTRAINT "production_batch_completions_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE "production_batch_completions" ADD CONSTRAINT "production_batch_completions_batch_id_organization_id_fkey" FOREIGN KEY ("batch_id", "organization_id") REFERENCES "production_batches"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE "production_batch_completions" ADD CONSTRAINT "production_batch_completions_completed_by_id_organization__fkey" FOREIGN KEY ("completed_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE; + +CREATE TABLE "production_batch_cancellations" ( + "batch_id" UUID NOT NULL, + "organization_id" UUID NOT NULL, + "cancelled_by_id" UUID NOT NULL, + "reason" VARCHAR(500) NOT NULL, + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "production_batch_cancellations_pkey" PRIMARY KEY ("batch_id"), + CONSTRAINT "production_batch_cancellations_reason" CHECK (LENGTH(TRIM("reason")) > 0) +); +CREATE UNIQUE INDEX "production_batch_cancellations_batch_id_organization_id_key" ON "production_batch_cancellations"("batch_id", "organization_id"); +ALTER TABLE "production_batch_cancellations" ADD CONSTRAINT "production_batch_cancellations_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE "production_batch_cancellations" ADD CONSTRAINT "production_batch_cancellations_batch_id_organization_id_fkey" FOREIGN KEY ("batch_id", "organization_id") REFERENCES "production_batches"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE "production_batch_cancellations" ADD CONSTRAINT "production_batch_cancellations_cancelled_by_id_organizatio_fkey" FOREIGN KEY ("cancelled_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE; + +CREATE FUNCTION guard_production_batch_transition() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.status <> 'DRAFT' OR NEW.started_at IS NOT NULL THEN RAISE EXCEPTION 'Production batch must begin as draft'; END IF; + RETURN NEW; + END IF; + IF TG_OP = 'DELETE' THEN RAISE EXCEPTION 'Production batches cannot be deleted'; END IF; + IF NEW.id <> OLD.id OR NEW.organization_id <> OLD.organization_id OR NEW.bom_id <> OLD.bom_id + OR NEW.created_by_id <> OLD.created_by_id OR NEW.reference <> OLD.reference + OR NEW.planned_quantity <> OLD.planned_quantity OR NEW.scheduled_date IS DISTINCT FROM OLD.scheduled_date + OR NEW.created_at <> OLD.created_at OR NOT ( + (OLD.status = 'DRAFT' AND NEW.status = 'IN_PROGRESS' AND OLD.started_at IS NULL AND NEW.started_at IS NOT NULL) + OR (OLD.status = 'DRAFT' AND NEW.status = 'CANCELLED' AND NEW.started_at IS NULL) + OR (OLD.status = 'IN_PROGRESS' AND NEW.status IN ('COMPLETED', 'CANCELLED') AND NEW.started_at = OLD.started_at) + ) + THEN RAISE EXCEPTION 'Invalid production batch transition'; END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER production_batches_guard BEFORE INSERT OR UPDATE OR DELETE ON production_batches FOR EACH ROW EXECUTE FUNCTION guard_production_batch_transition(); + +CREATE FUNCTION guard_production_batch_event() RETURNS trigger LANGUAGE plpgsql AS $$ +DECLARE parent production_batches%ROWTYPE; +BEGIN + IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Production batch events are immutable'; END IF; + SELECT * INTO parent FROM production_batches WHERE id = NEW.batch_id AND organization_id = NEW.organization_id; + IF TG_TABLE_NAME = 'production_batch_completions' THEN + IF parent.status <> 'COMPLETED' OR NEW.good_quantity + NEW.rejected_quantity <> parent.planned_quantity + THEN RAISE EXCEPTION 'Production batch completion does not reconcile'; END IF; + ELSIF parent.status <> 'CANCELLED' THEN + RAISE EXCEPTION 'Production batch is not cancelled'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER production_batch_completions_guard BEFORE INSERT OR UPDATE OR DELETE ON production_batch_completions FOR EACH ROW EXECUTE FUNCTION guard_production_batch_event(); +CREATE TRIGGER production_batch_cancellations_guard BEFORE INSERT OR UPDATE OR DELETE ON production_batch_cancellations FOR EACH ROW EXECUTE FUNCTION guard_production_batch_event(); + +UPDATE "roles" SET "permissions" = array_append(array_append("permissions", 'production.read'), 'production.manage') +WHERE "is_system" = true AND "name" = 'Owner' AND NOT ('production.read' = ANY("permissions")); diff --git a/prisma/production.prisma b/prisma/production.prisma new file mode 100644 index 0000000..40cf16f --- /dev/null +++ b/prisma/production.prisma @@ -0,0 +1,57 @@ +enum ProductionBatchStatus { + DRAFT + IN_PROGRESS + COMPLETED + CANCELLED +} + +model ProductionBatch { + id String @id @default(uuid()) @db.Uuid + organizationId String @map("organization_id") @db.Uuid + bomId String @map("bom_id") @db.Uuid + createdById String @map("created_by_id") @db.Uuid + reference String @db.VarChar(32) + plannedQuantity Int @map("planned_quantity") + status ProductionBatchStatus @default(DRAFT) + scheduledDate DateTime? @map("scheduled_date") @db.Date + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + startedAt DateTime? @map("started_at") @db.Timestamptz(3) + organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict) + bom ProductBom @relation(fields: [bomId, organizationId], references: [id, organizationId], onDelete: Restrict) + createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict) + completion ProductionBatchCompletion? + cancellation ProductionBatchCancellation? + @@unique([organizationId, reference]) + @@unique([id, organizationId]) + @@index([organizationId, status, createdAt, id]) + @@index([organizationId, bomId]) + @@map("production_batches") +} + +model ProductionBatchCompletion { + batchId String @id @map("batch_id") @db.Uuid + organizationId String @map("organization_id") @db.Uuid + completedById String @map("completed_by_id") @db.Uuid + goodQuantity Int @map("good_quantity") + rejectedQuantity Int @map("rejected_quantity") + rejectionReason String? @map("rejection_reason") @db.VarChar(500) + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + batch ProductionBatch @relation(fields: [batchId, organizationId], references: [id, organizationId], onDelete: Restrict) + organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict) + completedBy User @relation(fields: [completedById, organizationId], references: [id, organizationId], onDelete: Restrict) + @@unique([batchId, organizationId]) + @@map("production_batch_completions") +} + +model ProductionBatchCancellation { + batchId String @id @map("batch_id") @db.Uuid + organizationId String @map("organization_id") @db.Uuid + cancelledById String @map("cancelled_by_id") @db.Uuid + reason String @db.VarChar(500) + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + batch ProductionBatch @relation(fields: [batchId, organizationId], references: [id, organizationId], onDelete: Restrict) + organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict) + cancelledBy User @relation(fields: [cancelledById, organizationId], references: [id, organizationId], onDelete: Restrict) + @@unique([batchId, organizationId]) + @@map("production_batch_cancellations") +} diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 082b017..997402d 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -37,6 +37,9 @@ model Organization { supplierDocumentVersions SupplierDocumentVersion[] supplierDocumentDecisions SupplierDocumentDecision[] productBoms ProductBom[] + productionBatches ProductionBatch[] + productionBatchCompletions ProductionBatchCompletion[] + productionBatchCancellations ProductionBatchCancellation[] @@map("organizations") } model User { @@ -65,6 +68,9 @@ model User { supplierDocumentVersions SupplierDocumentVersion[] supplierDocumentDecisions SupplierDocumentDecision[] productBoms ProductBom[] + productionBatches ProductionBatch[] + productionBatchCompletions ProductionBatchCompletion[] + productionBatchCancellations ProductionBatchCancellation[] stockEntries StockLedger[] stockReservations StockReservation[] carts Cart[] diff --git a/src/app.module.ts b/src/app.module.ts index 16996ab..a91771e 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -4,6 +4,7 @@ import { CatalogModule } from './catalog/catalog.module'; import { AddressesModule } from './addresses/addresses.module'; import { InventoryModule } from './inventory/inventory.module'; import { ProcurementModule } from './procurement/procurement.module'; +import { ProductionModule } from './production/production.module'; import { Module } from '@nestjs/common'; import { EnvironmentModule } from './config/environment.module'; import { IdentityModule } from './identity/identity.module'; @@ -18,6 +19,7 @@ import { HealthModule } from './health/health.module'; AddressesModule, InventoryModule, ProcurementModule, + ProductionModule, CheckoutModule, OperationsModule, ], diff --git a/src/common/errors/commerce-errors.ts b/src/common/errors/commerce-errors.ts index 95c3be6..f9814da 100644 --- a/src/common/errors/commerce-errors.ts +++ b/src/common/errors/commerce-errors.ts @@ -341,4 +341,59 @@ export const COMMERCE_ERRORS = { 'A newer BOM revision is already active', 'BOM activation order rejected', ], + BATCH_NOT_FOUND: [ + 404, + 'Production batch not found', + 'Scoped production batch lookup failed', + ], + BATCH_REFERENCE_CONFLICT: [ + 409, + 'Batch reference is already used', + 'Production batch reference duplicate', + ], + BATCH_BOM_NOT_ACTIVE: [ + 409, + 'An active BOM is required', + 'Production batch BOM eligibility failed', + ], + BATCH_VARIANT_INACTIVE: [ + 409, + 'The variant is inactive', + 'Production batch variant eligibility failed', + ], + BATCH_YIELD_MISMATCH: [ + 409, + 'Planned quantity must be a multiple of BOM yield', + 'Production batch yield mismatch', + ], + BATCH_MATERIAL_LIMIT: [ + 409, + 'Planned material quantity exceeds the supported limit', + 'Production batch material scaling overflow', + ], + BATCH_START_STATE: [ + 409, + 'Only a draft batch can start', + 'Production batch start transition rejected', + ], + BATCH_COMPLETE_STATE: [ + 409, + 'Only a started batch can complete', + 'Production batch completion transition rejected', + ], + BATCH_CANCEL_STATE: [ + 409, + 'This batch cannot be cancelled', + 'Production batch cancellation transition rejected', + ], + BATCH_QUANTITY_MISMATCH: [ + 409, + 'Good and rejected quantities must equal the plan', + 'Production batch completion reconciliation failed', + ], + BATCH_REJECTION_REASON_REQUIRED: [ + 400, + 'Give a reason for rejected pieces', + 'Production batch completion rejection lacked reason', + ], } as const; diff --git a/src/identity/permissions.ts b/src/identity/permissions.ts index b39d657..405f0d8 100644 --- a/src/identity/permissions.ts +++ b/src/identity/permissions.ts @@ -28,5 +28,7 @@ export const PERMISSIONS = [ 'supplier_document.validate', 'bom.read', 'bom.manage', + 'production.read', + 'production.manage', ] as const; export type Permission = (typeof PERMISSIONS)[number]; diff --git a/src/production/batch-quantity.ts b/src/production/batch-quantity.ts new file mode 100644 index 0000000..87aca1d --- /dev/null +++ b/src/production/batch-quantity.ts @@ -0,0 +1,18 @@ +import { AppError } from '../common/errors/app-error'; + +const MAX_SCALED_QUANTITY = 999999999999n; + +export function plannedMaterialQuantity( + quantity: string, + factor: number, +): string { + const match = /^(0|[1-9]\d{0,8})(?:\.(\d{1,3}))?$/.exec(quantity); + if (!match || !Number.isSafeInteger(factor) || factor < 1) + throw new AppError('DATA_CONSTRAINT'); + const scaled = + (BigInt(match[1]) * 1000n + + BigInt((match[2] ?? '').padEnd(3, '0') || '0')) * + BigInt(factor); + if (scaled > MAX_SCALED_QUANTITY) throw new AppError('BATCH_MATERIAL_LIMIT'); + return `${scaled / 1000n}.${(scaled % 1000n).toString().padStart(3, '0')}`; +} diff --git a/src/production/batch.schemas.ts b/src/production/batch.schemas.ts new file mode 100644 index 0000000..61eb3c9 --- /dev/null +++ b/src/production/batch.schemas.ts @@ -0,0 +1,45 @@ +import { z } from 'zod'; +import { pageSchema } from '../identity/identity.schemas'; + +export const createBatchSchema = z + .object({ + bomId: z.uuid(), + reference: z + .string() + .trim() + .toUpperCase() + .max(32) + .regex(/^[A-Z0-9][A-Z0-9_-]*$/), + plannedQuantity: z.number().int().min(1).max(100000), + scheduledDate: z.iso + .date() + .transform((value) => new Date(`${value}T00:00:00.000Z`)) + .optional(), + }) + .strict(); + +export const completeBatchSchema = z + .object({ + goodQuantity: z.number().int().min(0).max(100000), + rejectedQuantity: z.number().int().min(0).max(100000), + rejectionReason: z.string().trim().min(1).max(500).optional(), + }) + .strict(); + +export const cancelBatchSchema = z + .object({ reason: z.string().trim().min(1).max(500) }) + .strict(); + +export const batchListQuery = pageSchema + .extend({ + status: z + .enum(['DRAFT', 'IN_PROGRESS', 'COMPLETED', 'CANCELLED']) + .optional(), + variantId: z.uuid().optional(), + }) + .strict(); + +export type CreateBatchInput = z.infer; +export type CompleteBatchInput = z.infer; +export type CancelBatchInput = z.infer; +export type BatchListQuery = z.infer; diff --git a/src/production/batch.store.ts b/src/production/batch.store.ts new file mode 100644 index 0000000..b467ee6 --- /dev/null +++ b/src/production/batch.store.ts @@ -0,0 +1,212 @@ +import { Injectable } from '@nestjs/common'; +import { AppError } from '../common/errors/app-error'; +import { DatabaseService } from '../database/database.service'; +import type { Prisma } from '../generated/prisma/client'; +import { AccessStore } from '../identity/access.store'; +import { recordAudit } from '../identity/audit'; +import type { Principal } from '../identity/identity.types'; +import { plannedMaterialQuantity } from './batch-quantity'; +import type { + BatchListQuery, + CancelBatchInput, + CompleteBatchInput, + CreateBatchInput, +} from './batch.schemas'; + +const batchView = { + bom: { include: { lines: { orderBy: { materialCode: 'asc' as const } } } }, + completion: true, + cancellation: true, +}; + +function present< + T extends { + plannedQuantity: number; + bom: { + outputQuantity: number; + lines: { quantity: { toString(): string } }[]; + }; + }, +>(batch: T) { + const factor = batch.plannedQuantity / batch.bom.outputQuantity; + return { + ...batch, + plannedMaterials: batch.bom.lines.map((line) => ({ + ...line, + plannedQuantity: plannedMaterialQuantity( + line.quantity.toString(), + factor, + ), + })), + }; +} + +@Injectable() +export class BatchStore { + constructor( + private readonly db: DatabaseService, + private readonly access: AccessStore, + ) {} + + list(actor: Principal, query: BatchListQuery) { + return this.db.productionBatch.findMany({ + where: { + organizationId: actor.organizationId, + ...(query.status ? { status: query.status } : {}), + ...(query.variantId ? { bom: { variantId: query.variantId } } : {}), + }, + orderBy: [{ createdAt: 'desc' }, { id: 'desc' }], + take: query.limit, + skip: query.offset, + }); + } + + async find(actor: Principal, id: string) { + const batch = await this.db.productionBatch.findFirst({ + where: { id, organizationId: actor.organizationId }, + include: batchView, + }); + if (!batch) throw new AppError('BATCH_NOT_FOUND'); + return present(batch); + } + + create(actor: Principal, input: CreateBatchInput) { + return this.access.mutate(actor, 'production.manage', async (tx) => { + const duplicate = await tx.productionBatch.findFirst({ + where: { + organizationId: actor.organizationId, + reference: input.reference, + }, + select: { id: true }, + }); + if (duplicate) throw new AppError('BATCH_REFERENCE_CONFLICT'); + const bom = await tx.productBom.findFirst({ + where: { id: input.bomId, organizationId: actor.organizationId }, + include: { variant: { select: { active: true } }, lines: true }, + }); + if (!bom) throw new AppError('BOM_NOT_FOUND'); + if (bom.status !== 'ACTIVE') throw new AppError('BATCH_BOM_NOT_ACTIVE'); + if (!bom.variant.active) throw new AppError('BATCH_VARIANT_INACTIVE'); + if (input.plannedQuantity % bom.outputQuantity !== 0) + throw new AppError('BATCH_YIELD_MISMATCH'); + const factor = input.plannedQuantity / bom.outputQuantity; + for (const line of bom.lines) + plannedMaterialQuantity(line.quantity.toString(), factor); + const batch = await tx.productionBatch.create({ + data: { + ...input, + organizationId: actor.organizationId, + createdById: actor.userId, + }, + }); + await recordAudit( + tx, + actor.organizationId, + actor.userId, + 'batch.created', + batch.id, + ); + return this.load(tx, batch.id); + }); + } + + start(actor: Principal, id: string) { + return this.access.mutate(actor, 'production.manage', async (tx) => { + const batch = await this.requireBatch(tx, actor, id); + if (batch.status !== 'DRAFT') throw new AppError('BATCH_START_STATE'); + await tx.productionBatch.update({ + where: { id }, + data: { status: 'IN_PROGRESS', startedAt: new Date() }, + }); + await recordAudit( + tx, + actor.organizationId, + actor.userId, + 'batch.started', + id, + ); + return this.load(tx, id); + }); + } + + complete(actor: Principal, id: string, input: CompleteBatchInput) { + return this.access.mutate(actor, 'production.manage', async (tx) => { + const batch = await this.requireBatch(tx, actor, id); + if (batch.status !== 'IN_PROGRESS') + throw new AppError('BATCH_COMPLETE_STATE'); + if (input.goodQuantity + input.rejectedQuantity !== batch.plannedQuantity) + throw new AppError('BATCH_QUANTITY_MISMATCH'); + if (input.rejectedQuantity > 0 && !input.rejectionReason) + throw new AppError('BATCH_REJECTION_REASON_REQUIRED'); + await tx.productionBatch.update({ + where: { id }, + data: { status: 'COMPLETED' }, + }); + await tx.productionBatchCompletion.create({ + data: { + ...input, + batchId: id, + organizationId: actor.organizationId, + completedById: actor.userId, + }, + }); + await recordAudit( + tx, + actor.organizationId, + actor.userId, + 'batch.completed', + id, + ); + return this.load(tx, id); + }); + } + + cancel(actor: Principal, id: string, input: CancelBatchInput) { + return this.access.mutate(actor, 'production.manage', async (tx) => { + const batch = await this.requireBatch(tx, actor, id); + if (batch.status !== 'DRAFT' && batch.status !== 'IN_PROGRESS') + throw new AppError('BATCH_CANCEL_STATE'); + await tx.productionBatch.update({ + where: { id }, + data: { status: 'CANCELLED' }, + }); + await tx.productionBatchCancellation.create({ + data: { + batchId: id, + organizationId: actor.organizationId, + cancelledById: actor.userId, + reason: input.reason, + }, + }); + await recordAudit( + tx, + actor.organizationId, + actor.userId, + 'batch.cancelled', + id, + ); + return this.load(tx, id); + }); + } + + private async requireBatch( + tx: Prisma.TransactionClient, + actor: Principal, + id: string, + ) { + const batch = await tx.productionBatch.findFirst({ + where: { id, organizationId: actor.organizationId }, + select: { status: true, plannedQuantity: true }, + }); + if (!batch) throw new AppError('BATCH_NOT_FOUND'); + return batch; + } + + private async load(tx: Prisma.TransactionClient, id: string) { + const batch = await tx.productionBatch.findUniqueOrThrow({ + where: { id }, + include: batchView, + }); + return present(batch); + } +} diff --git a/src/production/batches.controller.ts b/src/production/batches.controller.ts new file mode 100644 index 0000000..8f2dc0d --- /dev/null +++ b/src/production/batches.controller.ts @@ -0,0 +1,87 @@ +import { + Body, + Controller, + Get, + Param, + ParseUUIDPipe, + Post, + Query, +} from '@nestjs/common'; +import { SchemaPipe } from '../common/validation.pipe'; +import { + CurrentPrincipal, + RequirePermission, +} from '../identity/access.decorator'; +import type { Principal } from '../identity/identity.types'; +import { BatchStore } from './batch.store'; +import { + batchListQuery, + cancelBatchSchema, + completeBatchSchema, + createBatchSchema, + type BatchListQuery, + type CancelBatchInput, + type CompleteBatchInput, + type CreateBatchInput, +} from './batch.schemas'; + +@Controller('production-batches') +export class BatchesController { + constructor(private readonly batches: BatchStore) {} + + @Get() + @RequirePermission('production.read') + list( + @CurrentPrincipal() actor: Principal, + @Query(new SchemaPipe(batchListQuery)) query: BatchListQuery, + ) { + return this.batches.list(actor, query); + } + + @Get(':id') + @RequirePermission('production.read') + find( + @CurrentPrincipal() actor: Principal, + @Param('id', ParseUUIDPipe) id: string, + ) { + return this.batches.find(actor, id); + } + + @Post() + @RequirePermission('production.manage') + create( + @CurrentPrincipal() actor: Principal, + @Body(new SchemaPipe(createBatchSchema)) input: CreateBatchInput, + ) { + return this.batches.create(actor, input); + } + + @Post(':id/start') + @RequirePermission('production.manage') + start( + @CurrentPrincipal() actor: Principal, + @Param('id', ParseUUIDPipe) id: string, + ) { + return this.batches.start(actor, id); + } + + @Post(':id/complete') + @RequirePermission('production.manage') + complete( + @CurrentPrincipal() actor: Principal, + @Param('id', ParseUUIDPipe) id: string, + @Body(new SchemaPipe(completeBatchSchema)) input: CompleteBatchInput, + ) { + return this.batches.complete(actor, id, input); + } + + @Post(':id/cancel') + @RequirePermission('production.manage') + cancel( + @CurrentPrincipal() actor: Principal, + @Param('id', ParseUUIDPipe) id: string, + @Body(new SchemaPipe(cancelBatchSchema)) input: CancelBatchInput, + ) { + return this.batches.cancel(actor, id, input); + } +} diff --git a/src/production/production.module.ts b/src/production/production.module.ts new file mode 100644 index 0000000..6bfaeed --- /dev/null +++ b/src/production/production.module.ts @@ -0,0 +1,12 @@ +import { Module } from '@nestjs/common'; +import { DatabaseModule } from '../database/database.module'; +import { IdentityModule } from '../identity/identity.module'; +import { BatchStore } from './batch.store'; +import { BatchesController } from './batches.controller'; + +@Module({ + imports: [DatabaseModule, IdentityModule], + providers: [BatchStore], + controllers: [BatchesController], +}) +export class ProductionModule {} diff --git a/test/batch-quantity.spec.ts b/test/batch-quantity.spec.ts new file mode 100644 index 0000000..01befae --- /dev/null +++ b/test/batch-quantity.spec.ts @@ -0,0 +1,14 @@ +import { AppError } from '../src/common/errors/app-error'; +import { plannedMaterialQuantity } from '../src/production/batch-quantity'; + +describe('planned material scaling', () => { + it('scales exact three-decimal quantities without floating-point loss', () => { + expect(plannedMaterialQuantity('0.125', 8)).toBe('1.000'); + expect(plannedMaterialQuantity('125', 3)).toBe('375.000'); + expect(plannedMaterialQuantity('999999999.999', 1)).toBe('999999999.999'); + }); + it('rejects a quantity that would overflow the database column', () => { + expect(() => plannedMaterialQuantity('999999999.999', 2)).toThrow(AppError); + expect(() => plannedMaterialQuantity('1.000', 0)).toThrow(AppError); + }); +}); diff --git a/test/production-batches.spec.ts b/test/production-batches.spec.ts new file mode 100644 index 0000000..6146988 --- /dev/null +++ b/test/production-batches.spec.ts @@ -0,0 +1,232 @@ +import { randomUUID } from 'node:crypto'; +import { identityApp, type IdentityApp } from './helpers/identity-app'; +import { secondActor, seedProduct } from './helpers/commerce'; + +describe('production batch API', () => { + let ctx: IdentityApp; + const auth = { type: 'bearer' as const }; + const createActiveBom = async () => { + const { variant } = await seedProduct(ctx); + const material = await ctx + .api() + .post('/api/v1/materials') + .auth(ctx.token, auth) + .send({ + code: `W-${randomUUID().slice(0, 8)}`, + name: 'Soy Wax', + kind: 'WAX', + unit: 'GRAM', + }) + .expect(201); + const bom = await ctx + .api() + .post(`/api/v1/variants/${variant.id}/boms`) + .auth(ctx.token, auth) + .send({ + outputQuantity: 10, + lines: [{ materialId: material.body.id, quantity: '125.000' }], + }) + .expect(201); + await ctx + .api() + .post(`/api/v1/boms/${bom.body.id}/activate`) + .auth(ctx.token, auth) + .expect(201); + return { bomId: bom.body.id as string, variantId: variant.id as string }; + }; + const createBatch = (bomId: string, plannedQuantity = 20) => + ctx + .api() + .post('/api/v1/production-batches') + .auth(ctx.token, auth) + .send({ + bomId, + plannedQuantity, + reference: `B-${randomUUID().slice(0, 8)}`, + }); + + beforeAll(async () => { + ctx = await identityApp(); + }, 60000); + afterAll(async () => { + await ctx?.close(); + }); + beforeEach(async () => { + await ctx.clearLimits(); + }); + + it('tracks a batch from plan through completion with a stable BOM and exact yield', async () => { + const { bomId, variantId } = await createActiveBom(); + const created = await createBatch(bomId).expect(201); + expect(created.body).toMatchObject({ + status: 'DRAFT', + plannedQuantity: 20, + }); + expect(created.body.plannedMaterials[0].plannedQuantity).toBe('250.000'); + const started = await ctx + .api() + .post(`/api/v1/production-batches/${created.body.id}/start`) + .auth(ctx.token, auth) + .expect(201); + expect(started.body.status).toBe('IN_PROGRESS'); + const completed = await ctx + .api() + .post(`/api/v1/production-batches/${created.body.id}/complete`) + .auth(ctx.token, auth) + .send({ + goodQuantity: 18, + rejectedQuantity: 2, + rejectionReason: 'Surface defects', + }) + .expect(201); + expect(completed.body.completion).toMatchObject({ + goodQuantity: 18, + rejectedQuantity: 2, + }); + const listed = await ctx + .api() + .get(`/api/v1/production-batches?status=COMPLETED&variantId=${variantId}`) + .auth(ctx.token, auth) + .expect(200); + expect(listed.body.map((row: { id: string }) => row.id)).toContain( + created.body.id, + ); + const repeated = await ctx + .api() + .post(`/api/v1/production-batches/${created.body.id}/complete`) + .auth(ctx.token, auth) + .send({ goodQuantity: 20, rejectedQuantity: 0 }) + .expect(409); + expect(repeated.body.code).toBe('BATCH_COMPLETE_STATE'); + expect( + await ctx.db.auditEvent.count({ + where: { + organizationId: ctx.owner.organizationId, + action: 'batch.completed', + }, + }), + ).toBe(1); + }); + + it('enforces reference uniqueness, BOM yield and active BOM requirements', async () => { + const { bomId } = await createActiveBom(); + const mismatch = await createBatch(bomId, 11).expect(409); + expect(mismatch.body.code).toBe('BATCH_YIELD_MISMATCH'); + const reference = `B-${randomUUID().slice(0, 8)}`; + const input = { bomId, reference, plannedQuantity: 10 }; + await ctx + .api() + .post('/api/v1/production-batches') + .auth(ctx.token, auth) + .send(input) + .expect(201); + const duplicate = await ctx + .api() + .post('/api/v1/production-batches') + .auth(ctx.token, auth) + .send(input) + .expect(409); + expect(duplicate.body.code).toBe('BATCH_REFERENCE_CONFLICT'); + const missing = await createBatch(randomUUID()).expect(404); + expect(missing.body.code).toBe('BOM_NOT_FOUND'); + }); + + it('reconciles completion and records cancellable work without stock movement', async () => { + const { bomId } = await createActiveBom(); + const first = await createBatch(bomId).expect(201); + const early = await ctx + .api() + .post(`/api/v1/production-batches/${first.body.id}/complete`) + .auth(ctx.token, auth) + .send({ goodQuantity: 20, rejectedQuantity: 0 }) + .expect(409); + expect(early.body.code).toBe('BATCH_COMPLETE_STATE'); + await ctx + .api() + .post(`/api/v1/production-batches/${first.body.id}/start`) + .auth(ctx.token, auth) + .expect(201); + const mismatch = await ctx + .api() + .post(`/api/v1/production-batches/${first.body.id}/complete`) + .auth(ctx.token, auth) + .send({ goodQuantity: 19, rejectedQuantity: 0 }) + .expect(409); + expect(mismatch.body.code).toBe('BATCH_QUANTITY_MISMATCH'); + const missingReason = await ctx + .api() + .post(`/api/v1/production-batches/${first.body.id}/complete`) + .auth(ctx.token, auth) + .send({ goodQuantity: 19, rejectedQuantity: 1 }) + .expect(400); + expect(missingReason.body.code).toBe('BATCH_REJECTION_REASON_REQUIRED'); + const cancelled = await ctx + .api() + .post(`/api/v1/production-batches/${first.body.id}/cancel`) + .auth(ctx.token, auth) + .send({ reason: 'Production halted' }) + .expect(201); + expect(cancelled.body).toMatchObject({ + status: 'CANCELLED', + cancellation: { reason: 'Production halted' }, + }); + const repeated = await ctx + .api() + .post(`/api/v1/production-batches/${first.body.id}/cancel`) + .auth(ctx.token, auth) + .send({ reason: 'Again' }) + .expect(409); + expect(repeated.body.code).toBe('BATCH_CANCEL_STATE'); + }); + + it('separates read/manage permission and organization scope', async () => { + const { bomId } = await createActiveBom(); + const batch = await createBatch(bomId).expect(201); + const reader = await secondActor(ctx, true, ['production.read']); + await ctx + .api() + .get(`/api/v1/production-batches/${batch.body.id}`) + .auth(reader.token, auth) + .expect(200); + await ctx + .api() + .post(`/api/v1/production-batches/${batch.body.id}/start`) + .auth(reader.token, auth) + .expect(403); + const outsider = await secondActor(ctx, false, [ + 'production.read', + 'production.manage', + ]); + const hidden = await ctx + .api() + .get(`/api/v1/production-batches/${batch.body.id}`) + .auth(outsider.token, auth) + .expect(404); + expect(hidden.body.code).toBe('BATCH_NOT_FOUND'); + }); + + it('enforces the rejection reason in PostgreSQL as well as the API', async () => { + const { bomId } = await createActiveBom(); + const batch = await createBatch(bomId).expect(201); + await ctx + .api() + .post(`/api/v1/production-batches/${batch.body.id}/start`) + .auth(ctx.token, auth) + .expect(201); + await ctx.db.productionBatch.update({ + where: { id: batch.body.id }, + data: { status: 'COMPLETED' }, + }); + await expect( + ctx.db.productionBatchCompletion.create({ + data: { + batchId: batch.body.id, + organizationId: ctx.owner.organizationId, + completedById: ctx.owner.userId, + goodQuantity: 19, + rejectedQuantity: 1, + }, + }), + ).rejects.toThrow(); + }); +}); From d4aa7d5c79508ded5a5276f72517547f4774a3e3 Mon Sep 17 00:00:00 2001 From: mihir Date: Tue, 29 Sep 2026 00:30:48 +0530 Subject: [PATCH 2/3] feat(identity): prepare guarded local admin seed credentials --- README.md | 1 + docs/local-admin.md | 13 +++++++++ package.json | 2 ++ src/cli/local-admin.ts | 50 ++++++++++++++++++++++++++++++++ src/identity/local-admin-seed.ts | 26 +++++++++++++++++ test/local-admin-seed.spec.ts | 34 ++++++++++++++++++++++ 6 files changed, 126 insertions(+) create mode 100644 docs/local-admin.md create mode 100644 src/cli/local-admin.ts create mode 100644 src/identity/local-admin-seed.ts create mode 100644 test/local-admin-seed.spec.ts diff --git a/README.md b/README.md index 6b18704..8d21fbe 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,7 @@ Phase 2E adds [supplier payment records and reversals](docs/supplier-payments-ap Phase 2F adds [private versioned supplier documents and review](docs/supplier-documents-api.md). Phase 2G adds [versioned product bills of materials](docs/bom-api.md). Phase 2H adds [production batches](docs/production-batches-api.md). +For a development owner, see [local admin setup](docs/local-admin.md). ### Swagger UI diff --git a/docs/local-admin.md b/docs/local-admin.md new file mode 100644 index 0000000..f9437d5 --- /dev/null +++ b/docs/local-admin.md @@ -0,0 +1,13 @@ +# Local admin account + +The development-only seed uses the existing one-time owner bootstrap. It creates no committed default password. A local PostgreSQL server must be available using the `DATABASE_URL` in `.env`, and `NODE_ENV` must be `development`. + +```sh +pnpm db:generate +pnpm db:deploy +pnpm build +pnpm admin:prepare-local +pnpm admin:seed-local +``` + +`admin:prepare-local` creates an ignored `.env.local-admin` file with `OWNER_EMAIL=admin@manicandles.local`, organization/name settings and a random password. The command refuses to overwrite it. Read the password from that local file; do not commit or share it. `admin:seed-local` passes those values to the existing bootstrap command and prints only the resulting organization and user IDs. The seed accepts only a development environment with a loopback PostgreSQL URL. A second seed fails if an owner already exists; it does not reset the existing password. Use the normal identity workflow to change credentials. Create production administrators separately using fresh credentials and a controlled deployment procedure. diff --git a/package.json b/package.json index 5a71f5e..c29c1ca 100644 --- a/package.json +++ b/package.json @@ -23,6 +23,8 @@ "start:watch": "node --watch dist/main.js", "db:status": "prisma migrate status", "bootstrap:owner": "node dist/cli/bootstrap-owner.js", + "admin:prepare-local": "node dist/cli/local-admin.js prepare", + "admin:seed-local": "node dist/cli/local-admin.js seed", "db:test": "node scripts/test-migrations.mjs", "migrations:check": "node scripts/check-migrations.mjs", "security:audit": "pnpm audit --prod --audit-level=high" diff --git a/src/cli/local-admin.ts b/src/cli/local-admin.ts new file mode 100644 index 0000000..13a6179 --- /dev/null +++ b/src/cli/local-admin.ts @@ -0,0 +1,50 @@ +import 'dotenv/config'; +import { spawnSync } from 'node:child_process'; +import { readFile, writeFile } from 'node:fs/promises'; +import { resolve } from 'node:path'; +import { parse } from 'dotenv'; +import { + assertLocalAdminTarget, + localAdminSettings, +} from '../identity/local-admin-seed'; + +const credentialFile = resolve('.env.local-admin'); + +async function main() { + assertLocalAdminTarget(process.env.NODE_ENV, process.env.DATABASE_URL); + const mode = process.argv[2]; + if (mode === 'prepare') { + const settings = localAdminSettings(); + await writeFile( + credentialFile, + Object.entries(settings) + .map(([key, value]) => `${key}=${value}`) + .join('\n') + '\n', + { flag: 'wx', mode: 0o600 }, + ); + console.log('Local admin credentials prepared in .env.local-admin'); + return; + } + if (mode === 'seed') { + const settings = parse(await readFile(credentialFile)); + const result = spawnSync( + process.execPath, + [resolve('dist/cli/bootstrap-owner.js')], + { + env: { ...process.env, ...settings }, + stdio: 'inherit', + }, + ); + if (result.error) throw result.error; + if (result.status !== 0) process.exitCode = result.status ?? 1; + return; + } + throw new Error('Use prepare or seed'); +} + +void main().catch((error: unknown) => { + console.error( + error instanceof Error ? error.message : 'Local admin setup failed', + ); + process.exitCode = 1; +}); diff --git a/src/identity/local-admin-seed.ts b/src/identity/local-admin-seed.ts new file mode 100644 index 0000000..5515473 --- /dev/null +++ b/src/identity/local-admin-seed.ts @@ -0,0 +1,26 @@ +import { randomBytes } from 'node:crypto'; + +export function assertLocalAdminTarget(nodeEnv?: string, databaseUrl?: string) { + if (nodeEnv !== 'development') + throw new Error('Local admin seed requires NODE_ENV=development'); + let url: URL; + try { + url = new URL(databaseUrl ?? ''); + } catch { + throw new Error('Local admin seed requires a valid PostgreSQL URL'); + } + if ( + !['postgresql:', 'postgres:'].includes(url.protocol) || + !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname) + ) + throw new Error('Local admin seed requires a loopback PostgreSQL host'); +} + +export function localAdminSettings() { + return { + ORGANIZATION_NAME: 'Mani Candles Local', + OWNER_NAME: 'Local Admin', + OWNER_EMAIL: 'admin@manicandles.local', + OWNER_PASSWORD: randomBytes(32).toString('base64url'), + }; +} diff --git a/test/local-admin-seed.spec.ts b/test/local-admin-seed.spec.ts new file mode 100644 index 0000000..705f079 --- /dev/null +++ b/test/local-admin-seed.spec.ts @@ -0,0 +1,34 @@ +import { + assertLocalAdminTarget, + localAdminSettings, +} from '../src/identity/local-admin-seed'; + +describe('local admin seed guard', () => { + it('accepts only development against loopback PostgreSQL', () => { + expect(() => + assertLocalAdminTarget( + 'development', + 'postgresql://u:p@127.0.0.1:5432/local', + ), + ).not.toThrow(); + expect(() => + assertLocalAdminTarget('production', 'postgresql://u:p@127.0.0.1/local'), + ).toThrow(); + expect(() => + assertLocalAdminTarget( + 'development', + 'postgresql://u:p@db.example.com/local', + ), + ).toThrow(); + expect(() => + assertLocalAdminTarget('development', 'https://localhost/local'), + ).toThrow(); + }); + it('generates a unique strong password without a committed default', () => { + const first = localAdminSettings(); + const second = localAdminSettings(); + expect(first.OWNER_EMAIL).toBe('admin@manicandles.local'); + expect(first.OWNER_PASSWORD.length).toBeGreaterThanOrEqual(40); + expect(first.OWNER_PASSWORD).not.toBe(second.OWNER_PASSWORD); + }); +}); From cc3fb9d62ae851a803cba9612ffd21c196d5165d Mon Sep 17 00:00:00 2001 From: mihir Date: Tue, 29 Sep 2026 00:35:20 +0530 Subject: [PATCH 3/3] fix(identity): restrict Windows local admin credential ACL --- docs/local-admin.md | 1 + src/cli/local-admin.ts | 21 ++++++++++++++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/docs/local-admin.md b/docs/local-admin.md index f9437d5..e8997bb 100644 --- a/docs/local-admin.md +++ b/docs/local-admin.md @@ -11,3 +11,4 @@ pnpm admin:seed-local ``` `admin:prepare-local` creates an ignored `.env.local-admin` file with `OWNER_EMAIL=admin@manicandles.local`, organization/name settings and a random password. The command refuses to overwrite it. Read the password from that local file; do not commit or share it. `admin:seed-local` passes those values to the existing bootstrap command and prints only the resulting organization and user IDs. The seed accepts only a development environment with a loopback PostgreSQL URL. A second seed fails if an owner already exists; it does not reset the existing password. Use the normal identity workflow to change credentials. Create production administrators separately using fresh credentials and a controlled deployment procedure. +On Windows, preparation removes inherited file permissions and grants access only to the running user, SYSTEM and Administrators; it fails and removes the file if that restriction cannot be applied. diff --git a/src/cli/local-admin.ts b/src/cli/local-admin.ts index 13a6179..c67c10d 100644 --- a/src/cli/local-admin.ts +++ b/src/cli/local-admin.ts @@ -1,6 +1,6 @@ import 'dotenv/config'; import { spawnSync } from 'node:child_process'; -import { readFile, writeFile } from 'node:fs/promises'; +import { readFile, unlink, writeFile } from 'node:fs/promises'; import { resolve } from 'node:path'; import { parse } from 'dotenv'; import { @@ -22,6 +22,25 @@ async function main() { .join('\n') + '\n', { flag: 'wx', mode: 0o600 }, ); + if (process.platform === 'win32') { + const account = `${process.env.USERDOMAIN}\\${process.env.USERNAME}`; + const protectedFile = spawnSync( + 'icacls.exe', + [ + credentialFile, + '/inheritance:r', + '/grant:r', + `${account}:(F)`, + 'SYSTEM:(F)', + 'Administrators:(F)', + ], + { stdio: 'ignore' }, + ); + if (protectedFile.status !== 0) { + await unlink(credentialFile); + throw new Error('Could not restrict local credential file access'); + } + } console.log('Local admin credentials prepared in .env.local-admin'); return; }