Naalya Handbook
School featuresMicrosoft 365 sync

Webhooks and subscriptions

The public webhook that receives Graph notifications, the registry entity that routes them to a school, and the chain that self-renews subscriptions.

A subscription is a standing request that says "call this URL whenever a user changes." This page covers the webhook that receives those calls, the registry row that routes an anonymous notification back to the right school, and how a subscription keeps itself alive.

The public webhook

The webhook is the only public surface here. Graph delivers notifications with no bearer token, so the route is marked @Public(): it skips the normal auth guard. It also has two completely different jobs depending on how it's called.

The first is a one-time validation handshake. When you create a subscription, Graph immediately POSTs to your notification URL with a ?validationToken query param, and you have ten seconds to echo it back as plain text. Fail that and the subscription is never created:

apps/server/src/app/microsoft-sync/microsoft-sync.controller.ts
@Public()
@Post('webhook')
@HttpCode(HttpStatus.ACCEPTED)
async webhook(
  @Query('validationToken') validationToken: string | undefined,
  @Body() body: MicrosoftChangeNotificationPayload | undefined,
  @Res() res: Response,
) {
  // Microsoft sends a validation request as a POST with ?validationToken=<token>.
  // Respond 200 + the token as plain text within 10 seconds.
  if (validationToken) {
    return res.status(HttpStatus.OK).contentType('text/plain').send(validationToken);
  }

  // Real notifications: route + authenticate each one inside the service,
  // then always acknowledge the batch with 202.
  for (const notification of body?.value ?? []) {
    await this.syncService.enqueueNotification(notification);
  }
  return res.status(HttpStatus.ACCEPTED).json({ accepted: true });
}

The second job is the real one. Notice the controller does the bare minimum, it loops over the batch and hands each notification to the service, then returns 202 Accepted with { "accepted": true }. It never decides whether a notification is valid; that's the service's job, and an invalid one is logged and skipped without ever failing the HTTP response. The full authentication path lives on the sync flow page.

The webhook's operationId is microsoftSyncWebhook. The other four routes need the system role SOFTWARE_DEVELOPER; the school screen at /staff-hub/school/directory-sync calls them (see Portal routes).

Method and pathoperationIdInputSuccess
POST /api/v1/microsoft-sync/subscriptionscreateMicrosoftSyncSubscriptionBody CreateSubscriptionDto: schoolId (UUID)201, SubscriptionResponseDto. The operation text says an existing active subscription for the school is returned instead of creating another
GET /api/v1/microsoft-sync/subscriptionslistMicrosoftSyncSubscriptionsQuery schoolId (UUID, ParseUUIDPipe)200, array of SubscriptionResponseDto
DELETE /api/v1/microsoft-sync/subscriptions/:subscriptionIddeleteMicrosoftSyncSubscriptionUUID subscriptionId. The signed-in user id is passed as the actor200, { "message": "Subscription deleted" }. 404 when the service reports the subscription missing (ApiNotFoundErrorResponse)
POST /api/v1/microsoft-sync/sync-userssyncMicrosoftUsersBody SyncUsersDto: schoolId (UUID)201, SyncUsersResponseDto { "queued": number } from syncAllUsers. The operation text says 502 when Microsoft returns no users
CaseResult
Webhook with validationToken200 text/plain, the token
Webhook: unknown change, missing resource id, unknown subscription, clientState or tenant mismatchLogged and skipped; the batch still gets 202
Caller without the roleYou do not have the required role to access this resource (the Swagger text Software Developer role required. differs)
School with no Microsoft appSchool configuration not found or This school has no Microsoft app configured
syncMicrosoftUsers when Graph returns no usersMicrosoft returned no users, so nothing was synced.
Delete when Graph returns 404 and there is no local rowSubscription not found

The registry entity

A subscription isn't only a thing in Microsoft's cloud: the API keeps its own row for every one it creates, because the webhook needs to answer two questions instantly: which school does this subscriptionId belong to? and is the clientState secret correct? That row is MicrosoftSubscriptionEntity:

