@siduri-x/api 1.0.2 → 1.0.5

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.
Files changed (43) hide show
  1. package/dist/app.d.ts +43 -0
  2. package/dist/app.js +637 -0
  3. package/dist/auth.d.ts +34 -0
  4. package/dist/auth.js +84 -0
  5. package/dist/auth.test.d.ts +1 -0
  6. package/dist/auth.test.js +74 -0
  7. package/dist/b0-b6.test.d.ts +1 -0
  8. package/dist/b0-b6.test.js +121 -0
  9. package/dist/context-mapper.d.ts +18 -0
  10. package/dist/context-mapper.js +160 -0
  11. package/dist/context-mapper.test.d.ts +1 -0
  12. package/dist/context-mapper.test.js +136 -0
  13. package/dist/cors.d.ts +3 -0
  14. package/dist/cors.js +42 -0
  15. package/dist/index.d.ts +6 -0
  16. package/dist/index.js +191 -0
  17. package/dist/index.test.d.ts +1 -0
  18. package/dist/index.test.js +137 -0
  19. package/dist/runtime.d.ts +1 -0
  20. package/dist/runtime.js +17 -0
  21. package/dist/runtime.test.d.ts +1 -0
  22. package/dist/runtime.test.js +282 -0
  23. package/dist/smoke.test.d.ts +0 -0
  24. package/dist/smoke.test.js +6 -0
  25. package/dist/t4-gating.test.d.ts +1 -0
  26. package/dist/t4-gating.test.js +193 -0
  27. package/dist/t5-experience.test.d.ts +1 -0
  28. package/dist/t5-experience.test.js +155 -0
  29. package/dist/t6-security.test.d.ts +1 -0
  30. package/dist/t6-security.test.js +423 -0
  31. package/dist/t7-release.test.d.ts +1 -0
  32. package/dist/t7-release.test.js +119 -0
  33. package/package.json +14 -11
  34. package/src/app.ts +36 -64
  35. package/src/auth.test.ts +56 -23
  36. package/src/auth.ts +74 -22
  37. package/src/context-mapper.test.ts +42 -147
  38. package/src/context-mapper.ts +44 -179
  39. package/src/index.test.ts +8 -32
  40. package/src/index.ts +19 -3
  41. package/src/runtime.test.ts +3 -5
  42. package/src/t5-experience.test.ts +0 -1
  43. package/src/t6-security.test.ts +0 -1
