curriculum-api 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1341 @@
1
+ import {
2
+ adminLoginAttempts,
3
+ createDb,
4
+ migrate,
5
+ personalInfo,
6
+ profile,
7
+ publicUsage,
8
+ recruiterChatMessages,
9
+ recruiterChats,
10
+ seed,
11
+ settings,
12
+ tailoredResumes
13
+ } from "./chunk-RL62MWPL.js";
14
+ import {
15
+ CaptchaFailedError,
16
+ ChatExpiredError,
17
+ ChatRevokedError,
18
+ ConfigError,
19
+ DecryptionError,
20
+ DomainError,
21
+ ForbiddenError,
22
+ LimitReachedError,
23
+ LlmUnavailableError,
24
+ NotFoundError,
25
+ PAGE_SIZES,
26
+ PAGE_SIZE_KEY,
27
+ PersonalInfoService,
28
+ PiiLeakError,
29
+ SESSION_COOKIE,
30
+ SETTINGS_KEYS,
31
+ UnauthorizedError,
32
+ ValidationError,
33
+ clientIp,
34
+ findPii,
35
+ hashIp,
36
+ limitKey,
37
+ modelKey,
38
+ redactPii,
39
+ renderMarkdown,
40
+ setSessionCookie,
41
+ signSession,
42
+ verifySession
43
+ } from "./chunk-N6XNQ5R5.js";
44
+
45
+ // src/app.ts
46
+ import { OpenAPIHono as OpenAPIHono4 } from "@hono/zod-openapi";
47
+ import { Hono } from "hono";
48
+
49
+ // src/config.ts
50
+ import { z } from "zod";
51
+ var DEFAULT_LIMITS = {
52
+ publicQuestionsPerIpPerDay: 5,
53
+ recruiterQuestionsDefault: 10,
54
+ publicMaxOutputTokens: 500,
55
+ recruiterMaxOutputTokens: 1200,
56
+ maxQuestionChars: 1e3,
57
+ maxHistoryMessages: 10,
58
+ sessionTtlMinutes: 120
59
+ };
60
+ var required = (name) => z.string({ error: `${name} is required` }).min(1, `${name} is required`);
61
+ var limit = z.number().int().positive().optional();
62
+ var schema = z.object({
63
+ databaseUrl: required("databaseUrl"),
64
+ openrouterApiKey: required("openrouterApiKey"),
65
+ sessionSecret: required("sessionSecret").refine(
66
+ (v) => new TextEncoder().encode(v).length >= 32,
67
+ "sessionSecret must be at least 32 bytes"
68
+ ),
69
+ turnstileSecret: required("turnstileSecret"),
70
+ adminPasswordHash: required("adminPasswordHash"),
71
+ ipHashSalt: required("ipHashSalt"),
72
+ piiEncryptionKey: required("piiEncryptionKey").refine((v) => {
73
+ try {
74
+ return Buffer.from(v, "base64").length === 32 && Buffer.from(v, "base64").toString("base64") === v;
75
+ } catch {
76
+ return false;
77
+ }
78
+ }, "piiEncryptionKey must be base64 of exactly 32 bytes"),
79
+ basePath: z.string().optional(),
80
+ secureCookies: z.boolean().optional(),
81
+ models: z.object({
82
+ public: z.string().optional(),
83
+ tailor: z.string().optional(),
84
+ recruiter: z.string().optional()
85
+ }).optional(),
86
+ limits: z.object({
87
+ publicQuestionsPerIpPerDay: limit,
88
+ recruiterQuestionsDefault: limit,
89
+ publicMaxOutputTokens: limit,
90
+ recruiterMaxOutputTokens: limit,
91
+ maxQuestionChars: limit,
92
+ maxHistoryMessages: limit,
93
+ sessionTtlMinutes: limit
94
+ }).optional()
95
+ });
96
+ function resolveConfig(input) {
97
+ const parsed = schema.safeParse(input ?? {});
98
+ if (!parsed.success) {
99
+ const fields = [...new Set(parsed.error.issues.map((i) => i.path.join(".") || "config"))];
100
+ throw new ConfigError(fields);
101
+ }
102
+ const c = parsed.data;
103
+ const limits = { ...DEFAULT_LIMITS };
104
+ for (const [name, value] of Object.entries(c.limits ?? {})) {
105
+ if (value !== void 0) limits[name] = value;
106
+ }
107
+ return {
108
+ databaseUrl: c.databaseUrl,
109
+ openrouterApiKey: c.openrouterApiKey,
110
+ sessionSecret: c.sessionSecret,
111
+ turnstileSecret: c.turnstileSecret,
112
+ adminPasswordHash: c.adminPasswordHash,
113
+ ipHashSalt: c.ipHashSalt,
114
+ piiEncryptionKey: c.piiEncryptionKey,
115
+ basePath: c.basePath ?? "",
116
+ secureCookies: c.secureCookies ?? true,
117
+ models: { ...c.models },
118
+ limits
119
+ };
120
+ }
121
+
122
+ // src/llm/openrouter.ts
123
+ import { createOpenRouter } from "@openrouter/ai-sdk-provider";
124
+ function createProvider(apiKey) {
125
+ const provider = createOpenRouter({ apiKey });
126
+ return (modelId) => provider(modelId);
127
+ }
128
+
129
+ // src/repositories/admin-login-attempt.repository.ts
130
+ import { and, eq, sql } from "drizzle-orm";
131
+ var AdminLoginAttemptRepository = class {
132
+ constructor(db) {
133
+ this.db = db;
134
+ }
135
+ db;
136
+ async failures(ipHash, windowStart) {
137
+ const [row] = await this.db.select({ count: adminLoginAttempts.count }).from(adminLoginAttempts).where(
138
+ and(eq(adminLoginAttempts.ipHash, ipHash), eq(adminLoginAttempts.windowStart, windowStart))
139
+ );
140
+ return row?.count ?? 0;
141
+ }
142
+ async recordFailure(ipHash, windowStart) {
143
+ const [row] = await this.db.insert(adminLoginAttempts).values({ ipHash, windowStart, count: 1 }).onConflictDoUpdate({
144
+ target: [adminLoginAttempts.ipHash, adminLoginAttempts.windowStart],
145
+ set: { count: sql`${adminLoginAttempts.count} + 1` }
146
+ }).returning({ count: adminLoginAttempts.count });
147
+ return row?.count ?? 0;
148
+ }
149
+ async counts() {
150
+ const result = await this.db.execute(sql`
151
+ select
152
+ (select count(*) from curriculum_api.recruiter_chats
153
+ where status = 'active' and (expires_at is null or expires_at > now()))::int as chats,
154
+ (select count(*) from curriculum_api.tailored_resumes)::int as resumes,
155
+ (select coalesce(sum(used), 0) from curriculum_api.public_usage
156
+ where day = current_date)::int as usage
157
+ `);
158
+ const row = result.rows[0];
159
+ return {
160
+ activeChats: Number(row?.chats ?? 0),
161
+ resumes: Number(row?.resumes ?? 0),
162
+ publicQuestionsToday: Number(row?.usage ?? 0)
163
+ };
164
+ }
165
+ };
166
+
167
+ // src/repositories/personal-info.repository.ts
168
+ import { asc, eq as eq2, sql as sql2 } from "drizzle-orm";
169
+ var PersonalInfoRepository = class {
170
+ constructor(db) {
171
+ this.db = db;
172
+ }
173
+ db;
174
+ list() {
175
+ return this.db.select().from(personalInfo).orderBy(asc(personalInfo.sortOrder), asc(personalInfo.key));
176
+ }
177
+ async find(key) {
178
+ const [row] = await this.db.select().from(personalInfo).where(eq2(personalInfo.key, key));
179
+ return row ?? null;
180
+ }
181
+ async insert(row) {
182
+ const [created] = await this.db.insert(personalInfo).values(row).returning();
183
+ return created;
184
+ }
185
+ async update(key, patch) {
186
+ const [row] = await this.db.update(personalInfo).set({ ...patch, updatedAt: sql2`now()` }).where(eq2(personalInfo.key, key)).returning();
187
+ return row ?? null;
188
+ }
189
+ async delete(key) {
190
+ const rows = await this.db.delete(personalInfo).where(eq2(personalInfo.key, key)).returning({ key: personalInfo.key });
191
+ return rows.length > 0;
192
+ }
193
+ };
194
+
195
+ // src/repositories/profile.repository.ts
196
+ import { eq as eq3, sql as sql3 } from "drizzle-orm";
197
+ var ProfileRepository = class {
198
+ constructor(db) {
199
+ this.db = db;
200
+ }
201
+ db;
202
+ async find() {
203
+ const [row] = await this.db.select().from(profile).where(eq3(profile.id, 1));
204
+ return row ?? null;
205
+ }
206
+ async upsert(input) {
207
+ const [row] = await this.db.insert(profile).values({ ...input, id: 1 }).onConflictDoUpdate({ target: profile.id, set: { ...input, updatedAt: sql3`now()` } }).returning();
208
+ return row;
209
+ }
210
+ };
211
+
212
+ // src/repositories/public-usage.repository.ts
213
+ import { and as and2, eq as eq4, lt, sql as sql4 } from "drizzle-orm";
214
+ var PublicUsageRepository = class {
215
+ constructor(db) {
216
+ this.db = db;
217
+ }
218
+ db;
219
+ async acquire(ipHash, limit2) {
220
+ const [row] = await this.db.insert(publicUsage).values({ ipHash, day: sql4`current_date`, used: 1 }).onConflictDoUpdate({
221
+ target: [publicUsage.ipHash, publicUsage.day],
222
+ set: { used: sql4`${publicUsage.used} + 1` },
223
+ setWhere: lt(publicUsage.used, limit2)
224
+ }).returning({ used: publicUsage.used, day: publicUsage.day });
225
+ return row ?? null;
226
+ }
227
+ async release(ipHash, day) {
228
+ await this.db.update(publicUsage).set({ used: sql4`greatest(${publicUsage.used} - 1, 0)` }).where(and2(eq4(publicUsage.ipHash, ipHash), eq4(publicUsage.day, day)));
229
+ }
230
+ };
231
+
232
+ // src/repositories/recruiter-chat.repository.ts
233
+ import { and as and3, asc as asc2, desc, eq as eq5, getTableColumns, gt, isNull, lt as lt2, or, sql as sql5 } from "drizzle-orm";
234
+ var expired = sql5`(${recruiterChats.expiresAt} is not null and ${recruiterChats.expiresAt} <= now())`;
235
+ var columns = { ...getTableColumns(recruiterChats), expired };
236
+ var RecruiterChatRepository = class {
237
+ constructor(db) {
238
+ this.db = db;
239
+ }
240
+ db;
241
+ list() {
242
+ return this.db.select(columns).from(recruiterChats).orderBy(desc(recruiterChats.createdAt), desc(recruiterChats.id));
243
+ }
244
+ async findByToken(token) {
245
+ const [row] = await this.db.select(columns).from(recruiterChats).where(eq5(recruiterChats.token, token));
246
+ return row ?? null;
247
+ }
248
+ async findById(id) {
249
+ const [row] = await this.db.select(columns).from(recruiterChats).where(eq5(recruiterChats.id, id));
250
+ return row ?? null;
251
+ }
252
+ async insert(input) {
253
+ const [row] = await this.db.insert(recruiterChats).values(input).returning(columns);
254
+ return row;
255
+ }
256
+ async revoke(id) {
257
+ const [row] = await this.db.update(recruiterChats).set({ status: "revoked" }).where(eq5(recruiterChats.id, id)).returning(columns);
258
+ return row ?? null;
259
+ }
260
+ async reset(id) {
261
+ const [row] = await this.db.update(recruiterChats).set({ used: 0 }).where(eq5(recruiterChats.id, id)).returning(columns);
262
+ return row ?? null;
263
+ }
264
+ async delete(id) {
265
+ const rows = await this.db.delete(recruiterChats).where(eq5(recruiterChats.id, id)).returning({ id: recruiterChats.id });
266
+ return rows.length > 0;
267
+ }
268
+ async acquire(id) {
269
+ const [row] = await this.db.update(recruiterChats).set({ used: sql5`${recruiterChats.used} + 1` }).where(
270
+ and3(
271
+ eq5(recruiterChats.id, id),
272
+ eq5(recruiterChats.status, "active"),
273
+ lt2(recruiterChats.used, recruiterChats.maxQuestions),
274
+ or(isNull(recruiterChats.expiresAt), gt(recruiterChats.expiresAt, sql5`now()`))
275
+ )
276
+ ).returning(columns);
277
+ return row ?? null;
278
+ }
279
+ async release(id) {
280
+ await this.db.update(recruiterChats).set({ used: sql5`greatest(${recruiterChats.used} - 1, 0)` }).where(eq5(recruiterChats.id, id));
281
+ }
282
+ async touch(id) {
283
+ await this.db.update(recruiterChats).set({ lastUsedAt: sql5`now()` }).where(eq5(recruiterChats.id, id));
284
+ }
285
+ async resumeContent(id) {
286
+ if (id === null) return null;
287
+ const [row] = await this.db.select({ content: tailoredResumes.content }).from(tailoredResumes).where(eq5(tailoredResumes.id, id));
288
+ return row?.content ?? null;
289
+ }
290
+ async resumeExists(id) {
291
+ const rows = await this.db.select({ id: tailoredResumes.id }).from(tailoredResumes).where(eq5(tailoredResumes.id, id));
292
+ return rows.length > 0;
293
+ }
294
+ resumeOptions() {
295
+ return this.db.select({ id: tailoredResumes.id, title: tailoredResumes.title }).from(tailoredResumes).orderBy(desc(tailoredResumes.createdAt), desc(tailoredResumes.id));
296
+ }
297
+ async addMessages(chatId, messages) {
298
+ if (messages.length === 0) return;
299
+ await this.db.insert(recruiterChatMessages).values(messages.map((m) => ({ chatId, ...m })));
300
+ }
301
+ async messages(chatId) {
302
+ const rows = await this.db.select({
303
+ id: recruiterChatMessages.id,
304
+ role: recruiterChatMessages.role,
305
+ content: recruiterChatMessages.content,
306
+ createdAt: recruiterChatMessages.createdAt
307
+ }).from(recruiterChatMessages).where(eq5(recruiterChatMessages.chatId, chatId)).orderBy(asc2(recruiterChatMessages.seq));
308
+ return rows;
309
+ }
310
+ };
311
+
312
+ // src/repositories/resume.repository.ts
313
+ import { desc as desc2, eq as eq6, sql as sql6 } from "drizzle-orm";
314
+ var ResumeRepository = class {
315
+ constructor(db) {
316
+ this.db = db;
317
+ }
318
+ db;
319
+ list() {
320
+ return this.db.select().from(tailoredResumes).orderBy(desc2(tailoredResumes.createdAt), desc2(tailoredResumes.id));
321
+ }
322
+ async find(id) {
323
+ const [row] = await this.db.select().from(tailoredResumes).where(eq6(tailoredResumes.id, id));
324
+ return row ?? null;
325
+ }
326
+ async insert(row) {
327
+ const [created] = await this.db.insert(tailoredResumes).values(row).returning();
328
+ return created;
329
+ }
330
+ async update(id, patch) {
331
+ const [row] = await this.db.update(tailoredResumes).set({ ...patch, updatedAt: sql6`now()` }).where(eq6(tailoredResumes.id, id)).returning();
332
+ return row ?? null;
333
+ }
334
+ async delete(id) {
335
+ const rows = await this.db.delete(tailoredResumes).where(eq6(tailoredResumes.id, id)).returning({ id: tailoredResumes.id });
336
+ return rows.length > 0;
337
+ }
338
+ };
339
+
340
+ // src/repositories/settings.repository.ts
341
+ import { eq as eq7 } from "drizzle-orm";
342
+ var SettingsRepository = class {
343
+ constructor(db) {
344
+ this.db = db;
345
+ }
346
+ db;
347
+ async get(key) {
348
+ const [row] = await this.db.select().from(settings).where(eq7(settings.key, key));
349
+ return row?.value ?? null;
350
+ }
351
+ async all() {
352
+ const rows = await this.db.select().from(settings);
353
+ return Object.fromEntries(rows.map((r) => [r.key, r.value]));
354
+ }
355
+ async set(key, value) {
356
+ await this.db.insert(settings).values({ key, value }).onConflictDoUpdate({ target: settings.key, set: { value } });
357
+ }
358
+ async delete(key) {
359
+ await this.db.delete(settings).where(eq7(settings.key, key));
360
+ }
361
+ };
362
+
363
+ // src/security/admin-auth.ts
364
+ import bcrypt from "bcryptjs";
365
+ var LOGIN_WINDOW_MS = 15 * 60 * 1e3;
366
+ var MAX_FAILED_LOGINS = 5;
367
+ var FAILED_LOGIN_DELAY_MS = 500;
368
+ var AdminAuthService = class {
369
+ constructor(attempts, config, opts = {}) {
370
+ this.attempts = attempts;
371
+ this.config = config;
372
+ this.sleep = opts.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
373
+ this.now = opts.now ?? Date.now;
374
+ }
375
+ attempts;
376
+ config;
377
+ sleep;
378
+ now;
379
+ async login(password, ip) {
380
+ const ipHash = await hashIp(ip ?? "unknown", this.config.ipHashSalt);
381
+ const windowStart = new Date(Math.floor(this.now() / LOGIN_WINDOW_MS) * LOGIN_WINDOW_MS);
382
+ if (await this.attempts.failures(ipHash, windowStart) >= MAX_FAILED_LOGINS) {
383
+ return "throttled";
384
+ }
385
+ if (await this.matches(password)) return "ok";
386
+ await this.sleep(FAILED_LOGIN_DELAY_MS);
387
+ await this.attempts.recordFailure(ipHash, windowStart);
388
+ return "invalid";
389
+ }
390
+ dashboardCounts() {
391
+ return this.attempts.counts();
392
+ }
393
+ async matches(password) {
394
+ if (!password) return false;
395
+ try {
396
+ return await bcrypt.compare(password, this.config.adminPasswordHash);
397
+ } catch {
398
+ return false;
399
+ }
400
+ }
401
+ };
402
+
403
+ // src/services/llm.service.ts
404
+ import { generateText, streamText } from "ai";
405
+
406
+ // src/llm/first-chunk.ts
407
+ async function firstChunk(parts, onDone) {
408
+ const iterator = parts[Symbol.asyncIterator]();
409
+ let first;
410
+ while (first === void 0) {
411
+ let step;
412
+ try {
413
+ step = await iterator.next();
414
+ } catch {
415
+ throw new LlmUnavailableError();
416
+ }
417
+ if (step.done || step.value.type === "error") throw new LlmUnavailableError();
418
+ if (step.value.type === "text-delta" && step.value.text) first = step.value.text;
419
+ }
420
+ return new ReadableStream({
421
+ start(controller) {
422
+ controller.enqueue(first);
423
+ },
424
+ async pull(controller) {
425
+ for (; ; ) {
426
+ let step;
427
+ try {
428
+ step = await iterator.next();
429
+ } catch {
430
+ controller.error(new LlmUnavailableError());
431
+ return;
432
+ }
433
+ if (step.done) {
434
+ controller.close();
435
+ onDone?.();
436
+ return;
437
+ }
438
+ if (step.value.type === "error") {
439
+ controller.error(new LlmUnavailableError());
440
+ return;
441
+ }
442
+ if (step.value.type === "text-delta" && step.value.text) {
443
+ controller.enqueue(step.value.text);
444
+ return;
445
+ }
446
+ }
447
+ },
448
+ async cancel() {
449
+ await iterator.return?.();
450
+ }
451
+ });
452
+ }
453
+
454
+ // src/services/llm.service.ts
455
+ var LlmService = class {
456
+ constructor(config, settings2, personalInfo2, modelFactory, logger = console) {
457
+ this.config = config;
458
+ this.settings = settings2;
459
+ this.personalInfo = personalInfo2;
460
+ this.modelFactory = modelFactory;
461
+ this.logger = logger;
462
+ }
463
+ config;
464
+ settings;
465
+ personalInfo;
466
+ modelFactory;
467
+ logger;
468
+ async stream(req) {
469
+ const { fields, instructions, model } = await this.prepare(req);
470
+ const started = Date.now();
471
+ const result = streamText({
472
+ model: this.modelFactory(model),
473
+ instructions,
474
+ messages: req.messages.map((m) => ({ ...m, content: redactPii(m.content, fields) })),
475
+ maxOutputTokens: req.maxOutputTokens,
476
+ onError: () => {
477
+ }
478
+ });
479
+ const stream = await firstChunk(result.fullStream, () => {
480
+ void Promise.resolve(result.totalUsage).then(
481
+ (usage) => this.logCall(model, usage, started),
482
+ () => {
483
+ }
484
+ );
485
+ });
486
+ return { stream, model };
487
+ }
488
+ async generate(req) {
489
+ const { fields, instructions, model } = await this.prepare(req);
490
+ const started = Date.now();
491
+ try {
492
+ const result = await generateText({
493
+ model: this.modelFactory(model),
494
+ instructions,
495
+ prompt: redactPii(req.input, fields),
496
+ maxOutputTokens: req.maxOutputTokens
497
+ });
498
+ this.logCall(model, result.totalUsage, started);
499
+ return { text: result.text, model };
500
+ } catch {
501
+ throw new LlmUnavailableError();
502
+ }
503
+ }
504
+ /** Guard the system prompt and Career Body, resolve the model and build the system prompt. */
505
+ async prepare(req) {
506
+ const fields = await this.personalInfo.allValues();
507
+ const leaks = findPii(`${req.system}
508
+ ${req.body}`, fields);
509
+ if (leaks.length > 0) {
510
+ const key = leaks[0].key;
511
+ this.logger.warn("pii guard blocked an llm call", { fieldKey: key });
512
+ throw new PiiLeakError(key);
513
+ }
514
+ const model = await this.settings.model(req.area);
515
+ const instructions = `${req.system}
516
+
517
+ <cv>
518
+ ${req.body}
519
+ </cv>`;
520
+ return { fields, instructions, model };
521
+ }
522
+ logCall(model, usage, started) {
523
+ this.logger.info("llm call", {
524
+ model,
525
+ inputTokens: usage.inputTokens,
526
+ outputTokens: usage.outputTokens,
527
+ totalTokens: usage.totalTokens,
528
+ latencyMs: Date.now() - started
529
+ });
530
+ }
531
+ };
532
+
533
+ // src/services/profile.service.ts
534
+ var ProfileService = class {
535
+ constructor(repo) {
536
+ this.repo = repo;
537
+ }
538
+ repo;
539
+ async get() {
540
+ const row = await this.repo.find();
541
+ if (!row) throw new NotFoundError("Profile not found");
542
+ return row;
543
+ }
544
+ update(input) {
545
+ return this.repo.upsert(input);
546
+ }
547
+ };
548
+
549
+ // src/llm/data-block.ts
550
+ var MARKER_RUN = /[<>]{3,}/g;
551
+ function sanitizeMarkers(value) {
552
+ return value.replace(MARKER_RUN, "");
553
+ }
554
+ function dataBlock(name, value) {
555
+ return `<<<${name}_START>>>
556
+ ${sanitizeMarkers(value).trim()}
557
+ <<<${name}_END>>>`;
558
+ }
559
+ function wrapUserMessages(messages, name) {
560
+ return messages.map(
561
+ (m) => m.role === "user" ? { ...m, content: dataBlock(name, m.content) } : { ...m, content: sanitizeMarkers(m.content) }
562
+ );
563
+ }
564
+
565
+ // src/services/public-chat.service.ts
566
+ var EMPTY_CV = "The Master CV is empty: tell the visitor there is no career information yet.";
567
+ var PublicChatService = class {
568
+ constructor(usage, profile2, settings2, llm) {
569
+ this.usage = usage;
570
+ this.profile = profile2;
571
+ this.settings = settings2;
572
+ this.llm = llm;
573
+ }
574
+ usage;
575
+ profile;
576
+ settings;
577
+ llm;
578
+ /** Counts one question for `ipHash` atomically, then streams the model's answer. */
579
+ async ask(ipHash, messages) {
580
+ const profile2 = await this.profile.get();
581
+ const limit2 = await this.settings.limit("publicQuestionsPerIpPerDay");
582
+ const grant = await this.usage.acquire(ipHash, limit2);
583
+ if (!grant) throw new LimitReachedError();
584
+ try {
585
+ const { stream } = await this.llm.stream({
586
+ area: "public",
587
+ system: profile2.publicSystemPrompt,
588
+ body: profile2.masterCv.trim() === "" ? EMPTY_CV : profile2.masterCv,
589
+ messages: wrapUserMessages(messages, "VISITOR_MESSAGE"),
590
+ maxOutputTokens: await this.settings.limit("publicMaxOutputTokens")
591
+ });
592
+ return { stream, remaining: limit2 - grant.used };
593
+ } catch (error) {
594
+ if (error instanceof LlmUnavailableError || error instanceof PiiLeakError) {
595
+ await this.usage.release(ipHash, grant.day);
596
+ }
597
+ throw error;
598
+ }
599
+ }
600
+ };
601
+
602
+ // src/services/recruiter-chat.service.ts
603
+ var MAX_JOB_DESCRIPTION_CHARS = 2e3;
604
+ var MAX_QUESTIONS_LIMIT = 100;
605
+ var EMPTY_CV2 = "The Master CV is empty: tell the recruiter there is no career information yet.";
606
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
607
+ function invalid(field, reason) {
608
+ throw new ValidationError(`${field}: ${reason}`, { [field]: reason });
609
+ }
610
+ function newToken() {
611
+ const bytes = crypto.getRandomValues(new Uint8Array(18));
612
+ return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_");
613
+ }
614
+ function toChat(row) {
615
+ const { expired: expired2, status, ...rest } = row;
616
+ return {
617
+ ...rest,
618
+ status: status === "revoked" ? "revoked" : expired2 ? "expired" : "active"
619
+ };
620
+ }
621
+ function assertOpen(chat) {
622
+ if (chat.status === "revoked") throw new ChatRevokedError();
623
+ if (chat.status === "expired") throw new ChatExpiredError();
624
+ }
625
+ var RecruiterChatService = class {
626
+ constructor(chats, profile2, settings2, personalInfo2, llm) {
627
+ this.chats = chats;
628
+ this.profile = profile2;
629
+ this.settings = settings2;
630
+ this.personalInfo = personalInfo2;
631
+ this.llm = llm;
632
+ }
633
+ chats;
634
+ profile;
635
+ settings;
636
+ personalInfo;
637
+ llm;
638
+ async list() {
639
+ return (await this.chats.list()).map(toChat);
640
+ }
641
+ resumeOptions() {
642
+ return this.chats.resumeOptions();
643
+ }
644
+ async create(input) {
645
+ const recruiterName = (input.recruiterName ?? "").trim();
646
+ if (recruiterName === "") invalid("recruiterName", "must not be empty");
647
+ const jd = (input.jobDescriptionShort ?? "").trim();
648
+ if ([...jd].length > MAX_JOB_DESCRIPTION_CHARS) {
649
+ invalid("jobDescriptionShort", `must be at most ${MAX_JOB_DESCRIPTION_CHARS} characters`);
650
+ }
651
+ const maxQuestions = input.maxQuestions ?? await this.settings.limit("recruiterQuestionsDefault");
652
+ if (!Number.isInteger(maxQuestions) || maxQuestions < 1 || maxQuestions > MAX_QUESTIONS_LIMIT) {
653
+ invalid("maxQuestions", `must be an integer from 1 to ${MAX_QUESTIONS_LIMIT}`);
654
+ }
655
+ let expiresAt = null;
656
+ if (input.expiresAt !== void 0 && input.expiresAt.trim() !== "") {
657
+ expiresAt = new Date(input.expiresAt);
658
+ if (Number.isNaN(expiresAt.getTime())) invalid("expiresAt", "must be a valid date");
659
+ if (expiresAt.getTime() <= Date.now()) invalid("expiresAt", "must be in the future");
660
+ }
661
+ const resumeId = (input.tailoredResumeId ?? "").trim();
662
+ if (resumeId !== "" && !(UUID.test(resumeId) && await this.chats.resumeExists(resumeId))) {
663
+ invalid("tailoredResumeId", "Tailored Resume not found");
664
+ }
665
+ const company = (input.company ?? "").trim();
666
+ return toChat(
667
+ await this.chats.insert({
668
+ token: newToken(),
669
+ recruiterName,
670
+ company: company === "" ? null : company,
671
+ jobDescriptionShort: jd === "" ? null : jd,
672
+ tailoredResumeId: resumeId === "" ? null : resumeId,
673
+ maxQuestions,
674
+ expiresAt
675
+ })
676
+ );
677
+ }
678
+ async revoke(id) {
679
+ return this.found(UUID.test(id) ? await this.chats.revoke(id) : null);
680
+ }
681
+ /** Resets `used` only; a revoked chat stays revoked. */
682
+ async reset(id) {
683
+ return this.found(UUID.test(id) ? await this.chats.reset(id) : null);
684
+ }
685
+ async delete(id) {
686
+ if (!UUID.test(id) || !await this.chats.delete(id)) throw new NotFoundError();
687
+ }
688
+ /** The chat behind a token, whatever its status; NotFound when there is none. */
689
+ async byToken(token) {
690
+ return this.found(await this.chats.findByToken(token));
691
+ }
692
+ /** The chat behind a token, only if it can still be used (404, 410 otherwise). */
693
+ async requireActive(token) {
694
+ const chat = await this.byToken(token);
695
+ assertOpen(chat);
696
+ return chat;
697
+ }
698
+ async open(token) {
699
+ const chat = await this.requireActive(token);
700
+ return {
701
+ recruiterName: chat.recruiterName,
702
+ company: chat.company,
703
+ remaining: chat.maxQuestions - chat.used,
704
+ status: "active",
705
+ contact: await this.personalInfo.contactFor("recruiter")
706
+ };
707
+ }
708
+ /** The chat behind a token, if the session's chat id is that chat (403 otherwise). */
709
+ async authorize(token, cid) {
710
+ const chat = await this.byToken(token);
711
+ if (cid === void 0 || chat.id !== cid) throw new ForbiddenError();
712
+ return chat;
713
+ }
714
+ /** Counts one question atomically, then streams the answer. */
715
+ async ask(chat, messages) {
716
+ const granted = await this.chats.acquire(chat.id);
717
+ if (!granted) {
718
+ const current = await this.chats.findById(chat.id);
719
+ if (!current) throw new NotFoundError();
720
+ assertOpen(toChat(current));
721
+ throw new LimitReachedError();
722
+ }
723
+ try {
724
+ const profile2 = await this.profile.get();
725
+ const resume = await this.chats.resumeContent(granted.tailoredResumeId);
726
+ const content = resume !== null && resume.trim() !== "" ? resume : profile2.masterCv;
727
+ const jd = granted.jobDescriptionShort;
728
+ const { stream } = await this.llm.stream({
729
+ area: "recruiter",
730
+ system: jd === null ? profile2.recruiterSystemPrompt : `${profile2.recruiterSystemPrompt}
731
+
732
+ Job Description:
733
+ ${dataBlock("JOB_DESCRIPTION", jd)}`,
734
+ body: content.trim() === "" ? EMPTY_CV2 : content,
735
+ messages: wrapUserMessages(messages, "RECRUITER_MESSAGE"),
736
+ maxOutputTokens: await this.settings.limit("recruiterMaxOutputTokens")
737
+ });
738
+ await this.chats.touch(granted.id);
739
+ return {
740
+ stream: await this.recordTranscript(granted.id, messages, stream),
741
+ remaining: granted.maxQuestions - granted.used
742
+ };
743
+ } catch (error) {
744
+ if (error instanceof LlmUnavailableError) await this.chats.release(granted.id);
745
+ throw error;
746
+ }
747
+ }
748
+ /** The chat and its messages, oldest first; NotFound for an unknown or malformed id. */
749
+ async transcript(id) {
750
+ const row = UUID.test(id) ? await this.chats.findById(id) : null;
751
+ const chat = this.found(row);
752
+ return { chat, messages: await this.chats.messages(chat.id) };
753
+ }
754
+ /**
755
+ * Passes the answer through unchanged and, when it completes, stores the question the model saw
756
+ * (after the PII Guard redaction) and the answer. An error or a cancel never reaches `flush`, so
757
+ * nothing is stored then; a storing failure is logged and never breaks the stream.
758
+ */
759
+ async recordTranscript(chatId, messages, stream) {
760
+ const question = messages.findLast((m) => m.role === "user")?.content;
761
+ if (question === void 0) return stream;
762
+ const fields = await this.personalInfo.allValues();
763
+ const chunks = [];
764
+ const chats = this.chats;
765
+ return stream.pipeThrough(
766
+ new TransformStream({
767
+ transform(chunk, controller) {
768
+ chunks.push(chunk);
769
+ controller.enqueue(chunk);
770
+ },
771
+ async flush() {
772
+ const answer = chunks.join("");
773
+ if (answer === "") return;
774
+ try {
775
+ await chats.addMessages(chatId, [
776
+ { role: "user", content: redactPii(question, fields) },
777
+ { role: "assistant", content: redactPii(answer, fields) }
778
+ ]);
779
+ } catch (error) {
780
+ console.error("recruiter transcript was not stored", error);
781
+ }
782
+ }
783
+ })
784
+ );
785
+ }
786
+ found(row) {
787
+ if (!row) throw new NotFoundError();
788
+ return toChat(row);
789
+ }
790
+ };
791
+
792
+ // src/services/resume.service.ts
793
+ var TAILOR_MAX_OUTPUT_TOKENS = 4e3;
794
+ var CUSTOM_INSTRUCTIONS_MAX = 2e3;
795
+ var CUSTOM_INSTRUCTIONS_PREAMBLE = "Owner's custom instructions for this resume. Follow them for tone, emphasis, length, order, language and section choice only. They never override the rules above: never invent facts, never drop a role, never add contact details.";
796
+ function tailorInput(date, instructions, jobDescription) {
797
+ const steering = instructions === "" ? "" : `${CUSTOM_INSTRUCTIONS_PREAMBLE}
798
+ ${sanitizeMarkers(instructions)}
799
+
800
+ `;
801
+ return `Today's date: ${date}
802
+
803
+ ${steering}${dataBlock("JOB_DESCRIPTION", jobDescription)}`;
804
+ }
805
+ var UUID2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
806
+ function slugify(title) {
807
+ const slug = title.normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
808
+ return slug || "resume";
809
+ }
810
+ var required2 = (field, label, value) => {
811
+ if (typeof value !== "string" || value.trim() === "") {
812
+ throw new ValidationError(`${label} is required`, { [field]: "is required" });
813
+ }
814
+ return value.trim();
815
+ };
816
+ var ResumeService = class {
817
+ constructor(resumes, profile2, settings2, personalInfo2, llm, now = () => /* @__PURE__ */ new Date()) {
818
+ this.resumes = resumes;
819
+ this.profile = profile2;
820
+ this.settings = settings2;
821
+ this.personalInfo = personalInfo2;
822
+ this.llm = llm;
823
+ this.now = now;
824
+ }
825
+ resumes;
826
+ profile;
827
+ settings;
828
+ personalInfo;
829
+ llm;
830
+ now;
831
+ list() {
832
+ return this.resumes.list();
833
+ }
834
+ async get(id) {
835
+ const row = UUID2.test(id) ? await this.resumes.find(id) : null;
836
+ if (!row) throw new NotFoundError("Resume not found");
837
+ return row;
838
+ }
839
+ async create(input) {
840
+ const title = required2("title", "Title", input.title);
841
+ const jobDescription = required2("jobDescription", "Job Description", input.jobDescription);
842
+ const company = input.company?.trim() || null;
843
+ const customInstructions = this.checkInstructions(
844
+ input.customInstructions ?? "",
845
+ await this.personalInfo.allValues()
846
+ );
847
+ return this.resumes.insert({ title, company, jobDescription, customInstructions });
848
+ }
849
+ async delete(id) {
850
+ await this.get(id);
851
+ await this.resumes.delete(id);
852
+ }
853
+ /** Personal Info Fields the editor offers as header checkboxes. */
854
+ headerOptions() {
855
+ return this.personalInfo.list();
856
+ }
857
+ /** Tailors the Master CV to the Job Description. The model sees only those two texts. */
858
+ async generate(id, customInstructions) {
859
+ let resume = await this.get(id);
860
+ const instructions = customInstructions === void 0 ? void 0 : this.checkInstructions(customInstructions, await this.personalInfo.allValues());
861
+ const profile2 = await this.loadProfile();
862
+ if (!profile2 || profile2.masterCv.trim() === "") {
863
+ throw new ValidationError("Fill the master CV first");
864
+ }
865
+ if (instructions !== void 0) {
866
+ resume = await this.update(id, { customInstructions: instructions });
867
+ }
868
+ const { text, model } = await this.llm.generate({
869
+ area: "tailor",
870
+ system: profile2.tailorSystemPrompt,
871
+ body: profile2.masterCv,
872
+ input: tailorInput(
873
+ this.now().toISOString().slice(0, 10),
874
+ resume.customInstructions,
875
+ resume.jobDescription
876
+ ),
877
+ maxOutputTokens: TAILOR_MAX_OUTPUT_TOKENS
878
+ });
879
+ return this.update(id, { content: text, model });
880
+ }
881
+ /** Saves the markdown and the selected header keys after the PII Guard. */
882
+ async save(id, content, headerKeys, customInstructions) {
883
+ await this.get(id);
884
+ const fields = await this.personalInfo.allValues();
885
+ const instructions = customInstructions === void 0 ? void 0 : this.checkInstructions(customInstructions, fields);
886
+ const found = findPii(content, fields)[0];
887
+ if (found) {
888
+ throw new ValidationError(
889
+ `Your ${found.label} is in the body \u2014 keep contact data in Personal info`
890
+ );
891
+ }
892
+ const existing = fields.map((f) => f.key);
893
+ const kept = [...new Set(headerKeys)].filter((k) => existing.includes(k));
894
+ const all = existing.every((k) => kept.includes(k));
895
+ return this.update(id, {
896
+ content,
897
+ headerFields: all ? null : kept,
898
+ ...instructions === void 0 ? {} : { customInstructions: instructions }
899
+ });
900
+ }
901
+ async printData(id) {
902
+ const resume = await this.get(id);
903
+ const items = await this.personalInfo.contactFor("print");
904
+ const selected = resume.headerFields;
905
+ const header = selected === null ? items : items.filter((i) => selected.includes(i.key));
906
+ return this.buildPrint(header, resume.content, items);
907
+ }
908
+ async profilePrintData() {
909
+ const profile2 = await this.loadProfile();
910
+ const items = await this.personalInfo.contactFor("print");
911
+ return this.buildPrint(items, profile2?.masterCv ?? "", items, profile2);
912
+ }
913
+ async download(id) {
914
+ const resume = await this.get(id);
915
+ const data = await this.printData(id);
916
+ const lines = [`# ${data.fullName}`, ...data.header.map((h) => `${h.label}: ${h.value}`)];
917
+ return {
918
+ filename: `${slugify(resume.title)}.md`,
919
+ text: `${lines.join("\n")}
920
+
921
+ ${resume.content}`
922
+ };
923
+ }
924
+ /** Trims, bounds and PII-checks Custom Instructions; returns the value to store. */
925
+ checkInstructions(value, fields) {
926
+ const trimmed = value.trim();
927
+ if (trimmed.length > CUSTOM_INSTRUCTIONS_MAX) {
928
+ throw new ValidationError(
929
+ `Custom instructions must be at most ${CUSTOM_INSTRUCTIONS_MAX} characters`,
930
+ { customInstructions: "is too long" }
931
+ );
932
+ }
933
+ const found = findPii(trimmed, fields)[0];
934
+ if (found) {
935
+ throw new ValidationError(
936
+ `Your ${found.label} is in the custom instructions \u2014 keep contact data in Personal info`,
937
+ { customInstructions: "contains personal info" }
938
+ );
939
+ }
940
+ return trimmed;
941
+ }
942
+ async update(id, patch) {
943
+ const row = await this.resumes.update(id, patch);
944
+ if (!row) throw new NotFoundError("Resume not found");
945
+ return row;
946
+ }
947
+ async loadProfile() {
948
+ try {
949
+ return await this.profile.get();
950
+ } catch (error) {
951
+ if (error instanceof NotFoundError) return null;
952
+ throw error;
953
+ }
954
+ }
955
+ async buildPrint(header, body, allFields, known) {
956
+ const profile2 = known === void 0 ? await this.loadProfile() : known;
957
+ return {
958
+ fullName: profile2?.fullName ?? "",
959
+ header,
960
+ bodyHtml: renderMarkdown(body),
961
+ empty: body.trim() === "",
962
+ warnings: findPii(body, allFields).map((m) => m.label),
963
+ pageSize: await this.settings.pageSize()
964
+ };
965
+ }
966
+ };
967
+
968
+ // src/services/settings.service.ts
969
+ var SettingsService = class {
970
+ constructor(repo, config) {
971
+ this.repo = repo;
972
+ this.config = config;
973
+ }
974
+ repo;
975
+ config;
976
+ async model(area) {
977
+ const override = await this.repo.get(modelKey(area));
978
+ if (override) return override;
979
+ const fallback = this.config.models[area];
980
+ if (fallback) return fallback;
981
+ throw new ConfigError([modelKey(area)]);
982
+ }
983
+ async limit(name) {
984
+ const override = await this.repo.get(limitKey(name));
985
+ if (override !== null) {
986
+ const value = Number(override);
987
+ if (Number.isInteger(value) && value > 0) return value;
988
+ }
989
+ return this.config.limits[name];
990
+ }
991
+ async pageSize() {
992
+ const override = await this.repo.get(PAGE_SIZE_KEY);
993
+ return PAGE_SIZES.find((p) => p === override) ?? "A4";
994
+ }
995
+ async set(key, value) {
996
+ if (!SETTINGS_KEYS.includes(key)) {
997
+ throw new ValidationError(`Unknown setting: ${key}`, { key: "unknown setting" });
998
+ }
999
+ if (value === "") {
1000
+ await this.repo.delete(key);
1001
+ return;
1002
+ }
1003
+ if (key.startsWith("limits.") && !/^[1-9]\d*$/.test(value)) {
1004
+ throw new ValidationError(`${key} must be a positive integer`, { [key]: "positive integer" });
1005
+ }
1006
+ if (key === PAGE_SIZE_KEY && !PAGE_SIZES.some((p) => p === value)) {
1007
+ throw new ValidationError(`${key} must be A4 or Letter`, { [key]: "A4 or Letter" });
1008
+ }
1009
+ await this.repo.set(key, value);
1010
+ }
1011
+ overrides() {
1012
+ return this.repo.all();
1013
+ }
1014
+ };
1015
+
1016
+ // src/container.ts
1017
+ function createContainer(config) {
1018
+ const db = createDb(config.databaseUrl);
1019
+ const repos = {
1020
+ profile: new ProfileRepository(db),
1021
+ settings: new SettingsRepository(db),
1022
+ personalInfo: new PersonalInfoRepository(db),
1023
+ publicUsage: new PublicUsageRepository(db),
1024
+ recruiterChats: new RecruiterChatRepository(db),
1025
+ resumes: new ResumeRepository(db),
1026
+ loginAttempts: new AdminLoginAttemptRepository(db)
1027
+ };
1028
+ const settings2 = new SettingsService(repos.settings, config);
1029
+ const personalInfo2 = new PersonalInfoService(repos.personalInfo, config.piiEncryptionKey);
1030
+ const profile2 = new ProfileService(repos.profile);
1031
+ const llm = new LlmService(
1032
+ config,
1033
+ settings2,
1034
+ personalInfo2,
1035
+ createProvider(config.openrouterApiKey)
1036
+ );
1037
+ return {
1038
+ config,
1039
+ profile: profile2,
1040
+ settings: settings2,
1041
+ personalInfo: personalInfo2,
1042
+ llm,
1043
+ publicChat: new PublicChatService(repos.publicUsage, profile2, settings2, llm),
1044
+ recruiterChat: new RecruiterChatService(
1045
+ repos.recruiterChats,
1046
+ profile2,
1047
+ settings2,
1048
+ personalInfo2,
1049
+ llm
1050
+ ),
1051
+ resumes: new ResumeService(repos.resumes, profile2, settings2, personalInfo2, llm),
1052
+ adminAuth: new AdminAuthService(repos.loginAttempts, config)
1053
+ };
1054
+ }
1055
+
1056
+ // src/middleware/security-headers.ts
1057
+ import { createMiddleware } from "hono/factory";
1058
+ var ADMIN_CSP = "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-ancestors 'none'";
1059
+ function securityHeaders(basePath = "") {
1060
+ const adminPrefix = `${basePath}/admin`;
1061
+ return createMiddleware(async (c, next) => {
1062
+ await next();
1063
+ c.header("X-Frame-Options", "DENY");
1064
+ c.header("Referrer-Policy", "same-origin");
1065
+ c.header("X-Content-Type-Options", "nosniff");
1066
+ const path = c.req.path;
1067
+ if (path === adminPrefix || path.startsWith(`${adminPrefix}/`)) {
1068
+ c.header("Content-Security-Policy", ADMIN_CSP);
1069
+ }
1070
+ });
1071
+ }
1072
+
1073
+ // src/routes/health.ts
1074
+ import { createRoute, OpenAPIHono, z as z2 } from "@hono/zod-openapi";
1075
+ var route = createRoute({
1076
+ method: "get",
1077
+ path: "/health",
1078
+ summary: "Liveness check; never touches the database",
1079
+ responses: {
1080
+ 200: {
1081
+ description: "The app is running",
1082
+ content: { "application/json": { schema: z2.object({ ok: z2.literal(true) }) } }
1083
+ }
1084
+ }
1085
+ });
1086
+ var healthRouter = new OpenAPIHono();
1087
+ healthRouter.openapi(route, (c) => c.json({ ok: true }, 200));
1088
+
1089
+ // src/routes/openapi.ts
1090
+ function mountOpenApi(api, config) {
1091
+ api.doc31("/openapi.json", {
1092
+ openapi: "3.1.0",
1093
+ info: { title: "curriculum-api", version: "0.0.0" },
1094
+ servers: [{ url: `${config.basePath}/api` }]
1095
+ });
1096
+ }
1097
+
1098
+ // src/routes/public.ts
1099
+ import { OpenAPIHono as OpenAPIHono2 } from "@hono/zod-openapi";
1100
+ import { z as z3 } from "zod";
1101
+
1102
+ // src/middleware/require-session.ts
1103
+ import { getCookie } from "hono/cookie";
1104
+ import { createMiddleware as createMiddleware2 } from "hono/factory";
1105
+ function requireSession(scope) {
1106
+ return createMiddleware2(async (c, next) => {
1107
+ const token = getCookie(c, SESSION_COOKIE);
1108
+ if (!token) throw new UnauthorizedError();
1109
+ const session = await verifySession(token, c.var.config.sessionSecret);
1110
+ if (!session || session.scope !== scope) throw new UnauthorizedError();
1111
+ c.set("session", session);
1112
+ await next();
1113
+ });
1114
+ }
1115
+
1116
+ // src/security/turnstile.ts
1117
+ var VERIFY_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverify";
1118
+ async function verifyTurnstile(token, ip, secret, fetchFn = fetch) {
1119
+ try {
1120
+ const body = new URLSearchParams({ secret, response: token });
1121
+ if (ip) body.set("remoteip", ip);
1122
+ const res = await fetchFn(VERIFY_URL, { method: "POST", body });
1123
+ if (!res.ok) return false;
1124
+ const json = await res.json();
1125
+ return json.success === true;
1126
+ } catch {
1127
+ return false;
1128
+ }
1129
+ }
1130
+
1131
+ // src/routes/public.ts
1132
+ var publicRouter = new OpenAPIHono2();
1133
+ var chatBody = z3.object({
1134
+ messages: z3.array(z3.object({ role: z3.enum(["user", "assistant"]), content: z3.string() }))
1135
+ });
1136
+ var sessionBody = z3.object({ turnstileToken: z3.string() });
1137
+ async function parseJson(req, schema2) {
1138
+ const raw = await req.json().catch(() => void 0);
1139
+ const parsed = schema2.safeParse(raw);
1140
+ if (!parsed.success) throw new ValidationError("Invalid request body");
1141
+ return parsed.data;
1142
+ }
1143
+ publicRouter.post("/session", async (c) => {
1144
+ const { turnstileToken } = await parseJson(c.req.raw, sessionBody);
1145
+ const { config } = c.var;
1146
+ const ok = await verifyTurnstile(
1147
+ turnstileToken,
1148
+ clientIp(c.req.raw.headers),
1149
+ config.turnstileSecret
1150
+ );
1151
+ if (!ok) throw new CaptchaFailedError();
1152
+ const ttl = config.limits.sessionTtlMinutes * 60;
1153
+ setSessionCookie(c, await signSession({ scope: "public" }, config.sessionSecret, ttl), config);
1154
+ return c.body(null, 204);
1155
+ });
1156
+ publicRouter.get("/profile", async (c) => {
1157
+ const { profile: profile2, personalInfo: personalInfo2 } = c.var.services;
1158
+ const { fullName, headline } = await profile2.get();
1159
+ const contact = await personalInfo2.contactFor("public");
1160
+ c.header("Cache-Control", "no-store");
1161
+ return c.json({ fullName, headline, contact });
1162
+ });
1163
+ publicRouter.post("/chat", requireSession("public"), async (c) => {
1164
+ const { config, services } = c.var;
1165
+ const { messages } = await parseJson(c.req.raw, chatBody);
1166
+ const [maxHistory, maxChars] = await Promise.all([
1167
+ services.settings.limit("maxHistoryMessages"),
1168
+ services.settings.limit("maxQuestionChars")
1169
+ ]);
1170
+ const last = messages.at(-1);
1171
+ const total = messages.reduce((sum, m) => sum + [...m.content].length, 0);
1172
+ if (messages.length < 1 || messages.length > maxHistory || last?.role !== "user" || last.content === "" || [...last.content].length > maxChars || total > maxChars * maxHistory) {
1173
+ throw new ValidationError("Invalid request body");
1174
+ }
1175
+ const ipHash = await hashIp(clientIp(c.req.raw.headers) ?? "unknown", config.ipHashSalt);
1176
+ const { stream, remaining } = await services.publicChat.ask(ipHash, messages);
1177
+ return new Response(stream.pipeThrough(new TextEncoderStream()), {
1178
+ headers: {
1179
+ "Content-Type": "text/plain; charset=utf-8",
1180
+ "Cache-Control": "no-store",
1181
+ "X-Remaining": String(remaining)
1182
+ }
1183
+ });
1184
+ });
1185
+
1186
+ // src/routes/recruiter.ts
1187
+ import { OpenAPIHono as OpenAPIHono3 } from "@hono/zod-openapi";
1188
+ import { z as z4 } from "zod";
1189
+
1190
+ // src/middleware/require-active-recruiter-chat.ts
1191
+ import { createMiddleware as createMiddleware3 } from "hono/factory";
1192
+ var requireActiveRecruiterChat = createMiddleware3(async (c, next) => {
1193
+ await c.var.services.recruiterChat.requireActive(c.req.param("token") ?? "");
1194
+ await next();
1195
+ });
1196
+
1197
+ // src/routes/recruiter.ts
1198
+ var recruiterRouter = new OpenAPIHono3();
1199
+ var chatBody2 = z4.object({
1200
+ messages: z4.array(z4.object({ role: z4.enum(["user", "assistant"]), content: z4.string() }))
1201
+ });
1202
+ var sessionBody2 = z4.object({ turnstileToken: z4.string() });
1203
+ async function parseJson2(req, schema2) {
1204
+ const raw = await req.json().catch(() => void 0);
1205
+ const parsed = schema2.safeParse(raw);
1206
+ if (!parsed.success) throw new ValidationError("Invalid request body");
1207
+ return parsed.data;
1208
+ }
1209
+ recruiterRouter.use("*", async (c, next) => {
1210
+ c.header("Cache-Control", "no-store");
1211
+ c.header("X-Robots-Tag", "noindex");
1212
+ await next();
1213
+ });
1214
+ recruiterRouter.get(
1215
+ "/",
1216
+ requireActiveRecruiterChat,
1217
+ async (c) => c.json(await c.var.services.recruiterChat.open(c.req.param("token") ?? ""))
1218
+ );
1219
+ recruiterRouter.post("/session", requireActiveRecruiterChat, async (c) => {
1220
+ const { turnstileToken } = await parseJson2(c.req.raw, sessionBody2);
1221
+ const { config, services } = c.var;
1222
+ const ok = await verifyTurnstile(
1223
+ turnstileToken,
1224
+ clientIp(c.req.raw.headers),
1225
+ config.turnstileSecret
1226
+ );
1227
+ if (!ok) throw new CaptchaFailedError();
1228
+ const chat = await services.recruiterChat.requireActive(c.req.param("token") ?? "");
1229
+ const ttl = config.limits.sessionTtlMinutes * 60;
1230
+ setSessionCookie(
1231
+ c,
1232
+ await signSession({ scope: "recruiter", cid: chat.id }, config.sessionSecret, ttl),
1233
+ config
1234
+ );
1235
+ return c.body(null, 204);
1236
+ });
1237
+ recruiterRouter.post("/chat", requireSession("recruiter"), async (c) => {
1238
+ const { services } = c.var;
1239
+ const chat = await services.recruiterChat.authorize(
1240
+ c.req.param("token") ?? "",
1241
+ c.var.session?.cid
1242
+ );
1243
+ const { messages } = await parseJson2(c.req.raw, chatBody2);
1244
+ const [maxHistory, maxChars] = await Promise.all([
1245
+ services.settings.limit("maxHistoryMessages"),
1246
+ services.settings.limit("maxQuestionChars")
1247
+ ]);
1248
+ const last = messages.at(-1);
1249
+ const total = messages.reduce((sum, m) => sum + [...m.content].length, 0);
1250
+ if (messages.length < 1 || messages.length > maxHistory || last?.role !== "user" || last.content === "" || [...last.content].length > maxChars || total > maxChars * maxHistory) {
1251
+ throw new ValidationError("Invalid request body");
1252
+ }
1253
+ const { stream, remaining } = await services.recruiterChat.ask(chat, messages);
1254
+ return new Response(stream.pipeThrough(new TextEncoderStream()), {
1255
+ headers: {
1256
+ "Content-Type": "text/plain; charset=utf-8",
1257
+ "Cache-Control": "no-store",
1258
+ "X-Robots-Tag": "noindex",
1259
+ "X-Remaining": String(remaining)
1260
+ }
1261
+ });
1262
+ });
1263
+
1264
+ // src/app.ts
1265
+ function createApp(config) {
1266
+ const resolved = resolveConfig(config);
1267
+ return buildApp(resolved, createContainer(resolved));
1268
+ }
1269
+ function buildApp(config, services, extend) {
1270
+ const api = new OpenAPIHono4({
1271
+ defaultHook: (result) => {
1272
+ if (!result.success) {
1273
+ const fields = {};
1274
+ for (const issue of result.error.issues)
1275
+ fields[issue.path.join(".") || "body"] = issue.message;
1276
+ throw new ValidationError("Invalid request", fields);
1277
+ }
1278
+ }
1279
+ });
1280
+ api.onError((error, c) => {
1281
+ if (error instanceof DomainError) {
1282
+ if (error.status >= 500) {
1283
+ console.error(error);
1284
+ return c.json({ error: error.code }, error.status);
1285
+ }
1286
+ return c.json({ error: error.code, message: error.message }, error.status);
1287
+ }
1288
+ console.error(error);
1289
+ return c.json({ error: "internal_error" }, 500);
1290
+ });
1291
+ api.notFound((c) => c.json({ error: new NotFoundError().code }, 404));
1292
+ api.route("/", healthRouter);
1293
+ api.route("/public", publicRouter);
1294
+ api.route("/r/:token", recruiterRouter);
1295
+ extend?.(api);
1296
+ mountOpenApi(api, config);
1297
+ let admin;
1298
+ const loadAdmin = () => {
1299
+ admin ??= import("./admin-U7LVEF3Y.js").then((m) => m.adminRouter(config, services));
1300
+ return admin;
1301
+ };
1302
+ const routes = new Hono();
1303
+ routes.use("*", async (c, next) => {
1304
+ c.set("config", config);
1305
+ c.set("services", services);
1306
+ await next();
1307
+ });
1308
+ routes.route("/api", api);
1309
+ routes.get("/r/:token", (c) => {
1310
+ c.header("Cache-Control", "no-store");
1311
+ c.header("X-Robots-Tag", "noindex");
1312
+ return c.redirect(
1313
+ `${config.basePath}/admin/chat/${encodeURIComponent(c.req.param("token"))}`,
1314
+ 303
1315
+ );
1316
+ });
1317
+ routes.all("/admin/*", async (c) => (await loadAdmin()).fetch(c.req.raw));
1318
+ routes.all("/admin", async (c) => (await loadAdmin()).fetch(c.req.raw));
1319
+ const app = new Hono();
1320
+ app.use("*", securityHeaders(config.basePath));
1321
+ app.route(config.basePath || "/", routes);
1322
+ return app;
1323
+ }
1324
+ export {
1325
+ CaptchaFailedError,
1326
+ ChatExpiredError,
1327
+ ChatRevokedError,
1328
+ ConfigError,
1329
+ DecryptionError,
1330
+ DomainError,
1331
+ ForbiddenError,
1332
+ LimitReachedError,
1333
+ LlmUnavailableError,
1334
+ NotFoundError,
1335
+ PiiLeakError,
1336
+ UnauthorizedError,
1337
+ ValidationError,
1338
+ createApp,
1339
+ migrate,
1340
+ seed
1341
+ };