Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
7a51c15
fix(web): date an in-person session when it is submitted, not when th…
joshunrau Nov 19, 2026
3fcf3cd
feat(web): record the time of day of a retrospective session
joshunrau Nov 19, 2026
2cbbecb
fix(api): export when each record and session was collected, with the…
joshunrau Nov 19, 2026
d5d749d
feat: let a group require a form to be completed when a session starts
joshunrau Nov 19, 2026
2204b3e
test(subject-utils): pin the name hash to its known outputs
joshunrau Nov 19, 2026
e13ac82
build(subject-utils): pin transliteration to exactly 2.6.1
joshunrau Nov 19, 2026
8593679
fix(web): say what the name hash really ignores in the name help text
joshunrau Nov 19, 2026
6f7ebe4
docs: describe what the name hash really ignores
joshunrau Nov 19, 2026
de18aba
refactor: move the subject id scoping rule into subject-utils
joshunrau Nov 19, 2026
e19bdc1
fix(web): stop CSV upload scoping a name hash to the group
joshunrau Nov 19, 2026
168938b
feat(web): split the settings page into tabs and fold the mail server…
joshunrau Nov 19, 2026
b231a53
fix(web): hide the remote assignments settings on an instance without…
joshunrau Nov 19, 2026
bcb6ae6
feat(subject-utils): derive a subject id from custom identifying fields
joshunrau Nov 19, 2026
ad1a542
docs(subject-utils): list the scoping and custom-fields exports
joshunrau Nov 19, 2026
10d64a3
feat(api): store an administrator's definition of fields that identif…
joshunrau Nov 19, 2026
4b575bd
feat: identify subjects by the fields an administrator defines
joshunrau Nov 19, 2026
3d38770
feat(web): define the fields that identify subjects on the settings page
joshunrau Nov 19, 2026
b45ce85
feat: choose which identification methods an instance offers
joshunrau Nov 19, 2026
80a9834
chore: update route tree
joshunrau Nov 19, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 19 additions & 11 deletions .agents/docs/architecture/auth-and-permissions.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,17 @@ that they may read _some_ subject; the `where` decides whether they may read _th
one; the guard turns a missing one into a 500. Nothing checks the value. Routes whose declaration is not the ordinary
`{ action, subject }` on the model they serve:

| Route | Declaration | Why it is safe |
| --------------------------------- | --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `POST /v1/auth/login` | `'public'` | `@ThrottleLoginRequest()`; credentials checked in `AuthService.login`. |
| `GET /v1/setup` | `'public'` | Returns only `SetupState`. |
| `POST /v1/setup` | `'public'` | **`SetupService.initApp` drops the whole database.** It refuses only when `isSetup` is true and `NODE_ENV` is not `development`. |
| `DELETE /v1/setup` | `{ action: 'delete', subject: 'all' }` | Also refuses unless `NODE_ENV === 'test'`. |
| `GET /v1/gateway/healthcheck` | `[]` | Any login token. The module loads only when `GATEWAY_ENABLED`. |
| `POST /v1/instruments` | `{ action: 'manage', subject: 'Instrument' }` | No base level grants it, so admin-only in practice. The one `@AcceptsInstrumentToken()` route (below). |
| `PATCH /v1/users/self-update/:id` | `{ action: 'read', subject: 'User' }` | Deliberately weak; `UsersService.updateSelfById` refuses unless `id === currentUser.id`. |
| `GET /v1/summary` | five `read` rules | The only multi-element array; all five must pass. |
| Route | Declaration | Why it is safe |
| ------------------------------------------ | --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `POST /v1/auth/login` | `'public'` | `@ThrottleLoginRequest()`; credentials checked in `AuthService.login`. |
| `GET /v1/setup` | `'public'` | Returns only `SetupState`. |
| `POST /v1/setup` | `'public'` | **`SetupService.initApp` drops the whole database.** It refuses only when `isSetup` is true and `NODE_ENV` is not `development`. |
| `DELETE /v1/setup` | `{ action: 'delete', subject: 'all' }` | Also refuses unless `NODE_ENV === 'test'`. |
| `GET /v1/gateway/healthcheck` | `[]` | Any login token. The module loads only when `GATEWAY_ENABLED`. |
| `POST /v1/instruments` | `{ action: 'manage', subject: 'Instrument' }` | No base level grants it, so admin-only in practice. The one `@AcceptsInstrumentToken()` route (below). |
| `PATCH /v1/users/self-update/:id` | `{ action: 'read', subject: 'User' }` | Deliberately weak; `UsersService.updateSelfById` refuses unless `id === currentUser.id`. |
| `GET /v1/summary` | five `read` rules | The only multi-element array; all five must pass. |
| `GET /v1/subjects/identification/settings` | `{ action: 'read', subject: 'Subject' }` | Serves the instance's `SetupState` definition of custom identifying fields, salt included, because the browser of anyone who identifies subjects derives their ids from it. Never on the public `GET /v1/setup`. |

