forked from scratchfoundation/scratch-editor
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhandler.ts
More file actions
4428 lines (4050 loc) · 170 KB
/
Copy pathhandler.ts
File metadata and controls
4428 lines (4050 loc) · 170 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { APIGatewayProxyEventV2, APIGatewayProxyResultV2, APIGatewayProxyStructuredResultV2 } from 'aws-lambda';
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import {
DynamoDBDocumentClient,
PutCommand,
GetCommand,
QueryCommand,
ScanCommand,
DeleteCommand,
UpdateCommand,
BatchWriteCommand,
} from '@aws-sdk/lib-dynamodb';
import {
S3Client,
PutObjectCommand,
GetObjectCommand,
DeleteObjectCommand,
CopyObjectCommand,
HeadObjectCommand,
} from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { OAuth2Client } from 'google-auth-library';
import { createRemoteJWKSet, jwtVerify } from 'jose';
import * as crypto from 'crypto';
// --- Configuration ---
const CLASSROOMS_TABLE = process.env.CLASSROOMS_TABLE_NAME || 'Classrooms';
const MEMBERSHIPS_TABLE = process.env.MEMBERSHIPS_TABLE_NAME || 'ClassroomMemberships';
const SUBMISSIONS_TABLE = process.env.SUBMISSIONS_TABLE_NAME || 'ClassroomSubmissions';
const KICK_REQUESTS_TABLE = process.env.KICK_REQUESTS_TABLE_NAME || 'ClassroomKickRequests';
const GROUPS_TABLE = process.env.GROUPS_TABLE_NAME || 'ClassroomGroups';
const SUBMISSIONS_BUCKET = process.env.SUBMISSIONS_BUCKET_NAME || 'smalruby-classroom-submissions';
// みんなの課題 — nationwide shared assignment library (EPIC #1066)
const SHARED_ASSIGNMENTS_TABLE = process.env.SHARED_ASSIGNMENTS_TABLE_NAME || 'SharedAssignments';
const SHARED_REPORTS_TABLE = process.env.SHARED_REPORTS_TABLE_NAME || 'SharedAssignmentReports';
const SHARED_BUCKET = process.env.SHARED_BUCKET_NAME || 'smalruby-shared-assignments';
const GOOGLE_CLIENT_ID = process.env.GOOGLE_CLIENT_ID || '';
const MICROSOFT_CLIENT_ID = process.env.MICROSOFT_CLIENT_ID || '';
const DEV_BYPASS_TOKEN = process.env.DEV_BYPASS_TOKEN || '';
const STAGE = process.env.STAGE || 'stg';
const CORS_ALLOWED_ORIGINS = (process.env.CORS_ALLOWED_ORIGINS || '').split(',').map(o => o.trim());
const MAX_CLASS_NAME_LENGTH = 50;
const MAX_STUDENT_COUNT = parseInt(process.env.MAX_STUDENT_COUNT || '50', 10);
const MAX_NICKNAME_LENGTH = 20;
// 6-digit alphanumeric, excluding confusing chars (I, O, 0, 1)
const JOIN_CODE_CHARS = 'abcdefghjklmnpqrstuvwxyz23456789';
const JOIN_CODE_LENGTH = 6;
// Classroom TTL from environment (default 90 days — covers a school term so
// term-end batch evaluation can still read every submission)
const CLASSROOM_TTL_DAYS = parseInt(process.env.CLASSROOM_TTL_DAYS || '90', 10);
const CLASSROOM_TTL_SECONDS = CLASSROOM_TTL_DAYS * 24 * 60 * 60;
// Session and membership TTL matches classroom TTL
const SESSION_TTL_SECONDS = CLASSROOM_TTL_SECONDS;
// Token expiry is validated by each provider's library:
// - Google: google-auth-library checks exp automatically
// - Microsoft: jose jwtVerify checks exp automatically
// No custom ID_TOKEN_MAX_AGE_SECONDS check needed.
// Rate limiting for join endpoint (per IP)
const JOIN_RATE_LIMIT_WINDOW_SECONDS = parseInt(process.env.JOIN_RATE_LIMIT_WINDOW_SECONDS || '60', 10);
const JOIN_RATE_LIMIT_MAX_ATTEMPTS = parseInt(process.env.JOIN_RATE_LIMIT_MAX_ATTEMPTS || '50', 10);
const JOIN_CODE_REGEX = new RegExp(`^[${JOIN_CODE_CHARS}]{${JOIN_CODE_LENGTH}}$`);
// Session activity TTL — determines "seated" status for teachers (default 1 hour)
const SESSION_ACTIVE_TTL_SECONDS = parseInt(process.env.SESSION_ACTIVE_TTL_SECONDS || '3600', 10);
// Submission config (TTL matches classroom TTL)
const SUBMISSION_TTL_SECONDS = CLASSROOM_TTL_SECONDS;
const MAX_PROJECT_NAME_LENGTH = 100;
const PRESIGNED_URL_UPLOAD_EXPIRY = parseInt(process.env.PRESIGNED_URL_UPLOAD_EXPIRY || '300', 10); // default 5 minutes
const PRESIGNED_URL_DOWNLOAD_EXPIRY = parseInt(process.env.PRESIGNED_URL_DOWNLOAD_EXPIRY || '3600', 10); // default 1 hour
const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MB
const MAX_SCREENSHOT_COUNT = 20;
const MAX_TEACHER_COMMENT_LENGTH = 500;
// Kick request TTL: short-lived (1h) since the student is actively waiting
// for the teacher to act. Expired requests are removed by DynamoDB TTL.
const KICK_REQUEST_TTL_SECONDS = parseInt(process.env.KICK_REQUEST_TTL_SECONDS || '3600', 10);
const MAX_KICK_REQUEST_REASON_LENGTH = 200;
// Group (組) metadata TTL: groups are the teacher's year-long organizing
// concept and carry no student work, so they outlive the 90-day classroom
// retention. 400 days covers a school year (April–March) plus a buffer.
const GROUP_TTL_DAYS = parseInt(process.env.GROUP_TTL_DAYS || '400', 10);
const GROUP_TTL_SECONDS = GROUP_TTL_DAYS * 24 * 60 * 60;
const MAX_GROUP_NAME_LENGTH = 50;
// How many prior lessons of the same group to inspect when looking up the
// student's previous returned comment on join (personalized recap).
const PREVIOUS_COMMENT_LOOKBACK = 3;
// みんなの課題 (EPIC #1066): shared items are permanent (no TTL), so quota
// counters reuse the Classrooms table's reserved key space (TTL-cleaned)
// instead. Retention decisions: spike #1067 D10-D12.
const SHARE_DAILY_LIMIT = parseInt(process.env.SHARE_DAILY_LIMIT || '10', 10);
const REPORT_DAILY_LIMIT = parseInt(process.env.REPORT_DAILY_LIMIT || '20', 10);
const SHARED_STARTER_MAX_BYTES = parseInt(process.env.SHARED_STARTER_MAX_BYTES || String(50 * 1024 * 1024), 10);
const SHARED_REPORT_TTL_SECONDS = 90 * 24 * 60 * 60;
const SHARED_LIST_PAGE_SIZE = 30;
const MAX_SHARED_TITLE_LENGTH = 50;
const MAX_SHARED_SUMMARY_LENGTH = 100;
const MAX_SHARED_TAGS = 5;
const MAX_SHARED_TAG_LENGTH = 20;
const MAX_SUPPLEMENT_URL_LENGTH = 500;
const MAX_AUTHOR_NAME_LENGTH = 30;
const MAX_AUTHOR_AFFILIATION_LENGTH = 50;
const MAX_SHARED_REPORT_REASON_LENGTH = 200;
// Class (旧組) v2 data model: every assignment (Classrooms record) belongs to
// a class (ClassroomGroups record), and class-level GC linkage / co-teachers /
// studentCount are authoritative. The version is stamped on each group record
// so the client can trigger the one-time bulk migration when it sees older
// (or missing) versions on first class-list view.
const CLASSROOM_SCHEMA_VERSION = 2;
const MAX_TOPICS_PER_CLASS = 20;
const MAX_TOPIC_NAME_LENGTH = 50;
// Assignment content (lesson delivery): teacher-authored pages of
// (short text + optional image) plus an optional starter project, attached to
// a classroom. Objects live under {classroomId}/assignment/ in the
// submissions bucket and share its lifecycle expiry.
const MAX_ASSIGNMENT_PAGES = 10;
const MAX_ASSIGNMENT_PAGE_TEXT_LENGTH = 500;
// Content types accepted for assignment page images (MIME → S3 key extension).
const ASSIGNMENT_IMAGE_CONTENT_TYPES: Record<string, string> = {
'image/png': 'png',
'image/jpeg': 'jpg',
};
// AI evaluation support (teacher-facing): the Lambda relays static-analysis
// results to the Anthropic API and returns grade proposals / comment drafts.
// One call handles at most EVAL_MAX_SUBMISSIONS submissions so the response
// fits API Gateway's hard 30s integration timeout — the client chunks a
// whole class into several calls (the cached system prompt is shared).
const ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY || '';
const CLAUDE_MODEL = process.env.CLAUDE_MODEL || 'claude-haiku-4-5-20251001';
const EVAL_MAX_SUBMISSIONS = parseInt(process.env.EVAL_MAX_SUBMISSIONS || '10', 10);
const EVAL_MAX_PSEUDOCODE_LENGTH = parseInt(process.env.EVAL_MAX_PSEUDOCODE_LENGTH || '4000', 10);
const EVAL_RATE_LIMIT_WINDOW_SECONDS = parseInt(process.env.EVAL_RATE_LIMIT_WINDOW_SECONDS || '3600', 10);
const EVAL_RATE_LIMIT_MAX_REQUESTS = parseInt(process.env.EVAL_RATE_LIMIT_MAX_REQUESTS || '60', 10);
// Durable per-teacher daily cap on Claude API calls (adversarial review):
// the in-memory hourly window resets on cold starts and is per-instance, so
// a DynamoDB counter enforces the real budget. One 35-student class costs
// ~4 chunked calls per run (grade or comment), so 50 calls/day ≈ 5 full
// grade+comment runs. Env-configurable for tests and per-stage tuning.
const EVAL_DAILY_LIMIT = parseInt(process.env.EVAL_DAILY_LIMIT || '50', 10);
const EVAL_GRADES = ['S', 'A', 'B', 'C'];
// --- DynamoDB Client ---
const ddbClient = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(ddbClient, {
marshallOptions: { removeUndefinedValues: true },
});
// --- S3 Client ---
const s3Client = new S3Client({});
// --- Google Auth ---
const googleClient = new OAuth2Client(GOOGLE_CLIENT_ID);
// --- Exported helpers (for testing) ---
export function getCorsHeaders(origin?: string): Record<string, string> {
const allowed = origin && CORS_ALLOWED_ORIGINS.includes(origin) ? origin : CORS_ALLOWED_ORIGINS[0] || '*';
return {
'Access-Control-Allow-Origin': allowed,
'Access-Control-Allow-Methods': 'GET,POST,PUT,PATCH,DELETE,OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type,Authorization,X-Google-Access-Token',
'Content-Type': 'application/json',
};
}
export function generateJoinCode(): string {
let code = '';
for (let i = 0; i < JOIN_CODE_LENGTH; i++) {
code += JOIN_CODE_CHARS[crypto.randomInt(JOIN_CODE_CHARS.length)];
}
return code;
}
export function generateSessionToken(): string {
return crypto.randomUUID();
}
export function validateClassName(name: unknown): string {
if (typeof name !== 'string' || name.trim().length === 0) {
throw new ValidationError('Class name is required');
}
const trimmed = name.trim();
if (trimmed.length > MAX_CLASS_NAME_LENGTH) {
throw new ValidationError(`Class name must be ${MAX_CLASS_NAME_LENGTH} characters or less`);
}
return trimmed;
}
export function validateStudentCount(count: unknown): number {
const n = typeof count === 'number' ? count : parseInt(String(count), 10);
if (isNaN(n) || n < 1 || n > MAX_STUDENT_COUNT) {
throw new ValidationError(`Student count must be between 1 and ${MAX_STUDENT_COUNT}`);
}
return n;
}
export function validateSeatNumber(seat: unknown, maxSeats: number): number {
const n = typeof seat === 'number' ? seat : parseInt(String(seat), 10);
if (isNaN(n) || n < 1 || n > maxSeats) {
throw new ValidationError(`Seat number must be between 1 and ${maxSeats}`);
}
return n;
}
export function validateNickname(nickname: unknown): string | undefined {
if (nickname === undefined || nickname === null || nickname === '') return undefined;
if (typeof nickname !== 'string') {
throw new ValidationError('Nickname must be a string');
}
const trimmed = nickname.trim();
if (trimmed.length > MAX_NICKNAME_LENGTH) {
throw new ValidationError(`Nickname must be ${MAX_NICKNAME_LENGTH} characters or less`);
}
return trimmed || undefined;
}
export function validateJoinCode(code: unknown): string {
if (typeof code !== 'string' || code.trim().length !== JOIN_CODE_LENGTH) {
throw new ValidationError(`Join code must be ${JOIN_CODE_LENGTH} characters`);
}
const lower = code.trim().toLowerCase();
if (!JOIN_CODE_REGEX.test(lower)) {
throw new ValidationError('Join code contains invalid characters');
}
return lower;
}
// --- Error classes ---
class ValidationError extends Error {
constructor(message: string) {
super(message);
this.name = 'ValidationError';
}
}
class AuthError extends Error {
constructor(message: string) {
super(message);
this.name = 'AuthError';
}
}
class NotFoundError extends Error {
constructor(message: string) {
super(message);
this.name = 'NotFoundError';
}
}
class ConflictError extends Error {
constructor(message: string) {
super(message);
this.name = 'ConflictError';
}
}
class GoogleAPIError extends Error {
statusCode: number;
constructor(statusCode: number, message: string) {
super(message);
this.name = 'GoogleAPIError';
this.statusCode = statusCode;
}
}
// Tombstone error: the member's row exists but is flagged kicked. Surface this
// to the student so the UI can show a specific "you were removed by the
// teacher" banner instead of the generic "session expired" alert.
class KickedError extends Error {
joinCode: string;
className: string;
seatNumber: number;
constructor(joinCode: string, className: string, seatNumber: number) {
super('You were removed from the classroom by the teacher');
this.name = 'KickedError';
this.joinCode = joinCode;
this.className = className;
this.seatNumber = seatNumber;
}
}
// Kick tombstone TTL: how long after a teacher kick we keep the row around so
// the kicked student's next verify-session can read the reason. Anything beyond
// this (1 hour) and we don't bother — the student will hit the regular "session
// expired" path. The tombstone is also consumed proactively when another
// student joins the seat.
const KICK_TOMBSTONE_TTL_SECONDS = parseInt(process.env.KICK_TOMBSTONE_TTL_SECONDS || '3600', 10);
// --- Google Classroom API proxy ---
async function callGoogleClassroomAPI(
accessToken: string,
path: string,
method: string = 'GET',
body?: unknown,
): Promise<unknown> {
const url = `https://classroom.googleapis.com/v1/${path}`;
const response = await fetch(url, {
method,
headers: {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
body: body ? JSON.stringify(body) : undefined,
});
if (!response.ok) {
throw new GoogleAPIError(response.status, `Google Classroom API error: ${response.status}`);
}
return response.json();
}
function extractGoogleAccessToken(headers: Record<string, string | undefined>): string {
const token = headers['x-google-access-token'];
if (!token) {
throw new AuthError('X-Google-Access-Token header is required');
}
return token;
}
// --- Microsoft JWKS ---
const MICROSOFT_JWKS_URI = 'https://login.microsoftonline.com/common/discovery/v2.0/keys';
const microsoftJWKS = createRemoteJWKSet(new URL(MICROSOFT_JWKS_URI));
// --- Auth helpers ---
/**
* Decode a JWT payload without verification to inspect the issuer claim.
*/
function decodeJwtPayload(token: string): Record<string, unknown> {
const parts = token.split('.');
if (parts.length !== 3) throw new AuthError('Malformed token');
const payload = Buffer.from(parts[1], 'base64url').toString('utf-8');
return JSON.parse(payload);
}
/**
* A verified teacher's identity. `sub` is the provider's stable user id
* (Google sub / Microsoft oid) and is the classroom owner key. `email` is the
* verified email claim (lowercased), used to match co-teacher invitations.
* `email` may be null when the provider does not supply one.
*/
export interface TeacherIdentity {
sub: string;
email: string | null;
}
export async function verifyGoogleIdToken(idToken: string): Promise<TeacherIdentity> {
try {
const ticket = await googleClient.verifyIdToken({
idToken,
audience: GOOGLE_CLIENT_ID,
});
const payload = ticket.getPayload();
if (!payload || !payload.sub) {
throw new AuthError('Invalid token payload');
}
// Only trust the email when Google marks it verified.
const email = payload.email && payload.email_verified ? normalizeEmail(payload.email) : null;
return { sub: payload.sub, email };
} catch (err) {
if (err instanceof AuthError) throw err;
throw new AuthError('Invalid or expired Google ID token');
}
}
export async function verifyMicrosoftIdToken(idToken: string): Promise<TeacherIdentity> {
if (!MICROSOFT_CLIENT_ID) {
throw new AuthError('Microsoft authentication is not configured');
}
try {
const { payload } = await jwtVerify(idToken, microsoftJWKS, {
audience: MICROSOFT_CLIENT_ID,
});
// Validate issuer: must be Microsoft login endpoint
const iss = payload.iss as string;
if (!iss || !iss.startsWith('https://login.microsoftonline.com/')) {
throw new AuthError('Invalid Microsoft token issuer');
}
// Use oid (object ID) as the unique identifier for the user
const oid = (payload.oid || payload.sub) as string;
if (!oid) {
throw new AuthError('Invalid Microsoft token payload');
}
// Microsoft puts the email in `email` or, failing that, `preferred_username`
// (which is the UPN, normally an email address).
const rawEmail = (payload.email || payload.preferred_username) as string | undefined;
const email = rawEmail && rawEmail.includes('@') ? normalizeEmail(rawEmail) : null;
return { sub: oid, email };
} catch (err) {
if (err instanceof AuthError) throw err;
throw new AuthError('Invalid or expired Microsoft ID token');
}
}
/**
* Verify a teacher ID token from either Google or Microsoft.
* Detects the provider by inspecting the JWT issuer claim.
*/
export async function verifyTeacherIdToken(idToken: string): Promise<TeacherIdentity> {
// Dev bypass: accept DEV_BYPASS_TOKEN in non-production environments only
if (DEV_BYPASS_TOKEN && idToken === DEV_BYPASS_TOKEN && STAGE !== 'prod') {
return { sub: 'dev-test-teacher', email: 'dev-test-teacher@example.com' };
}
let payload: Record<string, unknown>;
try {
payload = decodeJwtPayload(idToken);
} catch {
throw new AuthError('Invalid token format');
}
const iss = payload.iss as string;
if (iss && iss.startsWith('https://login.microsoftonline.com/')) {
return verifyMicrosoftIdToken(idToken);
}
return verifyGoogleIdToken(idToken);
}
/** Normalize an email for storage/comparison: trim + lowercase. */
export function normalizeEmail(email: string): string {
return email.trim().toLowerCase();
}
/**
* Validate a co-teacher email supplied by a teacher when inviting. Returns the
* normalized email or throws ValidationError. Intentionally lenient (a single
* `@` with non-empty local/domain parts and a dot in the domain) — exact
* deliverability is not checked; a wrong address is recoverable via removal.
*/
export function validateCoTeacherEmail(value: unknown): string {
if (typeof value !== 'string') {
throw new ValidationError('email is required');
}
const email = normalizeEmail(value);
if (email.length === 0 || email.length > 254) {
throw new ValidationError('email must be between 1 and 254 characters');
}
// Basic shape check: local@domain.tld, no spaces.
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
throw new ValidationError('email is not a valid email address');
}
return email;
}
/**
* Whether the given teacher identity may manage the classroom: either they are
* the owner (teacherSub) or their verified email is in the classroom's
* coTeacherEmails list. Used by every teacher-facing ownership check.
*/
export function canManageClassroom(
classroom: Record<string, unknown> | undefined,
identity: TeacherIdentity,
): boolean {
if (!classroom) return false;
if (classroom.teacherSub === identity.sub) return true;
if (!identity.email) return false;
const coTeacherEmails = classroom.coTeacherEmails;
return Array.isArray(coTeacherEmails) && coTeacherEmails.includes(identity.email);
}
/**
* Class-aware manage check: classroom-level owner/co-teacher first (cheap,
* no I/O), then the owning class (group) — its owner and class-level
* co-teachers may manage every assignment inside it. Classroom-level
* coTeacherEmails stay honored for pre-v2 records.
*/
async function canManageViaGroup(
item: Record<string, unknown>,
identity: TeacherIdentity,
): Promise<boolean> {
if (canManageClassroom(item, identity)) {
return true;
}
if (typeof item.groupId === 'string' && item.groupId) {
const groupResult = await docClient.send(new GetCommand({
TableName: GROUPS_TABLE,
Key: { groupId: item.groupId },
}));
const group = groupResult.Item;
if (group) {
if (group.teacherSub === identity.sub) {
return true;
}
if (identity.email && Array.isArray(group.coTeacherEmails)) {
return (group.coTeacherEmails as string[]).includes(normalizeEmail(identity.email));
}
}
}
return false;
}
function extractBearerToken(authHeader?: string): string {
if (!authHeader || !authHeader.startsWith('Bearer ')) {
throw new AuthError('Authorization header with Bearer token is required');
}
return authHeader.slice(7);
}
// --- Route handlers ---
async function handleCreateClassroom(identity: TeacherIdentity, body: Record<string, unknown>): Promise<APIGatewayProxyStructuredResultV2> {
const className = validateClassName(body.className);
let assignmentName = validateClassName(body.assignmentName); // reuse same validator (1-50 chars)
const googleClassroomCourseId = typeof body.googleClassroomCourseId === 'string' ? body.googleClassroomCourseId.trim() : undefined;
// Optional group (クラス) assignment — must be a group this teacher owns.
let groupId: string | undefined;
let group: Record<string, unknown> | undefined;
if (typeof body.groupId === 'string' && body.groupId) {
group = await getOwnedGroup(identity, body.groupId);
groupId = body.groupId;
}
// v2: the class's studentCount is the source of truth — an assignment
// created inside a class inherits it when the request omits the count.
const studentCount = body.studentCount === undefined && group && typeof group.studentCount === 'number'
? group.studentCount
: validateStudentCount(body.studentCount);
const topic = body.topic !== undefined && body.topic !== null && body.topic !== ''
? validateTopicName(body.topic)
: undefined;
if (topic && groupId) {
await ensureGroupTopic(groupId, group, topic);
}
const sortDate = body.sortDate !== undefined ? validateSortDate(body.sortDate) : undefined;
// Auto-number duplicate assignment names within the same class
const existingClassrooms = await docClient.send(new QueryCommand({
TableName: CLASSROOMS_TABLE,
IndexName: 'teacherSub-index',
KeyConditionExpression: 'teacherSub = :ts',
ExpressionAttributeValues: { ':ts': identity.sub },
}));
if (existingClassrooms.Items) {
const sameClassAssignments = existingClassrooms.Items
.filter(item => item.className === className && item.status === 'active')
.map(item => item.assignmentName as string);
if (sameClassAssignments.includes(assignmentName)) {
let suffix = 2;
while (sameClassAssignments.includes(`${assignmentName} (${suffix})`)) {
suffix++;
}
assignmentName = `${assignmentName} (${suffix})`;
}
}
// Generate unique join code (retry up to 5 times)
let joinCode = '';
for (let attempt = 0; attempt < 5; attempt++) {
const candidate = generateJoinCode();
const existing = await docClient.send(new QueryCommand({
TableName: CLASSROOMS_TABLE,
IndexName: 'joinCode-index',
KeyConditionExpression: 'joinCode = :jc',
ExpressionAttributeValues: { ':jc': candidate },
Limit: 1,
}));
if (!existing.Items || existing.Items.length === 0) {
joinCode = candidate;
break;
}
}
if (!joinCode) {
return { statusCode: 500, body: JSON.stringify({ error: 'Failed to generate unique join code' }) };
}
const now = new Date().toISOString();
const classroomId = crypto.randomUUID();
const ttl = Math.floor(Date.now() / 1000) + CLASSROOM_TTL_SECONDS;
const expiresAt = new Date(ttl * 1000).toISOString();
await docClient.send(new PutCommand({
TableName: CLASSROOMS_TABLE,
Item: {
classroomId,
teacherSub: identity.sub,
className,
assignmentName,
joinCode,
studentCount,
googleClassroomCourseId: googleClassroomCourseId || undefined,
groupId,
topic,
sortDate: sortDate || now,
status: 'active',
createdAt: now,
updatedAt: now,
ttl,
},
}));
return {
statusCode: 201,
body: JSON.stringify({ classroomId, className, assignmentName, joinCode, studentCount, googleClassroomCourseId: googleClassroomCourseId || null, groupId: groupId || null, topic: topic || null, sortDate: sortDate || now, status: 'active', createdAt: now, expiresAt }),
};
}
/** Read the coTeacherEmails list from a classroom item, defaulting to []. */
function readCoTeacherEmails(item: Record<string, unknown>): string[] {
return Array.isArray(item.coTeacherEmails) ? (item.coTeacherEmails as string[]) : [];
}
/** Fetch the owning class (group) of an assignment, or undefined (pre-v2). */
async function getOwningGroup(
classroom: Record<string, unknown>,
): Promise<Record<string, unknown> | undefined> {
if (typeof classroom.groupId !== 'string' || !classroom.groupId) {
return undefined;
}
const result = await docClient.send(new GetCommand({
TableName: GROUPS_TABLE,
Key: { groupId: classroom.groupId },
}));
return result.Item;
}
/**
* v2 seat count: the class's studentCount is authoritative, but only ever
* grows the grid — max() with the assignment's own snapshot so an older
* lesson never loses occupied seats when the class count is set smaller.
*/
function seatCountFor(
classroom: Record<string, unknown>,
group: Record<string, unknown> | undefined,
): number {
const own = typeof classroom.studentCount === 'number' ? classroom.studentCount : 0;
const groupCount = group && typeof group.studentCount === 'number' ? group.studentCount : 0;
return Math.max(own, groupCount);
}
/**
* Shape a classroom item for the teacher-facing list/detail responses, adding
* the co-teacher list and the requesting teacher's role (owner vs co-teacher).
*/
function mapClassroomSummary(item: Record<string, unknown>, identity: TeacherIdentity) {
return {
classroomId: item.classroomId,
className: item.className,
assignmentName: item.assignmentName || null,
joinCode: item.joinCode,
studentCount: item.studentCount,
googleClassroomCourseId: item.googleClassroomCourseId || null,
googleClassroomAlternateLink: item.googleClassroomAlternateLink || null,
createdAt: item.createdAt,
expiresAt: item.ttl ? new Date((item.ttl as number) * 1000).toISOString() : null,
coTeacherEmails: readCoTeacherEmails(item),
groupId: item.groupId || null,
topic: item.topic || null,
sortDate: item.sortDate || item.createdAt || null,
hasAssignment: hasAssignmentContent(item),
status: item.status,
role: item.teacherSub === identity.sub ? 'owner' : 'co-teacher',
};
}
async function handleListClassrooms(identity: TeacherIdentity, includeArchived = false): Promise<APIGatewayProxyStructuredResultV2> {
// Classes the teacher owns — fast GSI query on teacherSub.
const owned = await docClient.send(new QueryCommand({
TableName: CLASSROOMS_TABLE,
IndexName: 'teacherSub-index',
KeyConditionExpression: 'teacherSub = :ts',
ExpressionAttributeValues: { ':ts': identity.sub },
}));
// Classes the teacher co-manages — matched by verified email. DynamoDB cannot
// index a list attribute with a GSI, so we Scan + filter on coTeacherEmails.
// The classrooms table is small (single org, 30-day TTL) so this is fine;
// revisit with a reverse-index table (email -> classroomId) if it grows large.
let coManaged: Record<string, unknown>[] = [];
if (identity.email) {
const scan = await docClient.send(new ScanCommand({
TableName: CLASSROOMS_TABLE,
FilterExpression: 'contains(coTeacherEmails, :email)',
ExpressionAttributeValues: { ':email': identity.email },
}));
coManaged = scan.Items || [];
}
// Merge by classroomId (owned wins). Archived classes are excluded unless
// the caller opts in with ?includeArchived=1 (the archive-list / restore UI,
// issue #1050) — the default stays active-only so already-deployed frontends
// never see archived items reappear.
const byId = new Map<string, Record<string, unknown>>();
for (const item of [...(owned.Items || []), ...coManaged]) {
const id = item.classroomId as string;
const visible = item.status === 'active' || (includeArchived && item.status === 'archived');
if (visible && !byId.has(id)) {
byId.set(id, item);
}
}
const classrooms = Array.from(byId.values()).map(item => mapClassroomSummary(item, identity));
return { statusCode: 200, body: JSON.stringify({ classrooms }) };
}
async function handleGetClassroom(identity: TeacherIdentity, classroomId: string): Promise<APIGatewayProxyStructuredResultV2> {
const result = await docClient.send(new GetCommand({
TableName: CLASSROOMS_TABLE,
Key: { classroomId },
}));
if (!result.Item || result.Item.status !== 'active') {
throw new NotFoundError('Classroom not found');
}
if (!(await canManageViaGroup(result.Item, identity))) {
throw new AuthError('Not authorized to view this classroom');
}
return {
statusCode: 200,
body: JSON.stringify({
classroomId: result.Item.classroomId,
className: result.Item.className,
assignmentName: result.Item.assignmentName || null,
joinCode: result.Item.joinCode,
studentCount: result.Item.studentCount,
googleClassroomCourseId: result.Item.googleClassroomCourseId || null,
googleClassroomAlternateLink: result.Item.googleClassroomAlternateLink || null,
status: result.Item.status,
createdAt: result.Item.createdAt,
expiresAt: result.Item.ttl ? new Date((result.Item.ttl as number) * 1000).toISOString() : null,
coTeacherEmails: readCoTeacherEmails(result.Item),
groupId: result.Item.groupId || null,
topic: result.Item.topic || null,
sortDate: result.Item.sortDate || result.Item.createdAt || null,
hasAssignment: hasAssignmentContent(result.Item),
role: result.Item.teacherSub === identity.sub ? 'owner' : 'co-teacher',
}),
};
}
// --- Co-teacher management ---
// A classroom is owned by one teacher (teacherSub) and may be co-managed by
// additional teachers identified by email (coTeacherEmails). Co-teachers are
// fully equal to the owner for every operation. The owner is NOT stored in
// coTeacherEmails, so these endpoints can never add/remove the owner — the
// creator always retains management (no "zero admins" state).
const MAX_CO_TEACHERS = 10;
async function handleListCoTeachers(identity: TeacherIdentity, classroomId: string): Promise<APIGatewayProxyStructuredResultV2> {
const result = await docClient.send(new GetCommand({
TableName: CLASSROOMS_TABLE,
Key: { classroomId },
}));
if (!result.Item || result.Item.status !== 'active') {
throw new NotFoundError('Classroom not found');
}
if (!(await canManageViaGroup(result.Item, identity))) {
throw new AuthError('Not authorized to view co-teachers for this classroom');
}
return {
statusCode: 200,
body: JSON.stringify({
ownerSub: result.Item.teacherSub,
coTeacherEmails: readCoTeacherEmails(result.Item),
}),
};
}
async function handleAddCoTeacher(identity: TeacherIdentity, classroomId: string, body: Record<string, unknown>): Promise<APIGatewayProxyStructuredResultV2> {
const email = validateCoTeacherEmail(body.email);
const result = await docClient.send(new GetCommand({
TableName: CLASSROOMS_TABLE,
Key: { classroomId },
}));
if (!result.Item || result.Item.status !== 'active') {
throw new NotFoundError('Classroom not found');
}
if (!(await canManageViaGroup(result.Item, identity))) {
throw new AuthError('Not authorized to manage co-teachers for this classroom');
}
const existing = readCoTeacherEmails(result.Item);
if (existing.includes(email)) {
// Idempotent: already invited.
return { statusCode: 200, body: JSON.stringify({ coTeacherEmails: existing }) };
}
if (existing.length >= MAX_CO_TEACHERS) {
throw new ValidationError(`A classroom may have at most ${MAX_CO_TEACHERS} co-teachers`);
}
const updated = [...existing, email];
await docClient.send(new UpdateCommand({
TableName: CLASSROOMS_TABLE,
Key: { classroomId },
UpdateExpression: 'SET coTeacherEmails = :list, updatedAt = :now',
ExpressionAttributeValues: { ':list': updated, ':now': new Date().toISOString() },
}));
return { statusCode: 200, body: JSON.stringify({ coTeacherEmails: updated }) };
}
async function handleRemoveCoTeacher(identity: TeacherIdentity, classroomId: string, emailParam: string): Promise<APIGatewayProxyStructuredResultV2> {
const email = normalizeEmail(decodeURIComponent(emailParam));
const result = await docClient.send(new GetCommand({
TableName: CLASSROOMS_TABLE,
Key: { classroomId },
}));
if (!result.Item || result.Item.status !== 'active') {
throw new NotFoundError('Classroom not found');
}
if (!(await canManageViaGroup(result.Item, identity))) {
throw new AuthError('Not authorized to manage co-teachers for this classroom');
}
const existing = readCoTeacherEmails(result.Item);
const updated = existing.filter(e => e !== email);
if (updated.length !== existing.length) {
await docClient.send(new UpdateCommand({
TableName: CLASSROOMS_TABLE,
Key: { classroomId },
UpdateExpression: 'SET coTeacherEmails = :list, updatedAt = :now',
ExpressionAttributeValues: { ':list': updated, ':now': new Date().toISOString() },
}));
}
return { statusCode: 200, body: JSON.stringify({ coTeacherEmails: updated }) };
}
async function handleUpdateClassroom(identity: TeacherIdentity, classroomId: string, body: Record<string, unknown>): Promise<APIGatewayProxyStructuredResultV2> {
// Verify ownership
const classroom = await docClient.send(new GetCommand({
TableName: CLASSROOMS_TABLE,
Key: { classroomId },
}));
if (!classroom.Item || !(await canManageViaGroup(classroom.Item, identity))) {
throw new AuthError('Not authorized to update this classroom');
}
const updates: Record<string, unknown> = { updatedAt: new Date().toISOString() };
if (body.className !== undefined) {
updates.className = validateClassName(body.className);
}
if (body.assignmentName !== undefined) {
updates.assignmentName = validateClassName(body.assignmentName);
}
if (body.studentCount !== undefined) {
updates.studentCount = validateStudentCount(body.studentCount);
}
if (body.status !== undefined) {
if (body.status !== 'active' && body.status !== 'archived') {
throw new ValidationError('Status must be "active" or "archived"');
}
updates.status = body.status;
}
if (body.regenerateJoinCode === true) {
updates.joinCode = generateJoinCode();
}
// Assign to / remove from a group (クラス). `groupId: null` clears the
// assignment; a string must be a group this teacher owns.
if (body.groupId !== undefined) {
if (body.groupId === null || body.groupId === '') {
updates.groupId = null;
} else if (typeof body.groupId === 'string') {
await getOwnedGroup(identity, body.groupId);
updates.groupId = body.groupId;
} else {
throw new ValidationError('groupId must be a string or null');
}
}
if (body.topic !== undefined) {
if (body.topic === null || body.topic === '') {
updates.topic = null;
} else {
updates.topic = validateTopicName(body.topic);
// A new topic used on an assignment becomes part of the class's list.
const effectiveGroupId = (updates.groupId !== undefined ? updates.groupId : classroom.Item.groupId) as
string | null | undefined;
if (effectiveGroupId) {
await ensureGroupTopic(effectiveGroupId, undefined, updates.topic as string);
}
}
}
if (body.sortDate !== undefined) {
updates.sortDate = validateSortDate(body.sortDate);
}
const expressionParts: string[] = [];
const expressionValues: Record<string, unknown> = {};
const expressionNames: Record<string, string> = {};
let i = 0;
for (const [key, value] of Object.entries(updates)) {
const attrName = `#attr${i}`;
const attrValue = `:val${i}`;
expressionNames[attrName] = key;
expressionValues[attrValue] = value;
expressionParts.push(`${attrName} = ${attrValue}`);
i++;
}
const result = await docClient.send(new UpdateCommand({
TableName: CLASSROOMS_TABLE,
Key: { classroomId },
UpdateExpression: `SET ${expressionParts.join(', ')}`,
ExpressionAttributeNames: expressionNames,
ExpressionAttributeValues: expressionValues,
ReturnValues: 'ALL_NEW',
}));
return {
statusCode: 200,
body: JSON.stringify({
classroomId: result.Attributes?.classroomId,
className: result.Attributes?.className,
assignmentName: result.Attributes?.assignmentName,
joinCode: result.Attributes?.joinCode,
studentCount: result.Attributes?.studentCount,
status: result.Attributes?.status,
}),
};
}
// Simple in-memory rate limiter for join endpoint (per Lambda instance)
const joinAttempts = new Map<string, { count: number; windowStart: number }>();
function checkJoinRateLimit(sourceIp: string): void {
const now = Math.floor(Date.now() / 1000);
const entry = joinAttempts.get(sourceIp);
if (entry && (now - entry.windowStart) < JOIN_RATE_LIMIT_WINDOW_SECONDS) {
if (entry.count >= JOIN_RATE_LIMIT_MAX_ATTEMPTS) {
throw new ValidationError('Too many join attempts. Please try again later.');
}
entry.count++;
} else {
joinAttempts.set(sourceIp, { count: 1, windowStart: now });
}
// Clean up old entries periodically
if (joinAttempts.size > 1000) {
for (const [ip, e] of joinAttempts) {
if ((now - e.windowStart) >= JOIN_RATE_LIMIT_WINDOW_SECONDS) {
joinAttempts.delete(ip);
}
}
}
}
async function handleJoinClassroom(sourceIp: string, body: Record<string, unknown>): Promise<APIGatewayProxyStructuredResultV2> {
checkJoinRateLimit(sourceIp);
const joinCode = validateJoinCode(body.joinCode);
// Look up classroom by join code
const classroomResult = await docClient.send(new QueryCommand({
TableName: CLASSROOMS_TABLE,
IndexName: 'joinCode-index',
KeyConditionExpression: 'joinCode = :jc',
ExpressionAttributeValues: { ':jc': joinCode },
Limit: 1,
}));
if (!classroomResult.Items || classroomResult.Items.length === 0) {
throw new NotFoundError('Invalid join code');
}
const classroom = classroomResult.Items[0];
if (classroom.status !== 'active') {
throw new NotFoundError('This classroom is no longer active');
}
const owningGroup = await getOwningGroup(classroom);
const seatNumber = validateSeatNumber(body.seatNumber, seatCountFor(classroom, owningGroup));
const nickname = validateNickname(body.nickname);
const memberId = `seat-${String(seatNumber).padStart(2, '0')}`;
const sessionToken = generateSessionToken();
const now = new Date().toISOString();
// Atomic put with condition to prevent race condition on seat assignment.
// We allow overwriting a row that the teacher previously kicked (kicked=true)
// so the seat opens up immediately after a kick — the tombstone is consumed
// here. The new row deliberately omits the kick attributes; verifying the
// old session token afterwards will fall through to the standard 401 path
// because the row no longer matches that sessionToken in the GSI.
try {
await docClient.send(new PutCommand({
TableName: MEMBERSHIPS_TABLE,
Item: {
classroomId: classroom.classroomId,
memberId,
displayName: nickname,
role: 'student',
sessionToken,
joinedAt: now,
lastActiveAt: now,
ttl: Math.floor(Date.now() / 1000) + SESSION_TTL_SECONDS,
},
ConditionExpression: 'attribute_not_exists(memberId) OR kicked = :kicked',
ExpressionAttributeValues: { ':kicked': true },
}));
} catch (err: unknown) {
if (err && typeof err === 'object' && 'name' in err && err.name === 'ConditionalCheckFailedException') {
throw new ConflictError(`Seat ${seatNumber} is already taken`);