apps/server/src/app/microsoft-sync/entities/microsoft-subscription.entity.ts
@Entity('microsoft_subscription')
@WithTimestamps()
export class MicrosoftSubscriptionEntity extends DatabaseEntity {
  @Index()
  @Column({ name: 'school_id', type: 'uuid' })
  schoolId: string;

  @Index({ unique: true })
  @Column({ name: 'subscription_id', unique: true })
  subscriptionId: string;       // the Graph subscription id: the webhook routing key

  @Column({ name: 'client_state_secret' })
  clientStateSecret: string;    // per-school random secret, echoed back as clientState

  @Column({ default: 'users' })
  resource: string;             // the Graph resource watched

  @Column({ name: 'expiration_date_time', type: 'timestamptz' })
  expirationDateTime: Date;
}

Not tenant-scoped

The single most important thing about this entity is what it isn't: it is deliberately not @TenantScoped. Almost every entity in the codebase is tenant-scoped, so queries automatically filter to the current school (see Multi-Tenancy). This one can't be: the webhook runs with no school context, and it has to read this table to discover the school in the first place. Scoping it would make that impossible: a chicken-and-egg lock-out.

The clientState secret is per-school and never reused

clientStateSecret is generated fresh with crypto.randomBytes(32) for each subscription. It is the shared secret Graph echoes back on every notification, and it's how the webhook proves a notification is genuinely for this school. Because it's unique per school, a leak is contained to one tenant: it can't be replayed against another.

Self-renewal

A Graph users subscription has a hard ceiling: Microsoft caps its lifetime at roughly 29 days. Let it lapse and notifications simply stop: no error, just silence. So the system renews itself ahead of expiry. Every create and every renew schedules a delayed BullMQ job to renew again, comfortably inside the window:

apps/server/src/app/microsoft-sync/microsoft-sync.service.ts
const SUBSCRIPTION_TTL_MS = 29 * 24 * 60 * 60 * 1000;   // Graph's max for /users
const RENEWAL_DELAY_MS    = 25 * 24 * 60 * 60 * 1000;   // renew at ~25 days

private async scheduleRenewal(subscriptionId: string, schoolId?: string): Promise<void> {
  await this.syncQueue.add('renew-subscription',
    { action: MicrosoftSyncAction.RENEW_SUBSCRIPTION, microsoftUserId: '', subscriptionId, schoolId },
    { delay: RENEWAL_DELAY_MS, jobId: renewalJobId(subscriptionId) },   // jobId = `renew-${id}`
  );
}

The jobId is deterministic, renew-{subscriptionId}, so scheduling twice gives one delayed job, not two. When the renewal job fires, renewSubscription PATCHes a new expiry onto the Graph subscription, updates the registry row, and calls scheduleRenewal again. The intent is a chain that only stops when the subscription is deleted.

The chain probably stops after the first renewal

Re-read on 29 November 2026 at API staging ed0e56f87083d7d10466b61b97948f7e855c1c03. microsoft-sync.service.ts, microsoft-sync.processor.ts, and app.module.ts are not among the 36 files that differ from API main d0fbb4030a82d967dabf2924f2dd2bdf69de3af0, so this is the same code on both branches. Inferred from that code and the BullMQ documentation. No subscription was created, and /queues was not opened.

renewSubscription runs inside the job whose id is renew-{subscriptionId}. It then adds the next renewal with that same id while the current job still exists. BullMQ's documentation says a job added with an id that already exists in the queue is ignored and not added. The queue's default job options in app.module.ts set only attempts: 3, with no removeOnComplete, so the finished renewal job also stays in Redis under that id. Read together, the second renewal is never queued, and the subscription would lapse about 54 days after it was created (25 days to the first renewal, then the new 29-day expiry).

The unit tests cover scheduling on create and removal on delete. No test calls renewSubscription. The spec was read and not run.

A lapsed subscription raises no error; notifications just stop. To confirm, look in /queues on a school that subscribed more than 25 days ago: no delayed renew-{subscriptionId} job means the chain has stopped.

Where to go next

On this page