Adding a fourth `'public'` route or a second `[]` is a security decision: raise it rather than
deciding alone.
Expand All @@ -40,7 +41,7 @@ route, `POST /v1/groups` per #1468, and `PATCH /v1/groups/:id/archive` and `/una
replaced a `DELETE /v1/groups/:id` that a group manager's `manage Group` reached; `$UpdateGroupData`
omits `archivedAt`, so `PATCH /v1/groups/:id` cannot archive either), and where the data crosses
groups with nothing to scope it by (audit logs, the instrument series overview, every repository's
sync log, mail settings). Most handlers carry their reason in a comment;
sync log, mail settings, the count of subjects by identification method). Most handlers carry their reason in a comment;
`grep -rn 'RouteAccess(ADMIN_ONLY)' apps/api/src` lists them. `UsersService` refuses an admin
archiving, disabling or demoting their own account, so the last admin cannot lock every `ADMIN_ONLY`
route.
Expand All @@ -50,6 +51,13 @@ route.
`ADMIN_ONLY` guard; and `InstrumentsService.findBundleById` called without a `currentUser`, which the
API's gateway module does to resolve an assignment's bundle. That parameter is optional for this
reason, so a new call site that omits it compiles and reads every group's instruments.
`StartSessionService` rolls back unscoped: when the record of a session instrument fails to save,
it deletes the session it just created and, if `SubjectsService.exists` (a boolean, unscoped
because a scoped lookup would miss a subject in another group) found no subject beforehand, the
subject too. `SessionsService.createMany` rolls back the same way. `SubjectsService.hasCustomFieldsSubjects`
(whether any id has the `cf_` prefix, which locks the instance-wide definition; only a boolean leaves
it) and `SubjectsService.countByIdentificationMethod` (every group's subjects, behind `ADMIN_ONLY`)
read across groups on purpose.

## Layer 2: row scoping

Expand Down
2 changes: 1 addition & 1 deletion .agents/docs/playbooks/add-web-route.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ run the generator.
it first.

10. **Add the tests.** A unit test named after the route file, in a `__tests__/` folder beside it
(`routes/_app/admin/__tests__/mail.test.tsx` tests `routes/_app/admin/mail.tsx`), and an e2e test
(`routes/_app/admin/__tests__/settings.test.tsx` tests `routes/_app/admin/settings.tsx`), and an e2e test
— `.agents/docs/playbooks/add-e2e-test.md`.

## Verify
Expand Down
29 changes: 29 additions & 0 deletions apps/api/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ enum GroupType {
enum SubjectIdentificationMethod {
CUSTOM_ID
PERSONAL_INFO
CUSTOM_FIELDS
}

type GroupSettings {
Expand All @@ -107,6 +108,8 @@ type GroupSettings {
idValidationRegexErrorMessage LocalizedString?
subjectIdDisplayLength Int?
minimumAge Int?
// A form instrument that must be completed to start a session in the group, if any.
sessionInstrumentId String?
}

// Mirrors $LocalizedString in @opendatacapture/schemas/core; each field is optional so
Expand Down Expand Up @@ -520,6 +523,31 @@ type MailTemplate {
subject LocalizedString?
}

// One field an administrator defines for identifying subjects. Fields are hashed in the order they
// are stored, so a field's position is its identity.
type CustomIdentificationField {
description LocalizedString?
label LocalizedString
pattern String
patternErrorMessage LocalizedString?
}

// The salt and the iteration count are generated with the first definition and never change: every
// id derived from the fields depends on them, and the values typed into the fields are not stored.
type CustomFieldsDefinition {
fields CustomIdentificationField[]
iterations Int
label LocalizedString
salt String
}

// An empty list of offered methods is one an administrator never chose, which offers the built-in
// two; once chosen, at least one is offered.
type SubjectIdentificationSettings {
customFields CustomFieldsDefinition?
offeredMethods SubjectIdentificationMethod[]
}

model SetupState {
createdAt DateTime @default(now()) @db.Date
updatedAt DateTime @updatedAt @db.Date
Expand All @@ -533,6 +561,7 @@ model SetupState {
isSetup Boolean
mailConfig MailConfig?
newUserEmailTemplate MailTemplate?
subjectIdentificationSettings SubjectIdentificationSettings?
tableColorMode TableColorMode?

@@map("SetupStateModel")
Expand Down
72 changes: 71 additions & 1 deletion apps/api/src/groups/__tests__/groups.service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { beforeEach, describe, expect, it } from 'vitest';

import { AuditLogger } from '@/audit/audit.logger';
import { createAppAbility } from '@/auth/ability.utils';
import { InstrumentsService } from '@/instruments/instruments.service';

import { GroupsService } from '../groups.service';

Expand All @@ -30,20 +31,23 @@ describe('GroupsService', () => {
let groupsService: GroupsService;
let groupModel: MockedInstance<Model<'Group'>>;
let instrumentModel: MockedInstance<Model<'Instrument'>>;
let instrumentsService: MockedInstance<InstrumentsService>;

beforeEach(async () => {
const moduleRef = await Test.createTestingModule({
providers: [
GroupsService,
MockFactory.createForModelToken(getModelToken('Group')),
MockFactory.createForModelToken(getModelToken('Instrument')),
MockFactory.createForService(AuditLogger)
MockFactory.createForService(AuditLogger),
MockFactory.createForService(InstrumentsService)
]
}).compile();
auditLogger = moduleRef.get(AuditLogger);
groupModel = moduleRef.get(getModelToken('Group'));
instrumentModel = moduleRef.get(getModelToken('Instrument'));
groupsService = moduleRef.get(GroupsService);
instrumentsService = moduleRef.get(InstrumentsService);
instrumentModel.findMany.mockResolvedValue([]);
});

Expand Down Expand Up @@ -335,6 +339,72 @@ describe('GroupsService', () => {
});
});

describe('updateById with a session instrument', () => {
const groupRequiring = (sessionInstrumentId: null | string) => ({
accessibleInstrumentIds: ['form-1', 'form-2'],
name: 'Test Group',
settings: { sessionInstrumentId }
});

const accessibleInstruments = (...ids: string[]) => {
instrumentModel.findMany.mockResolvedValueOnce(ids.map((id) => ({ id })));
};

it("should refuse an update dropping the session instrument from the group's instruments, even one not naming the setting", async () => {
groupModel.findFirst.mockResolvedValueOnce(groupRequiring('form-1'));
accessibleInstruments('form-2');
await expect(groupsService.updateById('123', { accessibleInstrumentIds: ['form-2'] })).rejects.toThrow(
/before removing instrument 'form-1'/
);
expect(groupModel.update).not.toHaveBeenCalled();
});

it('should refuse a session instrument the group cannot access, saying so rather than asking to remove it', async () => {
groupModel.findFirst.mockResolvedValueOnce(groupRequiring(null));
const update = groupsService.updateById('123', { settings: { sessionInstrumentId: 'form-3' } });
await expect(update).rejects.toBeInstanceOf(BadRequestException);
await expect(update).rejects.toThrow(/instrument 'form-3' is not$/);
expect(groupModel.update).not.toHaveBeenCalled();
});

it('should refuse a session instrument that is not a form, since only a form is rendered when a session starts', async () => {
groupModel.findFirst.mockResolvedValueOnce(groupRequiring(null));
instrumentsService.findById.mockResolvedValueOnce({ kind: 'INTERACTIVE' });
await expect(
groupsService.updateById('123', { settings: { sessionInstrumentId: 'form-1' } })
).rejects.toBeInstanceOf(BadRequestException);
expect(groupModel.update).not.toHaveBeenCalled();
});

it("should look the new session instrument up within the caller's ability and the group", async () => {
const ability = createAppAbility([{ action: 'manage', subject: 'all' }]);
groupModel.findFirst.mockResolvedValueOnce(groupRequiring(null));
instrumentsService.findById.mockResolvedValueOnce({ kind: 'FORM' });
await groupsService.updateById('123', { settings: { sessionInstrumentId: 'form-1' } }, { ability });
expect(instrumentsService.findById).toHaveBeenCalledWith('form-1', { ability }, ['123']);
expect(groupModel.update.mock.lastCall?.[0]).toMatchObject({
data: { settings: { sessionInstrumentId: 'form-1' } }
});
});

it('should accept dropping the session instrument from the group once the setting is cleared in the same update', async () => {
groupModel.findFirst.mockResolvedValueOnce(groupRequiring('form-1'));
accessibleInstruments('form-2');
await groupsService.updateById('123', {
accessibleInstrumentIds: ['form-2'],
settings: { sessionInstrumentId: null }
});
expect(groupModel.update.mock.lastCall?.[0]).toMatchObject({ data: { settings: { sessionInstrumentId: null } } });
});

it('should not look the session instrument up again when the update leaves it as it was', async () => {
groupModel.findFirst.mockResolvedValueOnce(groupRequiring('form-1'));
await groupsService.updateById('123', { settings: { sessionInstrumentId: 'form-1' } });
expect(instrumentsService.findById).not.toHaveBeenCalled();
expect(groupModel.update).toHaveBeenCalled();
});
});

describe('findAll', () => {
it('should return the array returned by the group model', async () => {
groupModel.findMany.mockResolvedValueOnce([{ name: 'Test Group' }]);
Expand Down
3 changes: 3 additions & 0 deletions apps/api/src/groups/groups.module.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import { Module } from '@nestjs/common';

import { InstrumentsModule } from '@/instruments/instruments.module';

import { GroupsController } from './groups.controller';
import { GroupsService } from './groups.service';

@Module({
controllers: [GroupsController],
exports: [GroupsService],
imports: [InstrumentsModule],
providers: [GroupsService]
})
export class GroupsModule {}
52 changes: 51 additions & 1 deletion apps/api/src/groups/groups.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@ import { PrismaClientKnownRequestError } from '@prisma/client/runtime/library';
import { AuditLogger } from '@/audit/audit.logger';
import { accessibleQuery } from '@/auth/ability.utils';
import type { EntityOperationOptions } from '@/core/types';
import { InstrumentsService } from '@/instruments/instruments.service';

@Injectable()
export class GroupsService {
constructor(
@InjectModel('Group') private readonly groupModel: Model<'Group'>,
@InjectModel('Instrument') private readonly instrumentModel: Model<'Instrument'>,
private readonly auditLogger: AuditLogger
private readonly auditLogger: AuditLogger,
private readonly instrumentsService: InstrumentsService
) {}

async archiveById(id: string, currentUser: RequestUser) {
Expand Down Expand Up @@ -124,6 +126,15 @@ export class GroupsService {
});
validInstrumentIds = existingInstruments.map(({ id }) => id);
}
await this.validateSessionInstrument(
{
accessibleInstrumentIds: validInstrumentIds ?? group.accessibleInstrumentIds,
groupId: id,
sessionInstrumentId: settings?.sessionInstrumentId,
storedSessionInstrumentId: group.settings.sessionInstrumentId
},
{ ability }
);

try {
return await this.groupModel.update({
Expand Down Expand Up @@ -204,4 +215,43 @@ export class GroupsService {
throw new BadRequestException(`No email template with id '${nextActiveId}' exists in this group`);
}
}

/**
* Every update is checked, not only one naming the session instrument: removing the instrument from
* the group's accessible list would otherwise leave every Start Session in the group requiring a
* form no one in it can open.
*/
private async validateSessionInstrument(
{
accessibleInstrumentIds,
groupId,
sessionInstrumentId,
storedSessionInstrumentId
}: {
accessibleInstrumentIds: string[];
groupId: string;
sessionInstrumentId: null | string | undefined;
storedSessionInstrumentId: null | string | undefined;
},
options: EntityOperationOptions
): Promise<void> {
// `undefined` leaves the stored value alone; `null` removes it.
const nextSessionInstrumentId = sessionInstrumentId === undefined ? storedSessionInstrumentId : sessionInstrumentId;
if (!nextSessionInstrumentId) {
return;
}
if (!accessibleInstrumentIds.includes(nextSessionInstrumentId)) {
throw new BadRequestException(
nextSessionInstrumentId === storedSessionInstrumentId
? `The group's Session Instrument must be one of its accessible instruments: set the Session Instrument to another form, or to none, before removing instrument '${nextSessionInstrumentId}'`
: `The group's Session Instrument must be one of its accessible instruments, and instrument '${nextSessionInstrumentId}' is not`
);
}
if (nextSessionInstrumentId !== storedSessionInstrumentId) {
const instrument = await this.instrumentsService.findById(nextSessionInstrumentId, options, [groupId]);
if (instrument.kind !== 'FORM') {
throw new BadRequestException(`The group's Session Instrument must be a form, not '${instrument.kind}'`);
}
}
}
}
Loading
Loading