package/dist/auth.d.ts ADDED
@@ -0,0 +1,34 @@
1
+ import { Request, Response, NextFunction } from 'express';
2
+ export type Role = 'OWNER' | 'OPERATOR' | 'VIEWER' | 'user' | string;
3
+ export interface Identity {
4
+ authenticated: boolean;
5
+ source: 'local' | 'external';
6
+ actorId?: string;
7
+ role?: Role;
8
+ [key: string]: unknown;
9
+ }
10
+ /**
11
+ * Checks whether an incoming request originates from the local machine loopback interface.
12
+ */
13
+ export declare function isLocalRequest(req: Request): boolean;
14
+ /**
15
+ * Resolves request identity according to the single-owner external machine boundary security model.
16
+ *
17
+ * - Security is enforced at the external machine boundary, NOT internally.
18
+ * - External network requests require a matching token (AUTH_TOKEN / OWNER_TOKEN).
19
+ * - There are no internal viewer/operator/owner role privileges inside the machine.
20
+ */
21
+ export declare function resolveIdentity(req: Request): Identity;
22
+ /**
23
+ * External boundary authentication middleware.
24
+ * Verifies that requests crossing the external boundary are authorized.
25
+ */
26
+ export declare function requireAuth(req: Request, res: Response, next: NextFunction): Response<any, Record<string, any>> | undefined;
27
+ /**
28
+ * Attaches the resolved machine identity to the request.
29
+ */
30
+ export declare function attachIdentity(req: Request, res: Response, next: NextFunction): void;
31
+ /**
32
+ * Compatibility alias: in single-owner model, all authenticated callers have full access.
33
+ */
34
+ export declare function requireRole(allowedRoles?: Role[]): (req: Request, res: Response, next: NextFunction) => Response<any, Record<string, any>> | undefined;
package/dist/auth.js ADDED
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isLocalRequest = isLocalRequest;
4
+ exports.resolveIdentity = resolveIdentity;
5
+ exports.requireAuth = requireAuth;
6
+ exports.attachIdentity = attachIdentity;
7
+ exports.requireRole = requireRole;
8
+ /**
9
+ * Checks whether an incoming request originates from the local machine loopback interface.
10
+ */
11
+ function isLocalRequest(req) {
12
+ const ip = req.ip || req.socket?.remoteAddress || '';
13
+ return (ip === '127.0.0.1' ||
14
+ ip === '::1' ||
15
+ ip === '::ffff:127.0.0.1' ||
16
+ ip.endsWith('127.0.0.1') ||
17
+ ip === 'localhost');
18
+ }
19
+ /**
20
+ * Resolves request identity according to the single-owner external machine boundary security model.
21
+ *
22
+ * - Security is enforced at the external machine boundary, NOT internally.
23
+ * - External network requests require a matching token (AUTH_TOKEN / OWNER_TOKEN).
24
+ * - There are no internal viewer/operator/owner role privileges inside the machine.
25
+ */
26
+ function resolveIdentity(req) {
27
+ const authHeader = req.headers?.authorization;
28
+ const token = authHeader?.startsWith('Bearer ') ? authHeader.split(' ')[1] : undefined;
29
+ const ownerToken = process.env.AUTH_TOKEN || process.env.API_TOKEN || process.env.OWNER_TOKEN;
30
+ const operatorToken = process.env.OPERATOR_TOKEN;
31
+ const configuredToken = ownerToken || operatorToken;
32
+ const local = isLocalRequest(req);
33
+ // 1. Explicit token matches
34
+ if (ownerToken && token === ownerToken) {
35
+ return { authenticated: true, source: local ? 'local' : 'external', role: 'OWNER' };
36
+ }
37
+ if (operatorToken && token === operatorToken) {
38
+ return { authenticated: true, source: local ? 'local' : 'external', role: 'OPERATOR' };
39
+ }
40
+ // 2. Dev local auth role fallback
41
+ const isDev = process.env.NODE_ENV !== 'production';
42
+ if (isDev && process.env.DEV_LOCAL_AUTH_ROLE) {
43
+ const fallbackRole = process.env.DEV_LOCAL_AUTH_ROLE.toUpperCase();
44
+ return {
45
+ authenticated: fallbackRole === 'OWNER' || fallbackRole === 'OPERATOR',
46
+ source: 'local',
47
+ role: fallbackRole,
48
+ };
49
+ }
50
+ // 3. Default unauthenticated / visitor
51
+ return { authenticated: false, source: local ? 'local' : 'external', role: 'VIEWER' };
52
+ }
53
+ /**
54
+ * External boundary authentication middleware.
55
+ * Verifies that requests crossing the external boundary are authorized.
56
+ */
57
+ function requireAuth(req, res, next) {
58
+ const identity = resolveIdentity(req);
59
+ req.identity = identity;
60
+ if (!identity.authenticated) {
61
+ return res.status(401).json({ error: 'Unauthorized: missing or invalid authentication token' });
62
+ }
63
+ next();
64
+ }
65
+ /**
66
+ * Attaches the resolved machine identity to the request.
67
+ */
68
+ function attachIdentity(req, res, next) {
69
+ req.identity = resolveIdentity(req);
70
+ next();
71
+ }
72
+ /**
73
+ * Compatibility alias: in single-owner model, all authenticated callers have full access.
74
+ */
75
+ function requireRole(allowedRoles) {
76
+ return (req, res, next) => {
77
+ const identity = resolveIdentity(req);
78
+ req.identity = identity;
79
+ if (!identity.authenticated) {
80
+ return res.status(403).json({ error: `Forbidden: requires one of ${(allowedRoles || []).join(', ')}` });
81
+ }
82
+ next();
83
+ };
84
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const auth_1 = require("./auth");
4
+ describe('Auth Identity Resolution (Single-Owner External Boundary)', () => {
5
+ const originalEnv = process.env;
6
+ beforeEach(() => {
7
+ jest.resetModules();
8
+ process.env = { ...originalEnv };
9
+ });
10
+ afterAll(() => {
11
+ process.env = originalEnv;
12
+ });
13
+ const mockReq = (token, ip = '192.168.1.50') => ({
14
+ headers: {
15
+ authorization: token ? `Bearer ${token}` : undefined,
16
+ },
17
+ ip,
18
+ socket: { remoteAddress: ip },
19
+ });
20
+ test('authenticates external request when token matches configured AUTH_TOKEN', () => {
21
+ process.env.AUTH_TOKEN = 'secret-auth-key';
22
+ process.env.NODE_ENV = 'production';
23
+ const identity = (0, auth_1.resolveIdentity)(mockReq('secret-auth-key'));
24
+ expect(identity.authenticated).toBe(true);
25
+ expect(identity.source).toBe('external');
26
+ });
27
+ test('authenticates external request when token matches legacy OWNER_TOKEN', () => {
28
+ process.env.OWNER_TOKEN = 'owner-secret';
29
+ process.env.NODE_ENV = 'production';
30
+ const identity = (0, auth_1.resolveIdentity)(mockReq('owner-secret'));
31
+ expect(identity.authenticated).toBe(true);
32
+ expect(identity.source).toBe('external');
33
+ });
34
+ test('rejects external request when token is missing in production with configured token', () => {
35
+ process.env.AUTH_TOKEN = 'secret-auth-key';
36
+ process.env.NODE_ENV = 'production';
37
+ const identity = (0, auth_1.resolveIdentity)(mockReq());
38
+ expect(identity.authenticated).toBe(false);
39
+ });
40
+ test('rejects external request for invalid token in production', () => {
41
+ process.env.AUTH_TOKEN = 'secret-auth-key';
42
+ process.env.NODE_ENV = 'production';
43
+ const identity = (0, auth_1.resolveIdentity)(mockReq('invalid-token'));
44
+ expect(identity.authenticated).toBe(false);
45
+ });
46
+ test('authenticates local loopback request in development mode', () => {
47
+ process.env.NODE_ENV = 'development';
48
+ process.env.DEV_LOCAL_AUTH_ROLE = 'OWNER';
49
+ process.env.AUTH_TOKEN = 'secret-key';
50
+ const devIdentity = (0, auth_1.resolveIdentity)(mockReq(undefined, '127.0.0.1'));
51
+ expect(devIdentity.authenticated).toBe(true);
52
+ expect(devIdentity.source).toBe('local');
53
+ });
54
+ test('requireAuth middleware accepts authenticated request and rejects unauthenticated with 401', () => {
55
+ process.env.AUTH_TOKEN = 'secret-key';
56
+ process.env.NODE_ENV = 'production';
57
+ const nextFn = jest.fn();
58
+ const resUnauthorized = {
59
+ status: jest.fn().mockReturnThis(),
60
+ json: jest.fn().mockReturnThis(),
61
+ };
62
+ // Unauthorized call
63
+ (0, auth_1.requireAuth)(mockReq('wrong-token'), resUnauthorized, nextFn);
64
+ expect(resUnauthorized.status).toHaveBeenCalledWith(401);
65
+ expect(nextFn).not.toHaveBeenCalled();
66
+ // Authorized call
67
+ const resAuthorized = {
68
+ status: jest.fn().mockReturnThis(),
69
+ json: jest.fn().mockReturnThis(),
70
+ };
71
+ (0, auth_1.requireAuth)(mockReq('secret-key'), resAuthorized, nextFn);
72
+ expect(nextFn).toHaveBeenCalled();
73
+ });
74
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,121 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const supertest_1 = __importDefault(require("supertest"));
7
+ const app_1 = require("./app");
8
+ const runtime_1 = require("./runtime");
9
+ describe('T0 B0 & B6 Runtime Proof Suite', () => {
10
+ let mockBrain;
11
+ let mockMemory;
12
+ let mockKnowledge;
13
+ let mockBehavior;
14
+ let runtime;
15
+ let app;
16
+ beforeEach(async () => {
17
+ mockBrain = {
18
+ generatePlan: jest.fn().mockImplementation(async (ctx) => {
19
+ return {
20
+ speech: 'Hello. I am a neutral companion.',
21
+ language: 'en',
22
+ };
23
+ }),
24
+ };
25
+ mockMemory = {
26
+ initialize: jest.fn().mockResolvedValue(undefined),
27
+ searchClaims: jest.fn().mockResolvedValue([]),
28
+ getClaims: jest.fn().mockResolvedValue([]),
29
+ getDirectives: jest.fn().mockResolvedValue([]),
30
+ getPendingClaims: jest.fn().mockResolvedValue([]),
31
+ proposeClaim: jest.fn().mockResolvedValue({}),
32
+ approveClaim: jest.fn().mockResolvedValue(undefined),
33
+ rejectClaim: jest.fn().mockResolvedValue(undefined),
34
+ };
35
+ mockKnowledge = {
36
+ search: jest.fn().mockResolvedValue([]),
37
+ };
38
+ mockBehavior = {
39
+ compile: jest.fn().mockResolvedValue(''),
40
+ };
41
+ const config = {
42
+ name: 'NeutralCompanion',
43
+ brain: { provider: 'openrouter' },
44
+ memory: { provider: 'postgres' },
45
+ knowledge: { provider: 'e-knowledge' },
46
+ behavior: { provider: 'active-self' },
47
+ voice: { provider: 'none' },
48
+ vision: { provider: 'none' },
49
+ body: { provider: 'none' },
50
+ };
51
+ runtime = new runtime_1.SiduriRuntime('companion-a', config, {
52
+ brain: mockBrain,
53
+ memory: mockMemory,
54
+ knowledge: mockKnowledge,
55
+ behavior: mockBehavior,
56
+ });
57
+ await runtime.initialize();
58
+ const runtimes = new Map([['companion-a', runtime]]);
59
+ const created = (0, app_1.createApp)(runtimes);
60
+ app = created.app;
61
+ });
62
+ // B0: Fresh companion is empty (no prior claims, no user relationship, no knowledge search on greeting)
63
+ describe('B0 — Fresh companion is empty', () => {
64
+ test('initial state has empty memory and empty directives', async () => {
65
+ const claims = await runtime.memory?.getClaims();
66
+ const directives = await runtime.memory?.getDirectives();
67
+ expect(claims).toEqual([]);
68
+ expect(directives).toEqual([]);
69
+ });
70
+ test('greeting does not query knowledge or inject prior personal knowledge', async () => {
71
+ const res = await (0, supertest_1.default)(app)
72
+ .post('/chat')
73
+ .send({
74
+ companionId: 'companion-a',
75
+ message: 'Hello.',
76
+ history: [],
77
+ });
78
+ expect(res.status).toBe(200);
79
+ expect(mockKnowledge.search).not.toHaveBeenCalled();
80
+ expect(mockBrain.generatePlan).toHaveBeenCalledWith(expect.objectContaining({
81
+ contextPrompt: '',
82
+ recipient: 'OWNER',
83
+ }));
84
+ });
85
+ });
86
+ // B6: Identity and relationship are learned, not inferred (self identity questions do not query external knowledge)
87
+ describe('B6 — Identity and relationship are learned, not inferred', () => {
88
+ test('asking "Who are you?" suppresses knowledge query and asserts self identity without external search', async () => {
89
+ mockBrain.generatePlan.mockResolvedValueOnce({
90
+ speech: 'I am NeutralCompanion.',
91
+ language: 'en',
92
+ });
93
+ const res = await (0, supertest_1.default)(app)
94
+ .post('/chat')
95
+ .send({
96
+ companionId: 'companion-a',
97
+ message: 'Who are you?',
98
+ history: [],
99
+ });
100
+ expect(res.status).toBe(200);
101
+ // B6 oracle: self identity chat does not query external knowledge
102
+ expect(mockKnowledge.search).not.toHaveBeenCalled();
103
+ expect(mockMemory.searchClaims).toHaveBeenCalled();
104
+ expect(mockBrain.generatePlan).toHaveBeenCalledWith(expect.objectContaining({
105
+ contextPrompt: '',
106
+ }));
107
+ expect(res.body.response.subtitle_en).toBe('I am NeutralCompanion.');
108
+ });
109
+ test('asking "Tell me about yourself" suppresses knowledge query', async () => {
110
+ const res = await (0, supertest_1.default)(app)
111
+ .post('/chat')
112
+ .send({
113
+ companionId: 'companion-a',
114
+ message: 'Tell me about yourself',
115
+ history: [],
116
+ });
117
+ expect(res.status).toBe(200);
118
+ expect(mockKnowledge.search).not.toHaveBeenCalled();
119
+ });
120
+ });
121
+ });
@@ -0,0 +1,18 @@
1
+ import { RequestContext, DiagnosticCode, ContextError } from '@siduri-x/core';
2
+ export interface ContextMapperOptions {
3
+ endpointPolicy?: 'public' | 'private' | 'operator' | 'direct' | string;
4
+ allowAnonymousPublicChat?: boolean;
5
+ }
6
+ export interface MapRequestContextResult {
7
+ accepted: boolean;
8
+ context?: RequestContext;
9
+ diagnostics?: DiagnosticCode[];
10
+ error?: ContextError;
11
+ }
12
+ /**
13
+ * Maps incoming HTTP requests to a canonical RequestContext.
14
+ * In a single-owner, single-machine model:
15
+ * - Security is enforced at the external boundary, not internally between roles.
16
+ * - No internal audience or viewer/operator/owner role hierarchies.
17
+ */
18
+ export declare function mapRequestContext(input: any, options?: ContextMapperOptions): MapRequestContextResult;
@@ -0,0 +1,160 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.mapRequestContext = mapRequestContext;
4
+ const core_1 = require("@siduri-x/core");
5
+ /**
6
+ * Maps incoming HTTP requests to a canonical RequestContext.
7
+ * In a single-owner, single-machine model:
8
+ * - Security is enforced at the external boundary, not internally between roles.
9
+ * - No internal audience or viewer/operator/owner role hierarchies.
10
+ */
11
+ function mapRequestContext(input, options = {}) {
12
+ const diagnostics = [];
13
+ if (!input || typeof input !== 'object') {
14
+ return {
15
+ accepted: false,
16
+ error: {
17
+ code: 'MISSING_CONTEXT',
18
+ fields: ['request'],
19
+ },
20
+ };
21
+ }
22
+ // 1. If incoming input already has a context structure
23
+ if (input.context && typeof input.context === 'object') {
24
+ const rawCtx = input.context;
25
+ const companionId = input.companionId || rawCtx.companionId || input.id;
26
+ const correlationId = rawCtx.conversation?.correlationId || input.correlationId;
27
+ if (!companionId) {
28
+ return {
29
+ accepted: false,
30
+ error: {
31
+ code: 'MISSING_CONTEXT',
32
+ fields: ['companionId'],
33
+ correlationId,
34
+ },
35
+ };
36
+ }
37
+ const actor = rawCtx.actor;
38
+ if (!actor || typeof actor !== 'object') {
39
+ return {
40
+ accepted: false,
41
+ error: {
42
+ code: 'MISSING_CONTEXT',
43
+ fields: ['actor'],
44
+ correlationId,
45
+ },
46
+ };
47
+ }
48
+ // Reject invalid primary_user subject
49
+ if (rawCtx.subject && (rawCtx.subject.subjectId === 'primary_user' || rawCtx.subject === 'primary_user')) {
50
+ return {
51
+ accepted: false,
52
+ error: {
53
+ code: 'FORBIDDEN_CONTEXT',
54
+ message: 'Global primary_user subject is forbidden',
55
+ field: 'subject.subjectId',
56
+ correlationId,
57
+ },
58
+ };
59
+ }
60
+ const constructed = {
61
+ companionId,
62
+ actor: {
63
+ actorId: actor.actorId,
64
+ sessionId: actor.sessionId,
65
+ capabilities: Array.isArray(actor.capabilities) ? actor.capabilities : ['chat'],
66
+ authenticated: actor.authenticated !== undefined ? Boolean(actor.authenticated) : true,
67
+ authorizationRole: actor.authorizationRole,
68
+ ...actor,
69
+ },
70
+ conversation: {
71
+ correlationId,
72
+ channel: rawCtx.conversation?.channel || input.channel || 'direct',
73
+ isLive: rawCtx.conversation?.isLive,
74
+ ...rawCtx.conversation,
75
+ },
76
+ source: input.source || rawCtx.source || 'local',
77
+ subject: rawCtx.subject,
78
+ };
79
+ const validated = (0, core_1.validateRequestContext)(constructed);
80
+ if (!validated.accepted) {
81
+ return validated;
82
+ }
83
+ return {
84
+ accepted: true,
85
+ context: validated.context,
86
+ diagnostics: diagnostics.length > 0 ? diagnostics : undefined,
87
+ };
88
+ }
89
+ // 2. Synthesize clean RequestContext from request envelope
90
+ const companionId = input.companionId || input.id;
91
+ const correlationId = input.correlationId || input.conversation?.correlationId || (input.generateCorrelationId ? `corr-${Date.now()}` : undefined);
92
+ if (!companionId) {
93
+ return {
94
+ accepted: false,
95
+ error: {
96
+ code: 'MISSING_CONTEXT',
97
+ fields: ['companionId'],
98
+ correlationId,
99
+ },
100
+ };
101
+ }
102
+ if (companionId === 'default') {
103
+ diagnostics.push('companion_default_mapped_for_bootstrap');
104
+ }
105
+ if (!correlationId) {
106
+ return {
107
+ accepted: false,
108
+ error: {
109
+ code: 'MISSING_CONTEXT',
110
+ fields: ['conversation.correlationId'],
111
+ },
112
+ };
113
+ }
114
+ if (input.subject === 'primary_user' || input.subjectId === 'primary_user') {
115
+ return {
116
+ accepted: false,
117
+ error: {
118
+ code: 'FORBIDDEN_CONTEXT',
119
+ message: 'Global primary_user subject is forbidden',
120
+ field: 'subject',
121
+ correlationId,
122
+ },
123
+ };
124
+ }
125
+ const actorId = input.actorId || input.actor?.actorId || 'local-user';
126
+ const sessionId = input.sessionId || input.actor?.sessionId || `session-${Date.now()}`;
127
+ if (!input.actorId && !input.actor?.actorId) {
128
+ diagnostics.push('anonymous_session_generated');
129
+ }
130
+ const capabilities = Array.isArray(input.capabilities)
131
+ ? input.capabilities
132
+ : Array.isArray(input.actor?.capabilities)
133
+ ? input.actor.capabilities
134
+ : ['chat', 'system'];
135
+ const mappedContext = {
136
+ companionId,
137
+ actor: {
138
+ actorId,
139
+ sessionId,
140
+ capabilities,
141
+ authenticated: input.authenticated !== undefined ? Boolean(input.authenticated) : true,
142
+ authorizationRole: input.role ? (input.role.toLowerCase() === 'viewer' ? 'viewer' : 'administrator') : undefined,
143
+ },
144
+ conversation: {
145
+ channel: input.channel || input.conversation?.channel || 'direct',
146
+ correlationId,
147
+ },
148
+ source: input.source || 'local',
149
+ subject: input.subject,
150
+ };
151
+ const validated = (0, core_1.validateRequestContext)(mappedContext);
152
+ if (!validated.accepted) {
153
+ return validated;
154
+ }
155
+ return {
156
+ accepted: true,
157
+ context: validated.context,
158
+ diagnostics: diagnostics.length > 0 ? diagnostics : undefined,
159
+ };
160
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,136 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const context_mapper_1 = require("./context-mapper");
4
+ describe('API Request Context Mapper (Single-Owner, Single-Machine)', () => {
5
+ test('Local chat request maps to valid RequestContext with local user defaults', () => {
6
+ const input = {
7
+ companionId: 'companion-a',
8
+ message: 'Hello world',
9
+ correlationId: 'corr-local-1',
10
+ };
11
+ const result = (0, context_mapper_1.mapRequestContext)(input);
12
+ expect(result.accepted).toBe(true);
13
+ expect(result.context?.companionId).toBe('companion-a');
14
+ expect(result.context?.actor.actorId).toBe('local-user');
15
+ expect(result.context?.actor.authenticated).toBe(true);
16
+ expect(result.context?.conversation.correlationId).toBe('corr-local-1');
17
+ expect(result.context?.source).toBe('local');
18
+ expect(result.context?.subject).toBeUndefined();
19
+ });
20
+ test('Accepts structured context envelope', () => {
21
+ const input = {
22
+ companionId: 'companion-a',
23
+ context: {
24
+ actor: {
25
+ actorId: 'user-main',
26
+ sessionId: 'session-main',
27
+ authenticated: true,
28
+ capabilities: ['chat', 'system'],
29
+ },
30
+ conversation: {
31
+ correlationId: 'corr-structured-1',
32
+ },
33
+ },
34
+ message: 'Hello structured context',
35
+ };
36
+ const result = (0, context_mapper_1.mapRequestContext)(input);
37
+ expect(result.accepted).toBe(true);
38
+ expect(result.context?.actor.actorId).toBe('user-main');
39
+ expect(result.context?.conversation.correlationId).toBe('corr-structured-1');
40
+ });
41
+ test('Rejects global primary_user subject', () => {
42
+ const input = {
43
+ companionId: 'companion-a',
44
+ context: {
45
+ actor: {
46
+ actorId: 'user-a',
47
+ sessionId: 'session-a',
48
+ },
49
+ conversation: {
50
+ correlationId: 'corr-primary-user',
51
+ },
52
+ subject: {
53
+ subjectId: 'primary_user',
54
+ kind: 'actor',
55
+ },
56
+ },
57
+ };
58
+ const result = (0, context_mapper_1.mapRequestContext)(input);
59
+ expect(result.accepted).toBe(false);
60
+ expect(result.error?.code).toBe('FORBIDDEN_CONTEXT');
61
+ expect(result.error?.field).toBe('subject.subjectId');
62
+ });
63
+ test('Rejects missing actor on structured context', () => {
64
+ const input = {
65
+ companionId: 'companion-a',
66
+ context: {
67
+ actor: {
68
+ actorId: '',
69
+ sessionId: 'session-a',
70
+ },
71
+ conversation: {
72
+ correlationId: 'corr-teach-no-actor',
73
+ },
74
+ },
75
+ };
76
+ const result = (0, context_mapper_1.mapRequestContext)(input);
77
+ expect(result.accepted).toBe(false);
78
+ expect(result.error?.code).toBe('MISSING_CONTEXT');
79
+ expect(result.error?.fields).toContain('actor.actorId');
80
+ });
81
+ test('Two companion IDs with same actor remain isolated under context mapper', () => {
82
+ const actor = {
83
+ actorId: 'user-a',
84
+ sessionId: 'session-a',
85
+ authenticated: true,
86
+ };
87
+ const conv = {
88
+ correlationId: 'corr-iso-1',
89
+ };
90
+ const reqA = { companionId: 'companion-a', context: { actor, conversation: conv } };
91
+ const reqB = { companionId: 'companion-b', context: { actor, conversation: conv } };
92
+ const resA = (0, context_mapper_1.mapRequestContext)(reqA);
93
+ const resB = (0, context_mapper_1.mapRequestContext)(reqB);
94
+ expect(resA.accepted).toBe(true);
95
+ expect(resB.accepted).toBe(true);
96
+ expect(resA.context?.companionId).toBe('companion-a');
97
+ expect(resB.context?.companionId).toBe('companion-b');
98
+ });
99
+ test('Rejects missing companionId', () => {
100
+ const input = {
101
+ message: 'No companion id',
102
+ correlationId: 'corr-no-comp',
103
+ };
104
+ const result = (0, context_mapper_1.mapRequestContext)(input);
105
+ expect(result.accepted).toBe(false);
106
+ expect(result.error?.code).toBe('MISSING_CONTEXT');
107
+ expect(result.error?.fields).toContain('companionId');
108
+ });
109
+ test('Rejects missing correlation ID when generateCorrelationId is not set', () => {
110
+ const input = {
111
+ companionId: 'companion-a',
112
+ context: {
113
+ actor: {
114
+ actorId: 'user-a',
115
+ sessionId: 'session-a',
116
+ },
117
+ conversation: {
118
+ correlationId: '',
119
+ },
120
+ },
121
+ };
122
+ const result = (0, context_mapper_1.mapRequestContext)(input);
123
+ expect(result.accepted).toBe(false);
124
+ expect(result.error?.code).toBe('MISSING_CONTEXT');
125
+ expect(result.error?.fields).toContain('conversation.correlationId');
126
+ });
127
+ test('Generates correlationId when generateCorrelationId option is true', () => {
128
+ const input = {
129
+ companionId: 'companion-a',
130
+ generateCorrelationId: true,
131
+ };
132
+ const result = (0, context_mapper_1.mapRequestContext)(input);
133
+ expect(result.accepted).toBe(true);
134
+ expect(result.context?.conversation.correlationId).toMatch(/^corr-/);
135
+ });
136
+ });
package/dist/cors.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ import cors from 'cors';
2
+ export declare function getAllowedOrigins(): Set<string>;
3
+ export declare function createCorsOptions(): cors.CorsOptions;