Checkpoint · Lesson 10.5
Capstone solution: work orders: checkpoint files
Compare your folder with the reference using Git, if you cloned it: git diff lesson/m10-l05 -- src.
Files changed in this lesson
migrations/007_create_work_orders.sql added
migrations/007_create_work_orders.sqlCREATE TABLE work_orders (
id integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
issue_id integer NOT NULL REFERENCES issues (id) ON DELETE CASCADE,
title text NOT NULL CHECK (length(title) BETWEEN 3 AND 200),
assignee_id integer NOT NULL REFERENCES users (id) ON DELETE RESTRICT,
created_by integer REFERENCES users (id) ON DELETE SET NULL,
due_on date NOT NULL,
status text NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'done')),
completed_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX work_orders_issue_id_idx ON work_orders (issue_id);
CREATE TABLE work_orders ( id integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, issue_id integer NOT NULL REFERENCES issues (id) ON DELETE CASCADE, title text NOT NULL CHECK (length(title) BETWEEN 3 AND 200), assignee_id integer NOT NULL REFERENCES users (id) ON DELETE RESTRICT, created_by integer REFERENCES users (id) ON DELETE SET NULL, due_on date NOT NULL, status text NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'done')), completed_at timestamptz, created_at timestamptz NOT NULL DEFAULT now()); CREATE INDEX work_orders_issue_id_idx ON work_orders (issue_id);src/authz/entities.js changed
src/authz/entities.js// The entity mapper: turns rows the application already loaded into Cedar entities.
// Every value comes from the database (through loadAccess and the models) or from
// the session (the user id). Nothing comes from the HTTP request.
const NAMESPACE = 'Caretaker';
export function ref(type, id) {
return { type: `${NAMESPACE}::${type}`, id: String(id) };
}
function refs(type, ids) {
return [...new Set(ids)].sort((a, b) => a - b).map((id) => ref(type, id));
}
function buildingsWithRole(user, role) {
return refs('Building', user.access.assignments.filter((a) => a.role === role).map((a) => a.building_id));
}
// Version 2: facts only. Each set is exactly the active rows of one role.
// Inheritance (organisation -> building) and the role ladder are decided by the policies.
export function userEntity(user) {
return {
uid: ref('User', user.id),
attrs: {
viewerBuildings: buildingsWithRole(user, 'viewer'),
reporterBuildings: buildingsWithRole(user, 'reporter'),
inspectorBuildings: buildingsWithRole(user, 'inspector'),
adminBuildings: buildingsWithRole(user, 'building_admin'),
memberOrganisations: refs('Organisation', user.access.memberships.map((m) => m.organisation_id)),
adminOrganisations: refs('Organisation', user.access.memberships.filter((m) => m.role === 'org_admin').map((m) => m.organisation_id)),
},
parents: [],
};
}
export function organisationEntity(organisationId) {
return { uid: ref('Organisation', organisationId), attrs: {}, parents: [] };
}
export function buildingEntity({ id, organisation_id }) {
return {
uid: ref('Building', id),
attrs: { organisation: ref('Organisation', organisation_id) },
parents: [ref('Organisation', organisation_id)],
};
}
export function issueEntity(issue) {
const attrs = { building: ref('Building', issue.building_id), status: issue.status, priority: issue.priority };
if (issue.reported_by !== null) {
attrs.reportedBy = ref('User', issue.reported_by);
}
return { uid: ref('Issue', issue.id), attrs, parents: [ref('Building', issue.building_id)] };
}
export function workOrderEntity(action) {
const attrs = { issue: ref('Issue', action.issue_id), assignee: ref('User', action.assignee_id), status: action.status };
if (action.created_by !== null) {
attrs.createdBy = ref('User', action.created_by);
}
return { uid: ref('WorkOrder', action.id), attrs, parents: [ref('Issue', action.issue_id)] };
}
export function inspectionEntity(inspection) {
const attrs = { building: ref('Building', inspection.building_id), status: inspection.status };
if (inspection.created_by !== null) {
attrs.createdBy = ref('User', inspection.created_by);
}
return { uid: ref('Inspection', inspection.id), attrs, parents: [ref('Building', inspection.building_id)] };
}
// The entity mapper: turns rows the application already loaded into Cedar entities.// Every value comes from the database (through loadAccess and the models) or from// the session (the user id). Nothing comes from the HTTP request. const NAMESPACE = 'Caretaker'; export function ref(type, id) { return { type: `${NAMESPACE}::${type}`, id: String(id) };} function refs(type, ids) { return [...new Set(ids)].sort((a, b) => a - b).map((id) => ref(type, id));} function buildingsWithRole(user, role) { return refs('Building', user.access.assignments.filter((a) => a.role === role).map((a) => a.building_id));} // Version 2: facts only. Each set is exactly the active rows of one role.// Inheritance (organisation -> building) and the role ladder are decided by the policies.export function userEntity(user) { return { uid: ref('User', user.id), attrs: { viewerBuildings: buildingsWithRole(user, 'viewer'), reporterBuildings: buildingsWithRole(user, 'reporter'), inspectorBuildings: buildingsWithRole(user, 'inspector'), adminBuildings: buildingsWithRole(user, 'building_admin'), memberOrganisations: refs('Organisation', user.access.memberships.map((m) => m.organisation_id)), adminOrganisations: refs('Organisation', user.access.memberships.filter((m) => m.role === 'org_admin').map((m) => m.organisation_id)), }, parents: [], };} export function organisationEntity(organisationId) { return { uid: ref('Organisation', organisationId), attrs: {}, parents: [] };} export function buildingEntity({ id, organisation_id }) { return { uid: ref('Building', id), attrs: { organisation: ref('Organisation', organisation_id) }, parents: [ref('Organisation', organisation_id)], };} export function issueEntity(issue) { const attrs = { building: ref('Building', issue.building_id), status: issue.status, priority: issue.priority }; if (issue.reported_by !== null) { attrs.reportedBy = ref('User', issue.reported_by); } return { uid: ref('Issue', issue.id), attrs, parents: [ref('Building', issue.building_id)] };} export function workOrderEntity(action) { const attrs = { issue: ref('Issue', action.issue_id), assignee: ref('User', action.assignee_id), status: action.status }; if (action.created_by !== null) { attrs.createdBy = ref('User', action.created_by); } return { uid: ref('WorkOrder', action.id), attrs, parents: [ref('Issue', action.issue_id)] };} export function inspectionEntity(inspection) { const attrs = { building: ref('Building', inspection.building_id), status: inspection.status }; if (inspection.created_by !== null) { attrs.createdBy = ref('User', inspection.created_by); } return { uid: ref('Inspection', inspection.id), attrs, parents: [ref('Building', inspection.building_id)] };}src/authz/policies/assignee-completes-work-order.cedar added
src/authz/policies/assignee-completes-work-order.cedar// The assignee may mark their own open work order as done.
permit (principal, action == Caretaker::Action::"CompleteWorkOrder", resource)
when { resource.assignee == principal && resource.status == "open" };
// The assignee may mark their own open work order as done.permit (principal, action == Caretaker::Action::"CompleteWorkOrder", resource)when { resource.assignee == principal && resource.status == "open" };src/authz/policies/forbid-self-assignment.cedar added
src/authz/policies/forbid-self-assignment.cedar// Nobody assigns a work order to themselves.
forbid (principal, action == Caretaker::Action::"CreateWorkOrder", resource)
when { context.assignee == principal };
// Nobody assigns a work order to themselves.forbid (principal, action == Caretaker::Action::"CreateWorkOrder", resource)when { context.assignee == principal };src/authz/policies/reporter-creates-work-orders.cedar added
src/authz/policies/reporter-creates-work-orders.cedar// The reporter of an issue may plan work orders for it while it is not closed.
permit (principal, action == Caretaker::Action::"CreateWorkOrder", resource)
when {
resource in principal.reporterBuildings &&
resource has reportedBy &&
resource.reportedBy == principal &&
resource.status != "closed"
};
// The reporter of an issue may plan work orders for it while it is not closed.permit (principal, action == Caretaker::Action::"CreateWorkOrder", resource)when { resource in principal.reporterBuildings && resource has reportedBy && resource.reportedBy == principal && resource.status != "closed"};src/authz/request.js changed
src/authz/request.jsimport { ref, userEntity, organisationEntity, buildingEntity, issueEntity, inspectionEntity, workOrderEntity } from './entities.js';
// Which entity type each action's resource is. Must match the schema's appliesTo.
export const RESOURCE_TYPES = {
ViewOrganisation: 'Organisation',
UpdateOrganisation: 'Organisation',
DeleteOrganisation: 'Organisation',
CreateBuilding: 'Organisation',
ViewMembers: 'Organisation',
ManageMembers: 'Organisation',
ViewBuilding: 'Building',
UpdateBuilding: 'Building',
DeleteBuilding: 'Building',
CreateIssue: 'Building',
CreateInspection: 'Building',
ViewBuildingAccess: 'Building',
ManageBuildingRoles: 'Building',
ViewIssue: 'Issue',
UpdateIssue: 'Issue',
DeleteIssue: 'Issue',
ViewInspection: 'Inspection',
UpdateInspection: 'Inspection',
SubmitInspection: 'Inspection',
ApproveInspection: 'Inspection',
ReturnInspection: 'Inspection',
ViewWorkOrder: 'WorkOrder',
CompleteWorkOrder: 'WorkOrder',
DeleteWorkOrder: 'WorkOrder',
CreateWorkOrder: 'Issue',
};
// The resource entity for a database row, followed by the building and organisation it belongs to.
function resourceEntities(type, row) {
switch (type) {
case 'Organisation':
return [organisationEntity(row.id)];
case 'Building':
return [buildingEntity(row), organisationEntity(row.organisation_id)];
case 'Issue':
return [issueEntity(row), buildingEntity({ id: row.building_id, organisation_id: row.organisation_id }), organisationEntity(row.organisation_id)];
case 'Inspection':
return [inspectionEntity(row), buildingEntity({ id: row.building_id, organisation_id: row.organisation_id }), organisationEntity(row.organisation_id)];
case 'WorkOrder': {
const { issue } = row;
return [workOrderEntity(row), issueEntity(issue), buildingEntity({ id: issue.building_id, organisation_id: issue.organisation_id }), organisationEntity(issue.organisation_id)];
}
default:
throw new Error(`Unknown resource type ${type}`);
}
}
// Builds the request part of an isAuthorized call for one user, action and database row.
export function buildAuthorizationCall(user, action, row, context = {}) {
const type = RESOURCE_TYPES[action];
if (!type) {
throw new Error(`No Cedar resource type for action ${action}`);
}
const [resource, ...related] = resourceEntities(type, row);
return {
principal: ref('User', user.id),
action: { type: 'Caretaker::Action', id: action },
resource: resource.uid,
context,
entities: [userEntity(user), resource, ...related],
};
}
import { ref, userEntity, organisationEntity, buildingEntity, issueEntity, inspectionEntity, workOrderEntity } from './entities.js'; // Which entity type each action's resource is. Must match the schema's appliesTo.export const RESOURCE_TYPES = { ViewOrganisation: 'Organisation', UpdateOrganisation: 'Organisation', DeleteOrganisation: 'Organisation', CreateBuilding: 'Organisation', ViewMembers: 'Organisation', ManageMembers: 'Organisation', ViewBuilding: 'Building', UpdateBuilding: 'Building', DeleteBuilding: 'Building', CreateIssue: 'Building', CreateInspection: 'Building', ViewBuildingAccess: 'Building', ManageBuildingRoles: 'Building', ViewIssue: 'Issue', UpdateIssue: 'Issue', DeleteIssue: 'Issue', ViewInspection: 'Inspection', UpdateInspection: 'Inspection', SubmitInspection: 'Inspection', ApproveInspection: 'Inspection', ReturnInspection: 'Inspection', ViewWorkOrder: 'WorkOrder', CompleteWorkOrder: 'WorkOrder', DeleteWorkOrder: 'WorkOrder', CreateWorkOrder: 'Issue',}; // The resource entity for a database row, followed by the building and organisation it belongs to.function resourceEntities(type, row) { switch (type) { case 'Organisation': return [organisationEntity(row.id)]; case 'Building': return [buildingEntity(row), organisationEntity(row.organisation_id)]; case 'Issue': return [issueEntity(row), buildingEntity({ id: row.building_id, organisation_id: row.organisation_id }), organisationEntity(row.organisation_id)]; case 'Inspection': return [inspectionEntity(row), buildingEntity({ id: row.building_id, organisation_id: row.organisation_id }), organisationEntity(row.organisation_id)]; case 'WorkOrder': { const { issue } = row; return [workOrderEntity(row), issueEntity(issue), buildingEntity({ id: issue.building_id, organisation_id: issue.organisation_id }), organisationEntity(issue.organisation_id)]; } default: throw new Error(`Unknown resource type ${type}`); }} // Builds the request part of an isAuthorized call for one user, action and database row.export function buildAuthorizationCall(user, action, row, context = {}) { const type = RESOURCE_TYPES[action]; if (!type) { throw new Error(`No Cedar resource type for action ${action}`); } const [resource, ...related] = resourceEntities(type, row); return { principal: ref('User', user.id), action: { type: 'Caretaker::Action', id: action }, resource: resource.uid, context, entities: [userEntity(user), resource, ...related], };}src/authz/schema.cedarschema changed
src/authz/schema.cedarschema// What Cedar may see in Caretaker, and in what shape. Version 2.
namespace Caretaker {
entity Organisation;
entity Building in [Organisation] = {
organisation: Organisation,
};
// Version 2: facts only. Each set holds exactly the rows the database has.
entity User = {
viewerBuildings: Set<Building>,
reporterBuildings: Set<Building>,
inspectorBuildings: Set<Building>,
adminBuildings: Set<Building>,
memberOrganisations: Set<Organisation>,
adminOrganisations: Set<Organisation>,
};
entity Issue in [Building] = {
building: Building,
status: String,
priority: String,
reportedBy?: User,
};
entity WorkOrder in [Issue] = {
issue: Issue,
assignee: User,
status: String,
createdBy?: User,
};
entity Inspection in [Building] = {
building: Building,
status: String,
createdBy?: User,
};
// Action groups. A policy about a group applies to every action in it.
action ReadBuildingData;
action AdministerBuilding;
action AdministerOrganisation;
action ViewOrganisation appliesTo { principal: [User], resource: [Organisation] };
action UpdateOrganisation, DeleteOrganisation, CreateBuilding in [AdministerOrganisation] appliesTo {
principal: [User],
resource: [Organisation],
};
action DeleteBuilding in [AdministerOrganisation] appliesTo { principal: [User], resource: [Building] };
action ViewMembers in [AdministerOrganisation] appliesTo { principal: [User], resource: [Organisation] };
action ManageMembers in [AdministerOrganisation] appliesTo {
principal: [User],
resource: [Organisation],
context: { targetUser: User, role: String },
};
action ViewBuilding in [ReadBuildingData] appliesTo { principal: [User], resource: [Building] };
action ViewIssue in [ReadBuildingData] appliesTo { principal: [User], resource: [Issue] };
action ViewInspection in [ReadBuildingData] appliesTo { principal: [User], resource: [Inspection] };
action CreateIssue, CreateInspection, UpdateBuilding in [AdministerBuilding] appliesTo { principal: [User], resource: [Building] };
action ViewBuildingAccess in [AdministerBuilding] appliesTo { principal: [User], resource: [Building] };
action ManageBuildingRoles in [AdministerBuilding] appliesTo {
principal: [User],
resource: [Building],
context: { targetUser: User, role: String },
};
action UpdateIssue, DeleteIssue in [AdministerBuilding] appliesTo { principal: [User], resource: [Issue] };
action UpdateInspection, SubmitInspection, ApproveInspection, ReturnInspection in [AdministerBuilding] appliesTo {
principal: [User],
resource: [Inspection],
};
action ViewWorkOrder in [ReadBuildingData] appliesTo { principal: [User], resource: [WorkOrder] };
action CompleteWorkOrder, DeleteWorkOrder in [AdministerBuilding] appliesTo {
principal: [User],
resource: [WorkOrder],
};
action CreateWorkOrder in [AdministerBuilding] appliesTo {
principal: [User],
resource: [Issue],
context: { assignee: User },
};
}
// What Cedar may see in Caretaker, and in what shape. Version 2.namespace Caretaker { entity Organisation; entity Building in [Organisation] = { organisation: Organisation, }; // Version 2: facts only. Each set holds exactly the rows the database has. entity User = { viewerBuildings: Set<Building>, reporterBuildings: Set<Building>, inspectorBuildings: Set<Building>, adminBuildings: Set<Building>, memberOrganisations: Set<Organisation>, adminOrganisations: Set<Organisation>, }; entity Issue in [Building] = { building: Building, status: String, priority: String, reportedBy?: User, }; entity WorkOrder in [Issue] = { issue: Issue, assignee: User, status: String, createdBy?: User, }; entity Inspection in [Building] = { building: Building, status: String, createdBy?: User, }; // Action groups. A policy about a group applies to every action in it. action ReadBuildingData; action AdministerBuilding; action AdministerOrganisation; action ViewOrganisation appliesTo { principal: [User], resource: [Organisation] }; action UpdateOrganisation, DeleteOrganisation, CreateBuilding in [AdministerOrganisation] appliesTo { principal: [User], resource: [Organisation], }; action DeleteBuilding in [AdministerOrganisation] appliesTo { principal: [User], resource: [Building] }; action ViewMembers in [AdministerOrganisation] appliesTo { principal: [User], resource: [Organisation] }; action ManageMembers in [AdministerOrganisation] appliesTo { principal: [User], resource: [Organisation], context: { targetUser: User, role: String }, }; action ViewBuilding in [ReadBuildingData] appliesTo { principal: [User], resource: [Building] }; action ViewIssue in [ReadBuildingData] appliesTo { principal: [User], resource: [Issue] }; action ViewInspection in [ReadBuildingData] appliesTo { principal: [User], resource: [Inspection] }; action CreateIssue, CreateInspection, UpdateBuilding in [AdministerBuilding] appliesTo { principal: [User], resource: [Building] }; action ViewBuildingAccess in [AdministerBuilding] appliesTo { principal: [User], resource: [Building] }; action ManageBuildingRoles in [AdministerBuilding] appliesTo { principal: [User], resource: [Building], context: { targetUser: User, role: String }, }; action UpdateIssue, DeleteIssue in [AdministerBuilding] appliesTo { principal: [User], resource: [Issue] }; action UpdateInspection, SubmitInspection, ApproveInspection, ReturnInspection in [AdministerBuilding] appliesTo { principal: [User], resource: [Inspection], }; action ViewWorkOrder in [ReadBuildingData] appliesTo { principal: [User], resource: [WorkOrder] }; action CompleteWorkOrder, DeleteWorkOrder in [AdministerBuilding] appliesTo { principal: [User], resource: [WorkOrder], }; action CreateWorkOrder in [AdministerBuilding] appliesTo { principal: [User], resource: [Issue], context: { assignee: User }, };}src/models/work-orders.js added
src/models/work-orders.jsimport { query } from '../db.js';
import { visibleBuildingCondition } from './scope.js';
// due_on is a date without time. Formatting it in SQL avoids JavaScript's Date shifting it by time zone.
const COLUMNS = `
ca.id, ca.issue_id, ca.title, ca.assignee_id, u.name AS assignee_name, ca.created_by,
to_char(ca.due_on, 'YYYY-MM-DD') AS due_on, ca.status, ca.completed_at`;
export async function listWorkOrders(issueId) {
const { rows } = await query(
`SELECT ${COLUMNS} FROM work_orders ca JOIN users u ON u.id = ca.assignee_id
WHERE ca.issue_id = $1 ORDER BY ca.status DESC, ca.due_on, ca.id`,
[issueId],
);
return rows;
}
// Bound to the issue in the URL: a work order of another issue is "not found" here.
export async function findWorkOrder(id, issueId) {
const { rows } = await query(
`SELECT ${COLUMNS} FROM work_orders ca JOIN users u ON u.id = ca.assignee_id
WHERE ca.id = $1 AND ca.issue_id = $2`,
[id, issueId],
);
return rows[0] ?? null;
}
// Users who may view issues at the building: the same condition as every list (lesson 5.3),
// with the user taken from each row (u.id) instead of a parameter.
export async function listEligibleAssignees(buildingId) {
const { rows } = await query(
`SELECT u.id, u.name FROM users u JOIN buildings s ON s.id = $1
WHERE ${visibleBuildingCondition('s', 'u.id')} ORDER BY u.name`,
[buildingId],
);
return rows;
}
export async function createWorkOrder({ issueId, title, assigneeId, dueOn, createdBy }) {
const { rows } = await query(
'INSERT INTO work_orders (issue_id, title, assignee_id, due_on, created_by) VALUES ($1, $2, $3, $4, $5) RETURNING id',
[issueId, title, assigneeId, dueOn, createdBy],
);
return rows[0];
}
export async function completeWorkOrder(id) {
const { rowCount } = await query("UPDATE work_orders SET status = 'done', completed_at = now() WHERE id = $1 AND status = 'open'", [id]);
return rowCount === 1;
}
export async function deleteWorkOrder(id) {
await query('DELETE FROM work_orders WHERE id = $1', [id]);
}
import { query } from '../db.js';import { visibleBuildingCondition } from './scope.js'; // due_on is a date without time. Formatting it in SQL avoids JavaScript's Date shifting it by time zone.const COLUMNS = ` ca.id, ca.issue_id, ca.title, ca.assignee_id, u.name AS assignee_name, ca.created_by, to_char(ca.due_on, 'YYYY-MM-DD') AS due_on, ca.status, ca.completed_at`; export async function listWorkOrders(issueId) { const { rows } = await query( `SELECT ${COLUMNS} FROM work_orders ca JOIN users u ON u.id = ca.assignee_id WHERE ca.issue_id = $1 ORDER BY ca.status DESC, ca.due_on, ca.id`, [issueId], ); return rows;} // Bound to the issue in the URL: a work order of another issue is "not found" here.export async function findWorkOrder(id, issueId) { const { rows } = await query( `SELECT ${COLUMNS} FROM work_orders ca JOIN users u ON u.id = ca.assignee_id WHERE ca.id = $1 AND ca.issue_id = $2`, [id, issueId], ); return rows[0] ?? null;} // Users who may view issues at the building: the same condition as every list (lesson 5.3),// with the user taken from each row (u.id) instead of a parameter.export async function listEligibleAssignees(buildingId) { const { rows } = await query( `SELECT u.id, u.name FROM users u JOIN buildings s ON s.id = $1 WHERE ${visibleBuildingCondition('s', 'u.id')} ORDER BY u.name`, [buildingId], ); return rows;} export async function createWorkOrder({ issueId, title, assigneeId, dueOn, createdBy }) { const { rows } = await query( 'INSERT INTO work_orders (issue_id, title, assignee_id, due_on, created_by) VALUES ($1, $2, $3, $4, $5) RETURNING id', [issueId, title, assigneeId, dueOn, createdBy], ); return rows[0];} export async function completeWorkOrder(id) { const { rowCount } = await query("UPDATE work_orders SET status = 'done', completed_at = now() WHERE id = $1 AND status = 'open'", [id]); return rowCount === 1;} export async function deleteWorkOrder(id) { await query('DELETE FROM work_orders WHERE id = $1', [id]);}src/routes/issues.js changed
src/routes/issues.jsimport express from 'express';
import { listIssues, findIssue, createIssue, updateIssue, deleteIssue, moveIssue, ISSUE_SORTS } from '../models/issues.js';
import { listBuildings, findBuilding, listVisibleBuildings } from '../models/buildings.js';
import { can } from '../authz/rules.js';
import { ref } from '../authz/entities.js';
import { listWorkOrders, findWorkOrder, listEligibleAssignees, createWorkOrder, completeWorkOrder, deleteWorkOrder } from '../models/work-orders.js';
import { notFound, forbidden } from '../lib/http.js';
import { PG_ERRORS } from '../db.js';
import { parseId } from '../lib/ids.js';
import { cleanText } from '../lib/validation.js';
export const issuesRouter = express.Router();
export const PRIORITIES = ['low', 'medium', 'high', 'critical'];
export const STATUSES = ['open', 'investigating', 'closed'];
const FIVE_MINUTES = 5 * 60 * 1000;
// <input type="datetime-local"> sends "2026-11-02T09:15" without a time zone. We treat it as UTC.
function parseDateTimeLocal(value) {
if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(value)) {
return null;
}
const date = new Date(`${value}:00Z`);
return Number.isNaN(date.getTime()) ? null : date;
}
// The reverse: a Date as "YYYY-MM-DDTHH:MM" in UTC, for the input's value attribute.
function toDateTimeLocal(date) {
return new Date(date).toISOString().slice(0, 16);
}
function validateIssue(input, { editing }) {
const errors = {};
const title = cleanText(input.title, { min: 3, max: 200 });
const description = cleanText(input.description, { max: 2000 });
const buildingId = parseId(input.building_id);
const occurredAt = parseDateTimeLocal(input.occurred_at);
const status = editing ? input.status : 'open';
if (!title.ok) {
errors.title = 'Title must be between 3 and 200 characters.';
}
if (!description.ok) {
errors.description = 'Description must be at most 2000 characters.';
}
if (!PRIORITIES.includes(input.priority)) {
errors.priority = `Priority must be one of: ${PRIORITIES.join(', ')}.`;
}
if (!editing && buildingId === null) {
errors.building_id = 'Choose a building.';
}
if (!occurredAt) {
errors.occurred_at = 'Enter the date and time it happened (UTC).';
} else if (occurredAt.getTime() > Date.now() + FIVE_MINUTES) {
errors.occurred_at = 'That time is in the future.';
}
if (!STATUSES.includes(status)) {
errors.status = `Status must be one of: ${STATUSES.join(', ')}.`;
}
// values: what the form shows again. record: what we store.
const values = {
title: title.text,
description: description.text,
priority: input.priority,
building_id: buildingId,
status,
occurred_at: typeof input.occurred_at === 'string' ? input.occurred_at : '',
};
const record = { ...values, occurred_at: occurredAt };
return { errors, values, record };
}
async function renderIssueForm(req, res, status, { issue = null, values = {}, errors = {} } = {}) {
const buildings = (await listBuildings()).filter((building) => can(req.user, 'CreateIssue', building));
res.status(status).render('issues/form', {
title: issue ? `Edit issue #${issue.id}` : 'Report an issue',
action: issue ? `/issues/${issue.id}/edit` : '/issues',
issue,
values,
errors,
buildings,
priorities: PRIORITIES,
statuses: STATUSES,
});
}
const PER_PAGE = 10;
// Converts the query string into list options. Invalid values become defaults.
function parseListQuery(query) {
const page = parseId(query.page) ?? 1;
return {
page,
sort: Object.hasOwn(ISSUE_SORTS, query.sort) ? query.sort : 'occurred_at',
dir: query.dir === 'asc' ? 'asc' : 'desc',
status: STATUSES.includes(query.status) ? query.status : null,
priority: PRIORITIES.includes(query.priority) ? query.priority : null,
building: parseId(query.building),
};
}
// Builds a /issues URL from the current options plus overrides, dropping defaults.
function listUrl(options, overrides = {}) {
const merged = { ...options, ...overrides };
const params = new URLSearchParams();
for (const [key, value] of Object.entries(merged)) {
const isDefault = value === null || (key === 'page' && value === 1) || (key === 'sort' && value === 'occurred_at') || (key === 'dir' && value === 'desc');
if (!isDefault) params.set(key, String(value));
}
const qs = params.toString();
return qs ? `/issues?${qs}` : '/issues';
}
async function loadIssue(req, res) {
const id = parseId(req.params.id);
const issue = id === null ? null : await findIssue(id);
if (!issue || !can(req.user, 'ViewIssue', issue)) {
notFound(req, res);
return null;
}
return issue;
}
issuesRouter.get('/', async (req, res) => {
const options = parseListQuery(req.query);
const { issues: rows, total } = await listIssues({ ...options, buildingId: options.building, perPage: PER_PAGE, userId: req.user.id });
// Defence in depth: the SQL filter should already match the policies. If a row on
// this page is denied by Cedar, hide it and report it: the two have drifted apart.
const issues = rows.filter((issue) => can(req.user, 'ViewIssue', issue));
if (issues.length !== rows.length) {
console.error('list/policy mismatch', { user: req.user.id, hidden: rows.filter((e) => !issues.includes(e)).map((e) => e.id) });
}
const buildings = await listVisibleBuildings(req.user.id);
res.render('issues/index', {
title: 'Maintenance issues',
issues,
total,
options,
buildings,
priorities: PRIORITIES,
statuses: STATUSES,
totalPages: Math.max(1, Math.ceil(total / PER_PAGE)),
listUrl: (overrides) => listUrl(options, overrides),
});
});
issuesRouter.get('/new', async (req, res) => {
await renderIssueForm(req, res, 200, { values: { occurred_at: toDateTimeLocal(new Date()) } });
});
issuesRouter.post('/', async (req, res) => {
const { errors, values, record } = validateIssue(req.body ?? {}, { editing: false });
if (Object.keys(errors).length > 0) {
return renderIssueForm(req, res, 400, { values, errors });
}
// The building id came from the form. Load the real building and check the user may report there.
const building = await findBuilding(record.building_id);
if (!building || !can(req.user, 'CreateIssue', building)) {
return renderIssueForm(req, res, 400, { values, errors: { building_id: 'Choose a building where you can report issues.' } });
}
let created;
try {
created = await createIssue(record, req.user.id);
} catch (err) {
if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) {
return renderIssueForm(req, res, 400, { values, errors: { building_id: 'Choose a building.' } });
}
throw err;
}
res.redirect(303, `/issues/${created.id}`);
});
// The issue page, with its work orders and (for people who may plan them) the add form.
async function renderIssuePage(req, res, status, issue, { values = {}, errors = {} } = {}) {
const actions = (await listWorkOrders(issue.id)).filter((a) => can(req.user, 'ViewWorkOrder', { ...a, issue }));
// UpdateIssue is allowed for exactly the people CreateWorkOrder permits (admins; the open issue's reporter).
const assignees = can(req.user, 'UpdateIssue', issue) ? await listEligibleAssignees(issue.building_id) : [];
res.status(status).render('issues/show', { title: issue.title, issue, actions, assignees, values, errors });
}
issuesRouter.get('/:id', async (req, res) => {
const issue = await loadIssue(req, res);
if (!issue) return;
await renderIssuePage(req, res, 200, issue);
});
function validateAction(input) {
const errors = {};
const title = cleanText(input.title, { min: 3, max: 200 });
const dueOn = typeof input.due_on === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(input.due_on) ? input.due_on : null;
const assigneeId = parseId(input.assignee_id);
if (!title.ok) errors.title = 'Title must be between 3 and 200 characters.';
if (!dueOn) errors.due_on = 'Choose a due date.';
if (assigneeId === null) errors.assignee_id = 'Choose who will do it.';
return { errors, values: { title: title.text, due_on: dueOn, assignee_id: assigneeId } };
}
// Loads a work order of THIS issue, or answers 404. Returns the work order with its issue attached.
async function loadAction(req, res, issue) {
const id = parseId(req.params.actionId);
const action = id === null ? null : await findWorkOrder(id, issue.id);
if (!action || !can(req.user, 'ViewWorkOrder', { ...action, issue })) {
notFound(req, res);
return null;
}
return { ...action, issue };
}
issuesRouter.post('/:id/actions', async (req, res) => {
const issue = await loadIssue(req, res);
if (!issue) return;
const { errors, values } = validateAction(req.body ?? {});
if (Object.keys(errors).length > 0) {
return renderIssuePage(req, res, 400, issue, { values, errors });
}
// Data rule: the assignee must be someone who may view this issue.
const eligible = await listEligibleAssignees(issue.building_id);
if (!eligible.some((u) => u.id === values.assignee_id)) {
return renderIssuePage(req, res, 400, issue, { values, errors: { assignee_id: 'Choose someone who can view this issue.' } });
}
if (!can(req.user, 'CreateWorkOrder', issue, { assignee: ref('User', values.assignee_id) })) {
return forbidden(res, 'You cannot assign this work order.');
}
await createWorkOrder({ issueId: issue.id, title: values.title, assigneeId: values.assignee_id, dueOn: values.due_on, createdBy: req.user.id });
req.flash('success', 'Work order added.');
res.redirect(303, `/issues/${issue.id}`);
});
issuesRouter.post('/:id/actions/:actionId/complete', async (req, res) => {
const issue = await loadIssue(req, res);
if (!issue) return;
const action = await loadAction(req, res, issue);
if (!action) return;
if (!can(req.user, 'CompleteWorkOrder', action)) return forbidden(res);
const done = await completeWorkOrder(action.id);
req.flash(done ? 'success' : 'error', done ? 'Marked as done.' : 'That work order was already done.');
res.redirect(303, `/issues/${issue.id}`);
});
issuesRouter.post('/:id/actions/:actionId/delete', async (req, res) => {
const issue = await loadIssue(req, res);
if (!issue) return;
const action = await loadAction(req, res, issue);
if (!action) return;
if (!can(req.user, 'DeleteWorkOrder', action)) return forbidden(res);
await deleteWorkOrder(action.id);
req.flash('success', 'Work order deleted.');
res.redirect(303, `/issues/${issue.id}`);
});
issuesRouter.get('/:id/edit', async (req, res) => {
const issue = await loadIssue(req, res);
if (!issue) return;
if (!can(req.user, 'UpdateIssue', issue)) return forbidden(res);
await renderIssueForm(req, res, 200, { issue, values: { ...issue, occurred_at: toDateTimeLocal(issue.occurred_at) } });
});
issuesRouter.post('/:id/edit', async (req, res) => {
const issue = await loadIssue(req, res);
if (!issue) return;
if (!can(req.user, 'UpdateIssue', issue)) return forbidden(res);
const { errors, values, record } = validateIssue(req.body ?? {}, { editing: true });
if (Object.keys(errors).length > 0) {
return renderIssueForm(req, res, 400, { issue, values, errors });
}
// The edit form cannot move an issue: the building stays the one we loaded.
await updateIssue(issue.id, { ...record, building_id: issue.building_id });
res.redirect(303, `/issues/${issue.id}`);
});
// Buildings this user may move the issue to: same organisation, another building, and CreateIssue allowed there.
async function moveDestinations(req, issue) {
return (await listBuildings()).filter((building) => building.organisation_id === issue.organisation_id
&& building.id !== issue.building_id
&& can(req.user, 'CreateIssue', building));
}
issuesRouter.get('/:id/move', async (req, res) => {
const issue = await loadIssue(req, res);
if (!issue) return;
if (!can(req.user, 'UpdateIssue', issue)) return forbidden(res);
res.render('issues/move', { title: `Move issue #${issue.id}`, issue, destinations: await moveDestinations(req, issue), error: null });
});
issuesRouter.post('/:id/move', async (req, res) => {
const issue = await loadIssue(req, res);
if (!issue) return;
// Source: the user must be allowed to change the issue where it is now.
if (!can(req.user, 'UpdateIssue', issue)) return forbidden(res);
// Destination: the client proposes a building id; everything else about the building comes from our database.
const buildingId = parseId(req.body?.building_id);
const destination = buildingId === null ? null : await findBuilding(buildingId);
const valid = destination
&& destination.id !== issue.building_id
&& destination.organisation_id === issue.organisation_id
&& can(req.user, 'CreateIssue', destination);
if (!valid) {
return res.status(400).render('issues/move', {
title: `Move issue #${issue.id}`, issue, destinations: await moveDestinations(req, issue),
error: 'Choose another building of this organisation where you can report issues.',
});
}
const moved = await moveIssue(issue.id, issue.building_id, destination.id);
req.flash(moved ? 'success' : 'error', moved ? `Moved to ${destination.name}.` : 'The issue changed while you were moving it. Try again.');
res.redirect(303, `/issues/${issue.id}`);
});
issuesRouter.post('/:id/delete', async (req, res) => {
const issue = await loadIssue(req, res);
if (!issue) return;
if (!can(req.user, 'DeleteIssue', issue)) return forbidden(res);
await deleteIssue(issue.id);
res.redirect(303, '/issues');
});
import express from 'express';import { listIssues, findIssue, createIssue, updateIssue, deleteIssue, moveIssue, ISSUE_SORTS } from '../models/issues.js';import { listBuildings, findBuilding, listVisibleBuildings } from '../models/buildings.js';import { can } from '../authz/rules.js';import { ref } from '../authz/entities.js';import { listWorkOrders, findWorkOrder, listEligibleAssignees, createWorkOrder, completeWorkOrder, deleteWorkOrder } from '../models/work-orders.js';import { notFound, forbidden } from '../lib/http.js';import { PG_ERRORS } from '../db.js';import { parseId } from '../lib/ids.js';import { cleanText } from '../lib/validation.js'; export const issuesRouter = express.Router(); export const PRIORITIES = ['low', 'medium', 'high', 'critical'];export const STATUSES = ['open', 'investigating', 'closed'];const FIVE_MINUTES = 5 * 60 * 1000; // <input type="datetime-local"> sends "2026-11-02T09:15" without a time zone. We treat it as UTC.function parseDateTimeLocal(value) { if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(value)) { return null; } const date = new Date(`${value}:00Z`); return Number.isNaN(date.getTime()) ? null : date;} // The reverse: a Date as "YYYY-MM-DDTHH:MM" in UTC, for the input's value attribute.function toDateTimeLocal(date) { return new Date(date).toISOString().slice(0, 16);} function validateIssue(input, { editing }) { const errors = {}; const title = cleanText(input.title, { min: 3, max: 200 }); const description = cleanText(input.description, { max: 2000 }); const buildingId = parseId(input.building_id); const occurredAt = parseDateTimeLocal(input.occurred_at); const status = editing ? input.status : 'open'; if (!title.ok) { errors.title = 'Title must be between 3 and 200 characters.'; } if (!description.ok) { errors.description = 'Description must be at most 2000 characters.'; } if (!PRIORITIES.includes(input.priority)) { errors.priority = `Priority must be one of: ${PRIORITIES.join(', ')}.`; } if (!editing && buildingId === null) { errors.building_id = 'Choose a building.'; } if (!occurredAt) { errors.occurred_at = 'Enter the date and time it happened (UTC).'; } else if (occurredAt.getTime() > Date.now() + FIVE_MINUTES) { errors.occurred_at = 'That time is in the future.'; } if (!STATUSES.includes(status)) { errors.status = `Status must be one of: ${STATUSES.join(', ')}.`; } // values: what the form shows again. record: what we store. const values = { title: title.text, description: description.text, priority: input.priority, building_id: buildingId, status, occurred_at: typeof input.occurred_at === 'string' ? input.occurred_at : '', }; const record = { ...values, occurred_at: occurredAt }; return { errors, values, record };} async function renderIssueForm(req, res, status, { issue = null, values = {}, errors = {} } = {}) { const buildings = (await listBuildings()).filter((building) => can(req.user, 'CreateIssue', building)); res.status(status).render('issues/form', { title: issue ? `Edit issue #${issue.id}` : 'Report an issue', action: issue ? `/issues/${issue.id}/edit` : '/issues', issue, values, errors, buildings, priorities: PRIORITIES, statuses: STATUSES, });} const PER_PAGE = 10; // Converts the query string into list options. Invalid values become defaults.function parseListQuery(query) { const page = parseId(query.page) ?? 1; return { page, sort: Object.hasOwn(ISSUE_SORTS, query.sort) ? query.sort : 'occurred_at', dir: query.dir === 'asc' ? 'asc' : 'desc', status: STATUSES.includes(query.status) ? query.status : null, priority: PRIORITIES.includes(query.priority) ? query.priority : null, building: parseId(query.building), };} // Builds a /issues URL from the current options plus overrides, dropping defaults.function listUrl(options, overrides = {}) { const merged = { ...options, ...overrides }; const params = new URLSearchParams(); for (const [key, value] of Object.entries(merged)) { const isDefault = value === null || (key === 'page' && value === 1) || (key === 'sort' && value === 'occurred_at') || (key === 'dir' && value === 'desc'); if (!isDefault) params.set(key, String(value)); } const qs = params.toString(); return qs ? `/issues?${qs}` : '/issues';} async function loadIssue(req, res) { const id = parseId(req.params.id); const issue = id === null ? null : await findIssue(id); if (!issue || !can(req.user, 'ViewIssue', issue)) { notFound(req, res); return null; } return issue;} issuesRouter.get('/', async (req, res) => { const options = parseListQuery(req.query); const { issues: rows, total } = await listIssues({ ...options, buildingId: options.building, perPage: PER_PAGE, userId: req.user.id }); // Defence in depth: the SQL filter should already match the policies. If a row on // this page is denied by Cedar, hide it and report it: the two have drifted apart. const issues = rows.filter((issue) => can(req.user, 'ViewIssue', issue)); if (issues.length !== rows.length) { console.error('list/policy mismatch', { user: req.user.id, hidden: rows.filter((e) => !issues.includes(e)).map((e) => e.id) }); } const buildings = await listVisibleBuildings(req.user.id); res.render('issues/index', { title: 'Maintenance issues', issues, total, options, buildings, priorities: PRIORITIES, statuses: STATUSES, totalPages: Math.max(1, Math.ceil(total / PER_PAGE)), listUrl: (overrides) => listUrl(options, overrides), });}); issuesRouter.get('/new', async (req, res) => { await renderIssueForm(req, res, 200, { values: { occurred_at: toDateTimeLocal(new Date()) } });}); issuesRouter.post('/', async (req, res) => { const { errors, values, record } = validateIssue(req.body ?? {}, { editing: false }); if (Object.keys(errors).length > 0) { return renderIssueForm(req, res, 400, { values, errors }); } // The building id came from the form. Load the real building and check the user may report there. const building = await findBuilding(record.building_id); if (!building || !can(req.user, 'CreateIssue', building)) { return renderIssueForm(req, res, 400, { values, errors: { building_id: 'Choose a building where you can report issues.' } }); } let created; try { created = await createIssue(record, req.user.id); } catch (err) { if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) { return renderIssueForm(req, res, 400, { values, errors: { building_id: 'Choose a building.' } }); } throw err; } res.redirect(303, `/issues/${created.id}`);}); // The issue page, with its work orders and (for people who may plan them) the add form.async function renderIssuePage(req, res, status, issue, { values = {}, errors = {} } = {}) { const actions = (await listWorkOrders(issue.id)).filter((a) => can(req.user, 'ViewWorkOrder', { ...a, issue })); // UpdateIssue is allowed for exactly the people CreateWorkOrder permits (admins; the open issue's reporter). const assignees = can(req.user, 'UpdateIssue', issue) ? await listEligibleAssignees(issue.building_id) : []; res.status(status).render('issues/show', { title: issue.title, issue, actions, assignees, values, errors });} issuesRouter.get('/:id', async (req, res) => { const issue = await loadIssue(req, res); if (!issue) return; await renderIssuePage(req, res, 200, issue);}); function validateAction(input) { const errors = {}; const title = cleanText(input.title, { min: 3, max: 200 }); const dueOn = typeof input.due_on === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(input.due_on) ? input.due_on : null; const assigneeId = parseId(input.assignee_id); if (!title.ok) errors.title = 'Title must be between 3 and 200 characters.'; if (!dueOn) errors.due_on = 'Choose a due date.'; if (assigneeId === null) errors.assignee_id = 'Choose who will do it.'; return { errors, values: { title: title.text, due_on: dueOn, assignee_id: assigneeId } };} // Loads a work order of THIS issue, or answers 404. Returns the work order with its issue attached.async function loadAction(req, res, issue) { const id = parseId(req.params.actionId); const action = id === null ? null : await findWorkOrder(id, issue.id); if (!action || !can(req.user, 'ViewWorkOrder', { ...action, issue })) { notFound(req, res); return null; } return { ...action, issue };} issuesRouter.post('/:id/actions', async (req, res) => { const issue = await loadIssue(req, res); if (!issue) return; const { errors, values } = validateAction(req.body ?? {}); if (Object.keys(errors).length > 0) { return renderIssuePage(req, res, 400, issue, { values, errors }); } // Data rule: the assignee must be someone who may view this issue. const eligible = await listEligibleAssignees(issue.building_id); if (!eligible.some((u) => u.id === values.assignee_id)) { return renderIssuePage(req, res, 400, issue, { values, errors: { assignee_id: 'Choose someone who can view this issue.' } }); } if (!can(req.user, 'CreateWorkOrder', issue, { assignee: ref('User', values.assignee_id) })) { return forbidden(res, 'You cannot assign this work order.'); } await createWorkOrder({ issueId: issue.id, title: values.title, assigneeId: values.assignee_id, dueOn: values.due_on, createdBy: req.user.id }); req.flash('success', 'Work order added.'); res.redirect(303, `/issues/${issue.id}`);}); issuesRouter.post('/:id/actions/:actionId/complete', async (req, res) => { const issue = await loadIssue(req, res); if (!issue) return; const action = await loadAction(req, res, issue); if (!action) return; if (!can(req.user, 'CompleteWorkOrder', action)) return forbidden(res); const done = await completeWorkOrder(action.id); req.flash(done ? 'success' : 'error', done ? 'Marked as done.' : 'That work order was already done.'); res.redirect(303, `/issues/${issue.id}`);}); issuesRouter.post('/:id/actions/:actionId/delete', async (req, res) => { const issue = await loadIssue(req, res); if (!issue) return; const action = await loadAction(req, res, issue); if (!action) return; if (!can(req.user, 'DeleteWorkOrder', action)) return forbidden(res); await deleteWorkOrder(action.id); req.flash('success', 'Work order deleted.'); res.redirect(303, `/issues/${issue.id}`);}); issuesRouter.get('/:id/edit', async (req, res) => { const issue = await loadIssue(req, res); if (!issue) return; if (!can(req.user, 'UpdateIssue', issue)) return forbidden(res); await renderIssueForm(req, res, 200, { issue, values: { ...issue, occurred_at: toDateTimeLocal(issue.occurred_at) } });}); issuesRouter.post('/:id/edit', async (req, res) => { const issue = await loadIssue(req, res); if (!issue) return; if (!can(req.user, 'UpdateIssue', issue)) return forbidden(res); const { errors, values, record } = validateIssue(req.body ?? {}, { editing: true }); if (Object.keys(errors).length > 0) { return renderIssueForm(req, res, 400, { issue, values, errors }); } // The edit form cannot move an issue: the building stays the one we loaded. await updateIssue(issue.id, { ...record, building_id: issue.building_id }); res.redirect(303, `/issues/${issue.id}`);}); // Buildings this user may move the issue to: same organisation, another building, and CreateIssue allowed there.async function moveDestinations(req, issue) { return (await listBuildings()).filter((building) => building.organisation_id === issue.organisation_id && building.id !== issue.building_id && can(req.user, 'CreateIssue', building));} issuesRouter.get('/:id/move', async (req, res) => { const issue = await loadIssue(req, res); if (!issue) return; if (!can(req.user, 'UpdateIssue', issue)) return forbidden(res); res.render('issues/move', { title: `Move issue #${issue.id}`, issue, destinations: await moveDestinations(req, issue), error: null });}); issuesRouter.post('/:id/move', async (req, res) => { const issue = await loadIssue(req, res); if (!issue) return; // Source: the user must be allowed to change the issue where it is now. if (!can(req.user, 'UpdateIssue', issue)) return forbidden(res); // Destination: the client proposes a building id; everything else about the building comes from our database. const buildingId = parseId(req.body?.building_id); const destination = buildingId === null ? null : await findBuilding(buildingId); const valid = destination && destination.id !== issue.building_id && destination.organisation_id === issue.organisation_id && can(req.user, 'CreateIssue', destination); if (!valid) { return res.status(400).render('issues/move', { title: `Move issue #${issue.id}`, issue, destinations: await moveDestinations(req, issue), error: 'Choose another building of this organisation where you can report issues.', }); } const moved = await moveIssue(issue.id, issue.building_id, destination.id); req.flash(moved ? 'success' : 'error', moved ? `Moved to ${destination.name}.` : 'The issue changed while you were moving it. Try again.'); res.redirect(303, `/issues/${issue.id}`);}); issuesRouter.post('/:id/delete', async (req, res) => { const issue = await loadIssue(req, res); if (!issue) return; if (!can(req.user, 'DeleteIssue', issue)) return forbidden(res); await deleteIssue(issue.id); res.redirect(303, '/issues');});src/seed.js changed
src/seed.jsimport { hashPassword } from './models/users.js';
// Every seeded user has this password. Local learning data only.
export const SEED_PASSWORD = 'password123';
export const users = [
{ id: 1, email: 'alice@example.test', name: 'Alice Byrne' },
{ id: 2, email: 'bob@example.test', name: 'Bob Okafor' },
{ id: 3, email: 'carol@example.test', name: 'Carol Duffy' },
{ id: 4, email: 'dave@example.test', name: 'Dave Murphy' },
{ id: 5, email: 'nora@example.test', name: 'Nora Quinn' },
{ id: 6, email: 'ravi@example.test', name: 'Ravi Shah' },
];
export const organisations = [
{ id: 1, name: 'Liffey Estates' },
{ id: 2, name: 'Harbour Lets' },
];
export const buildings = [
{ id: 10, organisationId: 1, name: 'Dublin Offices' },
{ id: 20, organisationId: 1, name: 'Cork Apartments' },
{ id: 30, organisationId: 2, name: 'Galway Studios' },
{ id: 40, organisationId: 2, name: 'Limerick House' },
];
const namedIssues = [
{ id: 101, buildingId: 10, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', occurredAt: '2026-11-02T09:15:00Z', description: 'The lift stopped between floors with nobody inside. Engineer called.' },
{ id: 102, buildingId: 10, title: 'Dripping tap in the second-floor kitchen', priority: 'low', status: 'closed', occurredAt: '2026-11-05T14:40:00Z', description: 'Worn washer. Tap replaced and floor dried.' },
{ id: 103, buildingId: 20, title: 'Front door lock sticks at entrance 4', priority: 'medium', status: 'open', occurredAt: '2026-11-08T07:05:00Z', description: 'The key turns only after several tries.' },
{ id: 104, buildingId: 20, title: 'Water stain on the ceiling of flat 7', priority: 'high', status: 'investigating', occurredAt: '2026-11-10T11:30:00Z', description: 'Stain about 40 cm wide. Roof drain to be checked.' },
{ id: 105, buildingId: 30, title: 'Boiler lost pressure in plant room', priority: 'critical', status: 'open', occurredAt: '2026-11-11T06:50:00Z', description: 'No heating on the ground floor.' },
{ id: 106, buildingId: 40, title: 'Car park barrier stuck open', priority: 'low', status: 'open', occurredAt: '2026-11-12T16:20:00Z', description: '' },
];
const fillerTitles = [
'Loose handrail on stairs',
'Bins not collected',
'Corridor light not working',
'Radiator cold in room 2',
'Window does not close fully',
'Loose floor tile at entrance',
'Toilet cistern keeps running',
'Blocked sink in kitchen',
];
// 24 extra issues (ids 107-130) alternate between buildings 10 and 20,
// so that lists have enough rows to page, sort and filter.
function fillerIssues() {
const priorities = ['low', 'medium', 'high', 'critical'];
const statuses = ['open', 'investigating', 'closed'];
const issues = [];
for (let i = 0; i < 24; i++) {
issues.push({
id: 107 + i,
buildingId: i % 2 === 0 ? 10 : 20,
title: `${fillerTitles[i % fillerTitles.length]} (#${107 + i})`,
priority: priorities[i % priorities.length],
status: statuses[i % statuses.length],
occurredAt: new Date(Date.UTC(2026, 9, 1 + i, 8 + (i % 9))).toISOString(),
description: '',
});
}
return issues;
}
export const issues = [...namedIssues, ...fillerIssues()];
// Organisation memberships: [userId, organisationId, role]
export const memberships = [
[1, 1, 'member'], // alice, Liffey
[2, 2, 'member'], // bob, Harbour Lets
[3, 1, 'org_admin'], // carol, Liffey
[4, 1, 'member'], // dave, Liffey
[6, 2, 'member'], // ravi, Harbour Lets
];
// Building role assignments. Ravi's was revoked by Bob on 20 November.
export const assignments = [
{ id: 1, userId: 1, buildingId: 10, role: 'building_admin', grantedBy: 3 },
{ id: 2, userId: 1, buildingId: 20, role: 'viewer', grantedBy: 3 },
{ id: 3, userId: 2, buildingId: 30, role: 'building_admin', grantedBy: null },
{ id: 4, userId: 4, buildingId: 10, role: 'inspector', grantedBy: 1 },
{ id: 5, userId: 4, buildingId: 20, role: 'reporter', grantedBy: 3 },
{ id: 6, userId: 6, buildingId: 30, role: 'viewer', grantedBy: 2, revokedBy: 2, revokedAt: '2026-11-20T10:00:00Z' },
];
export const inspections = [
{ id: 201, buildingId: 10, title: 'Q4 lift maintenance inspection', status: 'submitted', findings: 'Service log not signed for October. Emergency phone in lift 2 needs a new battery.' },
{ id: 202, buildingId: 10, title: 'Roof and gutter check, all four sides', status: 'submitted', findings: 'One blocked gutter on the north side.' },
{ id: 203, buildingId: 20, title: 'Door and lock check', status: 'draft', findings: '' },
{ id: 204, buildingId: 30, title: 'Boiler room review', status: 'draft', findings: '' },
];
export async function seed(client) {
await client.query('BEGIN');
try {
await client.query('TRUNCATE building_role_assignments, memberships, inspection_status_changes, inspections, issues, buildings, organisations, users RESTART IDENTITY CASCADE');
for (const u of users) {
await client.query(
'INSERT INTO users (id, email, name, password_hash) VALUES ($1, $2, $3, $4)',
[u.id, u.email, u.name, await hashPassword(SEED_PASSWORD)],
);
}
for (const o of organisations) {
await client.query('INSERT INTO organisations (id, name) VALUES ($1, $2)', [o.id, o.name]);
}
for (const s of buildings) {
await client.query('INSERT INTO buildings (id, organisation_id, name) VALUES ($1, $2, $3)', [s.id, s.organisationId, s.name]);
}
for (const e of issues) {
await client.query(
`INSERT INTO issues (id, building_id, title, description, priority, status, occurred_at)
VALUES ($1, $2, $3, $4, $5, $6, $7)`,
[e.id, e.buildingId, e.title, e.description, e.priority, e.status, e.occurredAt],
);
}
for (const a of inspections) {
await client.query(
`INSERT INTO inspections (id, building_id, title, findings, status, submitted_at)
VALUES ($1, $2, $3, $4, $5, CASE WHEN $5 = 'submitted' THEN now() END)`,
[a.id, a.buildingId, a.title, a.findings, a.status],
);
if (a.status === 'submitted') {
await client.query("INSERT INTO inspection_status_changes (inspection_id, from_status, to_status) VALUES ($1, 'draft', 'submitted')", [a.id]);
}
}
// Who reported each issue and created each inspection (see the scenario table in lesson 0.1).
await client.query(`UPDATE issues SET reported_by = CASE
WHEN id IN (101, 102) THEN 1 WHEN id IN (103, 104) THEN 4 WHEN id IN (105, 106) THEN 2
WHEN building_id = 10 THEN 1 WHEN building_id = 20 THEN 4 END`);
await client.query('UPDATE inspections SET created_by = CASE id WHEN 201 THEN 4 WHEN 202 THEN 1 WHEN 203 THEN 3 WHEN 204 THEN 2 END');
for (const [userId, organisationId, role] of memberships) {
await client.query('INSERT INTO memberships (user_id, organisation_id, role) VALUES ($1, $2, $3)', [userId, organisationId, role]);
}
for (const a of assignments) {
await client.query(
`INSERT INTO building_role_assignments (id, user_id, building_id, role, granted_by, granted_at, revoked_by, revoked_at)
VALUES ($1, $2, $3, $4, $5, '2026-11-01T09:00:00Z', $6, $7)`,
[a.id, a.userId, a.buildingId, a.role, a.grantedBy, a.revokedBy ?? null, a.revokedAt ?? null],
);
}
await client.query(
`INSERT INTO work_orders (id, issue_id, title, assignee_id, created_by, due_on)
VALUES (301, 101, 'Replace the lift door sensor on floor 2', 4, 1, '2026-12-15')`,
);
for (const table of ['users', 'organisations', 'buildings', 'issues', 'inspections', 'building_role_assignments', 'work_orders']) {
await client.query(`SELECT setval(pg_get_serial_sequence($1, 'id'), (SELECT max(id) FROM ${table}))`, [table]);
}
await client.query('COMMIT');
} catch (err) {
await client.query('ROLLBACK');
throw err;
}
}
import { hashPassword } from './models/users.js'; // Every seeded user has this password. Local learning data only.export const SEED_PASSWORD = 'password123'; export const users = [ { id: 1, email: 'alice@example.test', name: 'Alice Byrne' }, { id: 2, email: 'bob@example.test', name: 'Bob Okafor' }, { id: 3, email: 'carol@example.test', name: 'Carol Duffy' }, { id: 4, email: 'dave@example.test', name: 'Dave Murphy' }, { id: 5, email: 'nora@example.test', name: 'Nora Quinn' }, { id: 6, email: 'ravi@example.test', name: 'Ravi Shah' },]; export const organisations = [ { id: 1, name: 'Liffey Estates' }, { id: 2, name: 'Harbour Lets' },]; export const buildings = [ { id: 10, organisationId: 1, name: 'Dublin Offices' }, { id: 20, organisationId: 1, name: 'Cork Apartments' }, { id: 30, organisationId: 2, name: 'Galway Studios' }, { id: 40, organisationId: 2, name: 'Limerick House' },]; const namedIssues = [ { id: 101, buildingId: 10, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', occurredAt: '2026-11-02T09:15:00Z', description: 'The lift stopped between floors with nobody inside. Engineer called.' }, { id: 102, buildingId: 10, title: 'Dripping tap in the second-floor kitchen', priority: 'low', status: 'closed', occurredAt: '2026-11-05T14:40:00Z', description: 'Worn washer. Tap replaced and floor dried.' }, { id: 103, buildingId: 20, title: 'Front door lock sticks at entrance 4', priority: 'medium', status: 'open', occurredAt: '2026-11-08T07:05:00Z', description: 'The key turns only after several tries.' }, { id: 104, buildingId: 20, title: 'Water stain on the ceiling of flat 7', priority: 'high', status: 'investigating', occurredAt: '2026-11-10T11:30:00Z', description: 'Stain about 40 cm wide. Roof drain to be checked.' }, { id: 105, buildingId: 30, title: 'Boiler lost pressure in plant room', priority: 'critical', status: 'open', occurredAt: '2026-11-11T06:50:00Z', description: 'No heating on the ground floor.' }, { id: 106, buildingId: 40, title: 'Car park barrier stuck open', priority: 'low', status: 'open', occurredAt: '2026-11-12T16:20:00Z', description: '' },]; const fillerTitles = [ 'Loose handrail on stairs', 'Bins not collected', 'Corridor light not working', 'Radiator cold in room 2', 'Window does not close fully', 'Loose floor tile at entrance', 'Toilet cistern keeps running', 'Blocked sink in kitchen',]; // 24 extra issues (ids 107-130) alternate between buildings 10 and 20,// so that lists have enough rows to page, sort and filter.function fillerIssues() { const priorities = ['low', 'medium', 'high', 'critical']; const statuses = ['open', 'investigating', 'closed']; const issues = []; for (let i = 0; i < 24; i++) { issues.push({ id: 107 + i, buildingId: i % 2 === 0 ? 10 : 20, title: `${fillerTitles[i % fillerTitles.length]} (#${107 + i})`, priority: priorities[i % priorities.length], status: statuses[i % statuses.length], occurredAt: new Date(Date.UTC(2026, 9, 1 + i, 8 + (i % 9))).toISOString(), description: '', }); } return issues;} export const issues = [...namedIssues, ...fillerIssues()]; // Organisation memberships: [userId, organisationId, role]export const memberships = [ [1, 1, 'member'], // alice, Liffey [2, 2, 'member'], // bob, Harbour Lets [3, 1, 'org_admin'], // carol, Liffey [4, 1, 'member'], // dave, Liffey [6, 2, 'member'], // ravi, Harbour Lets]; // Building role assignments. Ravi's was revoked by Bob on 20 November.export const assignments = [ { id: 1, userId: 1, buildingId: 10, role: 'building_admin', grantedBy: 3 }, { id: 2, userId: 1, buildingId: 20, role: 'viewer', grantedBy: 3 }, { id: 3, userId: 2, buildingId: 30, role: 'building_admin', grantedBy: null }, { id: 4, userId: 4, buildingId: 10, role: 'inspector', grantedBy: 1 }, { id: 5, userId: 4, buildingId: 20, role: 'reporter', grantedBy: 3 }, { id: 6, userId: 6, buildingId: 30, role: 'viewer', grantedBy: 2, revokedBy: 2, revokedAt: '2026-11-20T10:00:00Z' },]; export const inspections = [ { id: 201, buildingId: 10, title: 'Q4 lift maintenance inspection', status: 'submitted', findings: 'Service log not signed for October. Emergency phone in lift 2 needs a new battery.' }, { id: 202, buildingId: 10, title: 'Roof and gutter check, all four sides', status: 'submitted', findings: 'One blocked gutter on the north side.' }, { id: 203, buildingId: 20, title: 'Door and lock check', status: 'draft', findings: '' }, { id: 204, buildingId: 30, title: 'Boiler room review', status: 'draft', findings: '' },]; export async function seed(client) { await client.query('BEGIN'); try { await client.query('TRUNCATE building_role_assignments, memberships, inspection_status_changes, inspections, issues, buildings, organisations, users RESTART IDENTITY CASCADE'); for (const u of users) { await client.query( 'INSERT INTO users (id, email, name, password_hash) VALUES ($1, $2, $3, $4)', [u.id, u.email, u.name, await hashPassword(SEED_PASSWORD)], ); } for (const o of organisations) { await client.query('INSERT INTO organisations (id, name) VALUES ($1, $2)', [o.id, o.name]); } for (const s of buildings) { await client.query('INSERT INTO buildings (id, organisation_id, name) VALUES ($1, $2, $3)', [s.id, s.organisationId, s.name]); } for (const e of issues) { await client.query( `INSERT INTO issues (id, building_id, title, description, priority, status, occurred_at) VALUES ($1, $2, $3, $4, $5, $6, $7)`, [e.id, e.buildingId, e.title, e.description, e.priority, e.status, e.occurredAt], ); } for (const a of inspections) { await client.query( `INSERT INTO inspections (id, building_id, title, findings, status, submitted_at) VALUES ($1, $2, $3, $4, $5, CASE WHEN $5 = 'submitted' THEN now() END)`, [a.id, a.buildingId, a.title, a.findings, a.status], ); if (a.status === 'submitted') { await client.query("INSERT INTO inspection_status_changes (inspection_id, from_status, to_status) VALUES ($1, 'draft', 'submitted')", [a.id]); } } // Who reported each issue and created each inspection (see the scenario table in lesson 0.1). await client.query(`UPDATE issues SET reported_by = CASE WHEN id IN (101, 102) THEN 1 WHEN id IN (103, 104) THEN 4 WHEN id IN (105, 106) THEN 2 WHEN building_id = 10 THEN 1 WHEN building_id = 20 THEN 4 END`); await client.query('UPDATE inspections SET created_by = CASE id WHEN 201 THEN 4 WHEN 202 THEN 1 WHEN 203 THEN 3 WHEN 204 THEN 2 END'); for (const [userId, organisationId, role] of memberships) { await client.query('INSERT INTO memberships (user_id, organisation_id, role) VALUES ($1, $2, $3)', [userId, organisationId, role]); } for (const a of assignments) { await client.query( `INSERT INTO building_role_assignments (id, user_id, building_id, role, granted_by, granted_at, revoked_by, revoked_at) VALUES ($1, $2, $3, $4, $5, '2026-11-01T09:00:00Z', $6, $7)`, [a.id, a.userId, a.buildingId, a.role, a.grantedBy, a.revokedBy ?? null, a.revokedAt ?? null], ); } await client.query( `INSERT INTO work_orders (id, issue_id, title, assignee_id, created_by, due_on) VALUES (301, 101, 'Replace the lift door sensor on floor 2', 4, 1, '2026-12-15')`, ); for (const table of ['users', 'organisations', 'buildings', 'issues', 'inspections', 'building_role_assignments', 'work_orders']) { await client.query(`SELECT setval(pg_get_serial_sequence($1, 'id'), (SELECT max(id) FROM ${table}))`, [table]); } await client.query('COMMIT'); } catch (err) { await client.query('ROLLBACK'); throw err; }}test/tenant-isolation.test.js changed
test/tenant-isolation.test.jsimport { test, before, after } from 'node:test';
import assert from 'node:assert/strict';
import { pool } from '../src/db.js';
import { resetDatabase, loginAs } from './helpers.js';
const TABLES = ['organisations', 'buildings', 'users', 'memberships', 'building_role_assignments', 'issues', 'inspections', 'inspection_status_changes', 'permission_changes', 'work_orders'];
async function fingerprint() {
const result = {};
for (const table of TABLES) {
const { rows } = await pool.query(`SELECT md5(coalesce(string_agg(t::text, '|' ORDER BY t::text), '')) AS hash FROM ${table} t`);
result[table] = rows[0].hash;
}
return result;
}
// Every route, pointed at Liffey (organisation 1, buildings 10 and 20).
const ATTACKS_ON_LIFFEY = [
['GET', '/organisations/1'],
['GET', '/organisations/1/edit'],
['POST', '/organisations/1/edit', { name: 'Taken over' }],
['POST', '/organisations/1/delete'],
['GET', '/organisations/1/members'],
['POST', '/organisations/1/members', { email: 'bob@example.test', role: 'org_admin' }],
['GET', '/organisations/1/buildings/new'],
['POST', '/organisations/1/buildings', { name: 'Hidden annex' }],
['GET', '/buildings/10'],
['GET', '/buildings/10/edit'],
['POST', '/buildings/10/edit', { name: 'Renamed' }],
['POST', '/buildings/10/delete'],
['GET', '/buildings/10/access'],
['POST', '/buildings/10/access', { user_id: '2', role: 'building_admin' }],
['POST', '/buildings/10/access/1/revoke'],
['GET', '/issues/101'],
['GET', '/issues/101/edit'],
['POST', '/issues/101/edit', { title: 'Changed', priority: 'low', status: 'closed', occurred_at: '2026-11-02T09:15' }],
['GET', '/issues/101/move'],
['POST', '/issues/101/move', { building_id: '30' }],
['POST', '/issues/101/delete'],
['POST', '/issues/101/actions', { title: 'Injected work order', assignee_id: '2', due_on: '2026-12-20' }],
['POST', '/issues/101/actions/301/complete'],
['POST', '/issues/101/actions/301/delete'],
['GET', '/inspections/201'],
['GET', '/inspections/203/edit'],
['POST', '/inspections/203/edit', { title: 'Changed', findings: '' }],
['POST', '/inspections/203/submit'],
['POST', '/inspections/201/approve'],
['POST', '/inspections/201/return'],
];
const CREATES_IN_LIFFEY = [
['POST', '/issues', { title: 'Injected issue', building_id: '10', priority: 'low', occurred_at: '2026-11-22T09:00' }],
['POST', '/inspections', { title: 'Injected inspection', building_id: '20', findings: '' }],
];
const send = (agent, [method, path, form]) => (method === 'GET' ? agent.get(path) : agent.post(path).type('form').send(form ?? {}));
let agents;
before(async () => {
await resetDatabase();
agents = { bob: await loginAs('bob'), ravi: await loginAs('ravi'), nora: await loginAs('nora') };
});
after(() => pool.end());
for (const name of ['bob', 'ravi', 'nora']) {
test(`${name} gets 404 for every Liffey route, and nothing changes`, async () => {
const before = await fingerprint();
const unexpected = [];
for (const attack of ATTACKS_ON_LIFFEY) {
const res = await send(agents[name], attack);
if (res.status !== 404) unexpected.push(`${attack[0]} ${attack[1]} -> ${res.status}`);
}
for (const attack of CREATES_IN_LIFFEY) {
const res = await send(agents[name], attack);
if (res.status !== 400) unexpected.push(`${attack[0]} ${attack[1]} -> ${res.status}`);
}
assert.deepEqual(unexpected, []);
assert.deepEqual(await fingerprint(), before);
});
}
test('inside one tenant: alice, a viewer at building 20, cannot change anything there', async () => {
const alice = await loginAs('alice');
const before = await fingerprint();
const attempts = [
['GET', '/issues/103/edit', 403],
['POST', '/issues/103/edit', 403, { title: 'Changed', priority: 'low', status: 'closed', occurred_at: '2026-11-08T07:05' }],
['POST', '/issues/104/delete', 403],
['GET', '/buildings/20/edit', 403],
['GET', '/buildings/20/access', 403],
['POST', '/buildings/20/access/5/revoke', 403],
['POST', '/buildings/10/access/5/revoke', 404],
['POST', '/inspections/203/submit', 403],
];
const unexpected = [];
for (const [method, path, expected, form] of attempts) {
const res = await send(alice, [method, path, form]);
if (res.status !== expected) unexpected.push(`${method} ${path} -> ${res.status}, expected ${expected}`);
}
assert.deepEqual(unexpected, []);
assert.deepEqual(await fingerprint(), before);
});
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import { pool } from '../src/db.js';import { resetDatabase, loginAs } from './helpers.js'; const TABLES = ['organisations', 'buildings', 'users', 'memberships', 'building_role_assignments', 'issues', 'inspections', 'inspection_status_changes', 'permission_changes', 'work_orders']; async function fingerprint() { const result = {}; for (const table of TABLES) { const { rows } = await pool.query(`SELECT md5(coalesce(string_agg(t::text, '|' ORDER BY t::text), '')) AS hash FROM ${table} t`); result[table] = rows[0].hash; } return result;} // Every route, pointed at Liffey (organisation 1, buildings 10 and 20).const ATTACKS_ON_LIFFEY = [ ['GET', '/organisations/1'], ['GET', '/organisations/1/edit'], ['POST', '/organisations/1/edit', { name: 'Taken over' }], ['POST', '/organisations/1/delete'], ['GET', '/organisations/1/members'], ['POST', '/organisations/1/members', { email: 'bob@example.test', role: 'org_admin' }], ['GET', '/organisations/1/buildings/new'], ['POST', '/organisations/1/buildings', { name: 'Hidden annex' }], ['GET', '/buildings/10'], ['GET', '/buildings/10/edit'], ['POST', '/buildings/10/edit', { name: 'Renamed' }], ['POST', '/buildings/10/delete'], ['GET', '/buildings/10/access'], ['POST', '/buildings/10/access', { user_id: '2', role: 'building_admin' }], ['POST', '/buildings/10/access/1/revoke'], ['GET', '/issues/101'], ['GET', '/issues/101/edit'], ['POST', '/issues/101/edit', { title: 'Changed', priority: 'low', status: 'closed', occurred_at: '2026-11-02T09:15' }], ['GET', '/issues/101/move'], ['POST', '/issues/101/move', { building_id: '30' }], ['POST', '/issues/101/delete'], ['POST', '/issues/101/actions', { title: 'Injected work order', assignee_id: '2', due_on: '2026-12-20' }], ['POST', '/issues/101/actions/301/complete'], ['POST', '/issues/101/actions/301/delete'], ['GET', '/inspections/201'], ['GET', '/inspections/203/edit'], ['POST', '/inspections/203/edit', { title: 'Changed', findings: '' }], ['POST', '/inspections/203/submit'], ['POST', '/inspections/201/approve'], ['POST', '/inspections/201/return'],]; const CREATES_IN_LIFFEY = [ ['POST', '/issues', { title: 'Injected issue', building_id: '10', priority: 'low', occurred_at: '2026-11-22T09:00' }], ['POST', '/inspections', { title: 'Injected inspection', building_id: '20', findings: '' }],]; const send = (agent, [method, path, form]) => (method === 'GET' ? agent.get(path) : agent.post(path).type('form').send(form ?? {})); let agents;before(async () => { await resetDatabase(); agents = { bob: await loginAs('bob'), ravi: await loginAs('ravi'), nora: await loginAs('nora') };});after(() => pool.end()); for (const name of ['bob', 'ravi', 'nora']) { test(`${name} gets 404 for every Liffey route, and nothing changes`, async () => { const before = await fingerprint(); const unexpected = []; for (const attack of ATTACKS_ON_LIFFEY) { const res = await send(agents[name], attack); if (res.status !== 404) unexpected.push(`${attack[0]} ${attack[1]} -> ${res.status}`); } for (const attack of CREATES_IN_LIFFEY) { const res = await send(agents[name], attack); if (res.status !== 400) unexpected.push(`${attack[0]} ${attack[1]} -> ${res.status}`); } assert.deepEqual(unexpected, []); assert.deepEqual(await fingerprint(), before); });} test('inside one tenant: alice, a viewer at building 20, cannot change anything there', async () => { const alice = await loginAs('alice'); const before = await fingerprint(); const attempts = [ ['GET', '/issues/103/edit', 403], ['POST', '/issues/103/edit', 403, { title: 'Changed', priority: 'low', status: 'closed', occurred_at: '2026-11-08T07:05' }], ['POST', '/issues/104/delete', 403], ['GET', '/buildings/20/edit', 403], ['GET', '/buildings/20/access', 403], ['POST', '/buildings/20/access/5/revoke', 403], ['POST', '/buildings/10/access/5/revoke', 404], ['POST', '/inspections/203/submit', 403], ]; const unexpected = []; for (const [method, path, expected, form] of attempts) { const res = await send(alice, [method, path, form]); if (res.status !== expected) unexpected.push(`${method} ${path} -> ${res.status}, expected ${expected}`); } assert.deepEqual(unexpected, []); assert.deepEqual(await fingerprint(), before);});test/work-orders.test.js added
test/work-orders.test.jsimport { test, before, after } from 'node:test';
import assert from 'node:assert/strict';
import { pool } from '../src/db.js';
import { resetDatabase, loginAs } from './helpers.js';
const agents = {};
before(async () => {
await resetDatabase();
for (const name of ['alice', 'bob', 'carol', 'dave']) agents[name] = await loginAs(name);
});
after(() => pool.end());
const form = (assigneeId) => ({ title: 'Reset the lift controller and test each floor', assignee_id: String(assigneeId), due_on: '2026-12-20' });
const statusOf = async (id) => (await pool.query('SELECT status FROM work_orders WHERE id = $1', [id])).rows[0]?.status;
const newestAction = async () => (await pool.query('SELECT max(id) AS id FROM work_orders')).rows[0].id;
test('add a work order to issue 101, assigned to dave', async () => {
const statuses = {};
for (const name of ['bob', 'dave', 'alice', 'carol']) statuses[name] = (await agents[name].post('/issues/101/actions').type('form').send(form(4))).status;
assert.deepEqual(statuses, { bob: 404, dave: 403, alice: 303, carol: 303 });
});
test('nobody assigns a work order to themselves', async () => {
const statuses = {};
for (const [name, id] of [['alice', 1], ['carol', 3], ['dave', 4]]) statuses[name] = (await agents[name].post('/issues/101/actions').type('form').send(form(id))).status;
assert.deepEqual(statuses, { alice: 403, carol: 403, dave: 403 });
});
test('mark done: the assignee, building admins and organisation admins', async () => {
assert.equal((await agents.bob.post('/issues/101/actions/301/complete')).status, 404);
assert.equal((await agents.dave.post('/issues/101/actions/301/complete')).status, 303);
assert.equal(await statusOf(301), 'done');
await agents.alice.post('/issues/101/actions').type('form').send(form(4));
const forAlice = await newestAction();
assert.equal((await agents.alice.post(`/issues/101/actions/${forAlice}/complete`)).status, 303);
assert.equal(await statusOf(forAlice), 'done');
await agents.alice.post('/issues/101/actions').type('form').send(form(4));
const forCarol = await newestAction();
assert.equal((await agents.carol.post(`/issues/101/actions/${forCarol}/complete`)).status, 303);
assert.equal(await statusOf(forCarol), 'done');
});
test('delete: building admins only', async () => {
const statuses = {};
for (const name of ['bob', 'dave', 'alice']) statuses[name] = (await agents[name].post('/issues/101/actions/301/delete')).status;
assert.deepEqual(statuses, { bob: 404, dave: 403, alice: 303 });
assert.equal(await statusOf(301), undefined);
});
test('the assignee must be able to view the issue', async () => {
const res = await agents.alice.post('/issues/101/actions').type('form').send(form(2));
assert.equal(res.status, 400);
assert.match(res.text, /Choose someone who can view this issue/);
});
test('a work order id from another issue is not found', async () => {
await agents.carol.post('/issues/103/actions').type('form').send(form(4));
const otherIssuesAction = await newestAction();
assert.equal((await agents.carol.post(`/issues/101/actions/${otherIssuesAction}/complete`)).status, 404);
assert.equal(await statusOf(otherIssuesAction), 'open');
});
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import { pool } from '../src/db.js';import { resetDatabase, loginAs } from './helpers.js'; const agents = {};before(async () => { await resetDatabase(); for (const name of ['alice', 'bob', 'carol', 'dave']) agents[name] = await loginAs(name);});after(() => pool.end()); const form = (assigneeId) => ({ title: 'Reset the lift controller and test each floor', assignee_id: String(assigneeId), due_on: '2026-12-20' });const statusOf = async (id) => (await pool.query('SELECT status FROM work_orders WHERE id = $1', [id])).rows[0]?.status;const newestAction = async () => (await pool.query('SELECT max(id) AS id FROM work_orders')).rows[0].id; test('add a work order to issue 101, assigned to dave', async () => { const statuses = {}; for (const name of ['bob', 'dave', 'alice', 'carol']) statuses[name] = (await agents[name].post('/issues/101/actions').type('form').send(form(4))).status; assert.deepEqual(statuses, { bob: 404, dave: 403, alice: 303, carol: 303 });}); test('nobody assigns a work order to themselves', async () => { const statuses = {}; for (const [name, id] of [['alice', 1], ['carol', 3], ['dave', 4]]) statuses[name] = (await agents[name].post('/issues/101/actions').type('form').send(form(id))).status; assert.deepEqual(statuses, { alice: 403, carol: 403, dave: 403 });}); test('mark done: the assignee, building admins and organisation admins', async () => { assert.equal((await agents.bob.post('/issues/101/actions/301/complete')).status, 404); assert.equal((await agents.dave.post('/issues/101/actions/301/complete')).status, 303); assert.equal(await statusOf(301), 'done'); await agents.alice.post('/issues/101/actions').type('form').send(form(4)); const forAlice = await newestAction(); assert.equal((await agents.alice.post(`/issues/101/actions/${forAlice}/complete`)).status, 303); assert.equal(await statusOf(forAlice), 'done'); await agents.alice.post('/issues/101/actions').type('form').send(form(4)); const forCarol = await newestAction(); assert.equal((await agents.carol.post(`/issues/101/actions/${forCarol}/complete`)).status, 303); assert.equal(await statusOf(forCarol), 'done');}); test('delete: building admins only', async () => { const statuses = {}; for (const name of ['bob', 'dave', 'alice']) statuses[name] = (await agents[name].post('/issues/101/actions/301/delete')).status; assert.deepEqual(statuses, { bob: 404, dave: 403, alice: 303 }); assert.equal(await statusOf(301), undefined);}); test('the assignee must be able to view the issue', async () => { const res = await agents.alice.post('/issues/101/actions').type('form').send(form(2)); assert.equal(res.status, 400); assert.match(res.text, /Choose someone who can view this issue/);}); test('a work order id from another issue is not found', async () => { await agents.carol.post('/issues/103/actions').type('form').send(form(4)); const otherIssuesAction = await newestAction(); assert.equal((await agents.carol.post(`/issues/101/actions/${otherIssuesAction}/complete`)).status, 404); assert.equal(await statusOf(otherIssuesAction), 'open');});views/issues/show.ejs changed
views/issues/show.ejs<%- include('../partials/head') %>
<p class="breadcrumbs"><a href="/issues">Issues</a> / #<%= issue.id %></p>
<div class="page-header">
<h1><%= issue.title %></h1>
<div class="actions">
<% if (can('UpdateIssue', issue)) { %>
<a class="btn" href="/issues/<%= issue.id %>/edit">Edit</a>
<a class="btn" href="/issues/<%= issue.id %>/move">Move</a>
<% } %>
<% if (can('DeleteIssue', issue)) { %>
<form method="post" action="/issues/<%= issue.id %>/delete" data-confirm="Delete this issue? This cannot be undone."><input type="hidden" name="_csrf" value="<%= csrfToken %>">
<button type="submit" class="btn btn-danger">Delete</button>
</form>
<% } %>
</div>
</div>
<dl class="details">
<dt>Building</dt><dd><%= issue.building_name %></dd>
<dt>Priority</dt><dd><span class="badge sev-<%= issue.priority %>"><%= issue.priority %></span></dd>
<dt>Status</dt><dd><span class="badge status-<%= issue.status %>"><%= issue.status %></span></dd>
<dt>Reported by</dt><dd><%= issue.reported_by_name ?? 'unknown' %></dd>
<dt>Occurred</dt><dd><%= formatDate(issue.occurred_at) %> UTC</dd>
<dt>Last updated</dt><dd><%= formatDate(issue.updated_at) %> UTC</dd>
</dl>
<% if (issue.description) { %>
<h2>Description</h2>
<p class="prose"><%= issue.description %></p>
<% } %>
<h2>Work orders</h2>
<% if (actions.length === 0) { %>
<p class="muted">No work orders yet.</p>
<% } else { %>
<table class="data">
<thead><tr><th>Work order</th><th>Assignee</th><th>Due</th><th>Status</th><th></th></tr></thead>
<tbody>
<% for (const a of actions) { const actionRef = { ...a, issue }; %>
<tr>
<td><%= a.title %></td>
<td><%= a.assignee_name %></td>
<td><%= a.due_on %></td>
<td><span class="badge status-<%= a.status === 'done' ? 'closed' : 'open' %>"><%= a.status %></span></td>
<td class="actions">
<% if (a.status === 'open' && can('CompleteWorkOrder', actionRef)) { %>
<form method="post" action="/issues/<%= issue.id %>/actions/<%= a.id %>/complete"><input type="hidden" name="_csrf" value="<%= csrfToken %>"><button type="submit" class="btn btn-small">Mark done</button></form>
<% } %>
<% if (can('DeleteWorkOrder', actionRef)) { %>
<form method="post" action="/issues/<%= issue.id %>/actions/<%= a.id %>/delete" data-confirm="Delete this work order?"><input type="hidden" name="_csrf" value="<%= csrfToken %>"><button type="submit" class="btn btn-small btn-danger">Delete</button></form>
<% } %>
</td>
</tr>
<% } %>
</tbody>
</table>
<% } %>
<% if (assignees.length > 0) { %>
<h3>Add a work order</h3>
<form method="post" action="/issues/<%= issue.id %>/actions" class="form" novalidate><input type="hidden" name="_csrf" value="<%= csrfToken %>">
<div class="field<%= errors.title ? ' has-error' : '' %>">
<label for="action-title">What needs to be done</label>
<input id="action-title" name="title" value="<%= values.title ?? '' %>" maxlength="200">
<% if (errors.title) { %><p class="field-error"><%= errors.title %></p><% } %>
</div>
<div class="field<%= errors.assignee_id ? ' has-error' : '' %>">
<label for="assignee_id">Assignee</label>
<select id="assignee_id" name="assignee_id">
<% for (const u of assignees) { %><option value="<%= u.id %>"<%= values.assignee_id === u.id ? ' selected' : '' %>><%= u.name %></option><% } %>
</select>
<% if (errors.assignee_id) { %><p class="field-error"><%= errors.assignee_id %></p><% } %>
</div>
<div class="field<%= errors.due_on ? ' has-error' : '' %>">
<label for="due_on">Due</label>
<input id="due_on" name="due_on" type="date" value="<%= values.due_on ?? '' %>">
<% if (errors.due_on) { %><p class="field-error"><%= errors.due_on %></p><% } %>
</div>
<div class="form-actions"><button type="submit" class="btn btn-primary">Add work order</button></div>
</form>
<% } %>
<%- include('../partials/foot') %>
<%- include('../partials/head') %><p class="breadcrumbs"><a href="/issues">Issues</a> / #<%= issue.id %></p><div class="page-header"> <h1><%= issue.title %></h1> <div class="actions"> <% if (can('UpdateIssue', issue)) { %> <a class="btn" href="/issues/<%= issue.id %>/edit">Edit</a> <a class="btn" href="/issues/<%= issue.id %>/move">Move</a> <% } %> <% if (can('DeleteIssue', issue)) { %> <form method="post" action="/issues/<%= issue.id %>/delete" data-confirm="Delete this issue? This cannot be undone."><input type="hidden" name="_csrf" value="<%= csrfToken %>"> <button type="submit" class="btn btn-danger">Delete</button> </form> <% } %> </div></div><dl class="details"> <dt>Building</dt><dd><%= issue.building_name %></dd> <dt>Priority</dt><dd><span class="badge sev-<%= issue.priority %>"><%= issue.priority %></span></dd> <dt>Status</dt><dd><span class="badge status-<%= issue.status %>"><%= issue.status %></span></dd> <dt>Reported by</dt><dd><%= issue.reported_by_name ?? 'unknown' %></dd> <dt>Occurred</dt><dd><%= formatDate(issue.occurred_at) %> UTC</dd> <dt>Last updated</dt><dd><%= formatDate(issue.updated_at) %> UTC</dd></dl><% if (issue.description) { %> <h2>Description</h2> <p class="prose"><%= issue.description %></p><% } %> <h2>Work orders</h2><% if (actions.length === 0) { %> <p class="muted">No work orders yet.</p><% } else { %> <table class="data"> <thead><tr><th>Work order</th><th>Assignee</th><th>Due</th><th>Status</th><th></th></tr></thead> <tbody> <% for (const a of actions) { const actionRef = { ...a, issue }; %> <tr> <td><%= a.title %></td> <td><%= a.assignee_name %></td> <td><%= a.due_on %></td> <td><span class="badge status-<%= a.status === 'done' ? 'closed' : 'open' %>"><%= a.status %></span></td> <td class="actions"> <% if (a.status === 'open' && can('CompleteWorkOrder', actionRef)) { %> <form method="post" action="/issues/<%= issue.id %>/actions/<%= a.id %>/complete"><input type="hidden" name="_csrf" value="<%= csrfToken %>"><button type="submit" class="btn btn-small">Mark done</button></form> <% } %> <% if (can('DeleteWorkOrder', actionRef)) { %> <form method="post" action="/issues/<%= issue.id %>/actions/<%= a.id %>/delete" data-confirm="Delete this work order?"><input type="hidden" name="_csrf" value="<%= csrfToken %>"><button type="submit" class="btn btn-small btn-danger">Delete</button></form> <% } %> </td> </tr> <% } %> </tbody> </table><% } %> <% if (assignees.length > 0) { %> <h3>Add a work order</h3> <form method="post" action="/issues/<%= issue.id %>/actions" class="form" novalidate><input type="hidden" name="_csrf" value="<%= csrfToken %>"> <div class="field<%= errors.title ? ' has-error' : '' %>"> <label for="action-title">What needs to be done</label> <input id="action-title" name="title" value="<%= values.title ?? '' %>" maxlength="200"> <% if (errors.title) { %><p class="field-error"><%= errors.title %></p><% } %> </div> <div class="field<%= errors.assignee_id ? ' has-error' : '' %>"> <label for="assignee_id">Assignee</label> <select id="assignee_id" name="assignee_id"> <% for (const u of assignees) { %><option value="<%= u.id %>"<%= values.assignee_id === u.id ? ' selected' : '' %>><%= u.name %></option><% } %> </select> <% if (errors.assignee_id) { %><p class="field-error"><%= errors.assignee_id %></p><% } %> </div> <div class="field<%= errors.due_on ? ' has-error' : '' %>"> <label for="due_on">Due</label> <input id="due_on" name="due_on" type="date" value="<%= values.due_on ?? '' %>"> <% if (errors.due_on) { %><p class="field-error"><%= errors.due_on %></p><% } %> </div> <div class="form-actions"><button type="submit" class="btn btn-primary">Add work order</button></div> </form><% } %><%- include('../partials/foot') %>Project tree at this checkpoint
.env.example
.env.test
.gitignore
.npmrc
README.md
compose.yaml
db/init/01-create-test-database.sql
migrations/001_create_organisations_buildings_issues.sql
migrations/002_create_inspections.sql
migrations/003_create_users.sql
migrations/004_create_session_table.sql
migrations/005_create_memberships_and_building_roles.sql
migrations/006_create_permission_changes.sql
migrations/007_create_work_orders.sql
package-lock.json
package.json
public/css/style.css
public/js/app.js
scripts/authz-bench.js
scripts/authz-explain.js
scripts/cedar-errors-demo.js
scripts/cedar-hello.js
scripts/forged-entity-demo.js
scripts/migrate.js
scripts/partial-demo.js
scripts/reset.js
scripts/seed.js
scripts/template-demo.js
scripts/validate-policies.js
services/authz-service.js
services/start-authz-service.js
src/app.js
src/authz/authorize.js
src/authz/cedar.js
src/authz/entities.js
src/authz/policies/assignee-completes-work-order.cedar
src/authz/policies/building-admin.cedar
src/authz/policies/building-read.cedar
src/authz/policies/forbid-building-admin-grants.cedar
src/authz/policies/forbid-self-approval.cedar
src/authz/policies/forbid-self-assignment.cedar
src/authz/policies/forbid-self-membership-change.cedar
src/authz/policies/forbid-self-role-change.cedar
src/authz/policies/inspector-create-inspection.cedar
src/authz/policies/inspector-own-inspections.cedar
src/authz/policies/org-admin.cedar
src/authz/policies/org-member.cedar
src/authz/policies/reporter-create-issue.cedar
src/authz/policies/reporter-creates-work-orders.cedar
src/authz/policies/reporter-own-issues.cedar
src/authz/policy-store.js
src/authz/request.js
src/authz/rules.js
src/authz/schema.cedarschema
src/config.js
src/db.js
src/lib/http.js
src/lib/ids.js
src/lib/validation.js
src/middleware/auth.js
src/middleware/csrf.js
src/middleware/flash.js
src/middleware/rate-limit.js
src/middleware/security-headers.js
src/migrate.js
src/models/access.js
src/models/assignments.js
src/models/buildings.js
src/models/dashboard.js
src/models/inspections.js
src/models/issues.js
src/models/members.js
src/models/organisations.js
src/models/scope.js
src/models/users.js
src/models/work-orders.js
src/routes/account.js
src/routes/auth.js
src/routes/buildings.js
src/routes/inspections.js
src/routes/issues.js
src/routes/organisations.js
src/seed.js
src/server.js
test/access-matrix.test.js
test/access.test.js
test/auth.test.js
test/authz-decisions.test.js
test/authz-service.test.js
test/building-access.test.js
test/buildings.test.js
test/csrf.test.js
test/dashboard.test.js
test/forged-input.test.js
test/hardening.test.js
test/helpers.js
test/inspections.test.js
test/isolation.test.js
test/issue-authz.test.js
test/issue-list.test.js
test/issue-moves.test.js
test/issues.test.js
test/list-parity.test.js
test/members.test.js
test/organisations.test.js
test/policies.test.js
test/rate-limit.test.js
test/require-login.test.js
test/resource-authz.test.js
test/tenant-isolation.test.js
test/work-orders.test.js
views/account.ejs
views/auth/login.ejs
views/auth/register.ejs
views/buildings/access.ejs
views/buildings/form.ejs
views/buildings/show.ejs
views/dashboard.ejs
views/error.ejs
views/forbidden.ejs
views/inspections/form.ejs
views/inspections/index.ejs
views/inspections/show.ejs
views/issues/form.ejs
views/issues/index.ejs
views/issues/move.ejs
views/issues/show.ejs
views/not-found.ejs
views/organisations/form.ejs
views/organisations/index.ejs
views/organisations/members.ejs
views/organisations/show.ejs
views/partials/foot.ejs
views/partials/head.ejs
views/partials/nav.ejs