@c15t/backend 2.0.0-rc.5 → 2.0.0-rc.6
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/302.js +473 -0
- package/dist/364.js +1140 -0
- package/dist/583.js +540 -0
- package/dist/cache.cjs +1 -1
- package/dist/cache.js +4 -415
- package/dist/core.cjs +21 -24
- package/dist/core.js +18 -2420
- package/dist/db/adapters/drizzle.cjs +1 -1
- package/dist/db/adapters/drizzle.js +1 -2
- package/dist/db/adapters/kysely.cjs +1 -1
- package/dist/db/adapters/kysely.js +1 -2
- package/dist/db/adapters/mongo.cjs +1 -1
- package/dist/db/adapters/mongo.js +1 -2
- package/dist/db/adapters/prisma.cjs +1 -1
- package/dist/db/adapters/prisma.js +1 -2
- package/dist/db/adapters/typeorm.cjs +1 -1
- package/dist/db/adapters/typeorm.js +1 -2
- package/dist/db/adapters.cjs +1 -1
- package/dist/db/migrator.cjs +1 -1
- package/dist/db/schema.cjs +1 -1
- package/dist/db/schema.js +1 -1
- package/dist/define-config.cjs +1 -1
- package/dist/edge.cjs +1 -1
- package/dist/edge.js +3 -882
- package/dist/router.cjs +17 -18
- package/dist/router.js +1 -2058
- package/dist/types/index.cjs +1 -1
- package/dist-types/cache/gvl-resolver.d.ts +1 -1
- package/dist-types/db/registry/runtime-policy-decision.d.ts +1 -1
- package/dist-types/db/schema/1.0.0/consent.d.ts +1 -1
- package/dist-types/db/schema/2.0.0/audit-log.d.ts +1 -1
- package/dist-types/db/schema/2.0.0/consent-policy.d.ts +1 -1
- package/dist-types/db/schema/2.0.0/consent-purpose.d.ts +1 -1
- package/dist-types/db/schema/2.0.0/consent.d.ts +1 -1
- package/dist-types/db/schema/2.0.0/domain.d.ts +1 -1
- package/dist-types/db/schema/2.0.0/runtime-policy-decision.d.ts +1 -1
- package/dist-types/db/schema/2.0.0/subject.d.ts +1 -1
- package/dist-types/handlers/init/index.d.ts +1 -1
- package/dist-types/handlers/init/policy.d.ts +1 -1
- package/dist-types/handlers/init/resolve-init.d.ts +1 -1
- package/dist-types/handlers/policy/snapshot.d.ts +1 -1
- package/dist-types/policies/defaults.d.ts +1 -1
- package/dist-types/policies/matchers.d.ts +2 -2
- package/dist-types/types/index.d.ts +2 -2
- package/dist-types/version.d.ts +1 -1
- package/docs/guides/policy-packs.md +1 -1
- package/package.json +15 -15
package/dist/router.js
CHANGED
|
@@ -1,2058 +1 @@
|
|
|
1
|
-
|
|
2
|
-
import { Hono } from "hono";
|
|
3
|
-
import { describeRoute, resolver, validator } from "hono-openapi";
|
|
4
|
-
import { HTTPException } from "hono/http-exception";
|
|
5
|
-
import { SpanKind as api_SpanKind, SpanStatusCode as api_SpanStatusCode, context, metrics as api_metrics, trace as api_trace } from "@opentelemetry/api";
|
|
6
|
-
import { SignJWT, errors, jwtVerify } from "jose";
|
|
7
|
-
import { resolvePolicyDecision } from "@c15t/schema/types";
|
|
8
|
-
import { deepMergeTranslations, selectLanguage } from "@c15t/translations";
|
|
9
|
-
import { baseTranslations } from "@c15t/translations/all";
|
|
10
|
-
import { object, optional, string } from "valibot";
|
|
11
|
-
import base_x from "base-x";
|
|
12
|
-
function extractErrorMessage(error) {
|
|
13
|
-
if (error instanceof AggregateError && error.errors?.length > 0) {
|
|
14
|
-
const inner = error.errors.map((e)=>e instanceof Error ? e.message : String(e)).join('; ');
|
|
15
|
-
return `AggregateError: ${inner}`;
|
|
16
|
-
}
|
|
17
|
-
if (error instanceof Error) return error.message || error.name;
|
|
18
|
-
return String(error);
|
|
19
|
-
}
|
|
20
|
-
const version_version = '2.0.0-rc.5';
|
|
21
|
-
let cachedConfig = null;
|
|
22
|
-
let cachedDefaultAttributes = {};
|
|
23
|
-
function create_telemetry_options_isTelemetryEnabled(options) {
|
|
24
|
-
if (options) return options.telemetry?.enabled === true;
|
|
25
|
-
return cachedConfig?.enabled === true;
|
|
26
|
-
}
|
|
27
|
-
const create_telemetry_options_getTracer = (options)=>{
|
|
28
|
-
if (!create_telemetry_options_isTelemetryEnabled(options)) return api_trace.getTracer('c15t-noop');
|
|
29
|
-
const tracer = options?.telemetry?.tracer ?? cachedConfig?.tracer;
|
|
30
|
-
if (tracer) return tracer;
|
|
31
|
-
return api_trace.getTracer(options?.appName ?? 'c15t');
|
|
32
|
-
};
|
|
33
|
-
const getMeter = (options)=>{
|
|
34
|
-
if (!create_telemetry_options_isTelemetryEnabled(options)) return api_metrics.getMeter('c15t-noop');
|
|
35
|
-
const meter = options?.telemetry?.meter ?? cachedConfig?.meter;
|
|
36
|
-
if (meter) return meter;
|
|
37
|
-
return api_metrics.getMeter(options?.appName ?? 'c15t');
|
|
38
|
-
};
|
|
39
|
-
function getDefaultAttributes() {
|
|
40
|
-
return cachedDefaultAttributes;
|
|
41
|
-
}
|
|
42
|
-
const handleSpanError = (span, error)=>{
|
|
43
|
-
span.setStatus({
|
|
44
|
-
code: api_SpanStatusCode.ERROR,
|
|
45
|
-
message: extractErrorMessage(error)
|
|
46
|
-
});
|
|
47
|
-
if (error instanceof Error) span.setAttribute('error.type', error.name);
|
|
48
|
-
};
|
|
49
|
-
const withSpanContext = async (span, operation)=>context["with"](api_trace.setSpan(context.active(), span), operation);
|
|
50
|
-
function sanitizeAttributes(attrs) {
|
|
51
|
-
return Object.fromEntries(Object.entries(attrs).filter(([_, v])=>null != v));
|
|
52
|
-
}
|
|
53
|
-
function createMetrics(meter) {
|
|
54
|
-
const consentCreated = meter.createCounter('c15t.consent.created', {
|
|
55
|
-
description: 'Number of consent submissions',
|
|
56
|
-
unit: '1'
|
|
57
|
-
});
|
|
58
|
-
const consentAccepted = meter.createCounter('c15t.consent.accepted', {
|
|
59
|
-
description: 'Number of consents accepted',
|
|
60
|
-
unit: '1'
|
|
61
|
-
});
|
|
62
|
-
const consentRejected = meter.createCounter('c15t.consent.rejected', {
|
|
63
|
-
description: 'Number of consents rejected',
|
|
64
|
-
unit: '1'
|
|
65
|
-
});
|
|
66
|
-
const subjectCreated = meter.createCounter('c15t.subject.created', {
|
|
67
|
-
description: 'Number of new subjects created',
|
|
68
|
-
unit: '1'
|
|
69
|
-
});
|
|
70
|
-
const subjectLinked = meter.createCounter('c15t.subject.linked', {
|
|
71
|
-
description: 'Number of subjects linked to external ID',
|
|
72
|
-
unit: '1'
|
|
73
|
-
});
|
|
74
|
-
const consentCheckCount = meter.createCounter('c15t.consent_check.count', {
|
|
75
|
-
description: 'Number of cross-device consent checks',
|
|
76
|
-
unit: '1'
|
|
77
|
-
});
|
|
78
|
-
const initCount = meter.createCounter('c15t.init.count', {
|
|
79
|
-
description: 'Number of init endpoint calls',
|
|
80
|
-
unit: '1'
|
|
81
|
-
});
|
|
82
|
-
const httpRequestDuration = meter.createHistogram('c15t.http.request.duration', {
|
|
83
|
-
description: 'HTTP request latency',
|
|
84
|
-
unit: 'ms'
|
|
85
|
-
});
|
|
86
|
-
const httpRequestCount = meter.createCounter('c15t.http.request.count', {
|
|
87
|
-
description: 'Number of HTTP requests',
|
|
88
|
-
unit: '1'
|
|
89
|
-
});
|
|
90
|
-
const httpErrorCount = meter.createCounter('c15t.http.error.count', {
|
|
91
|
-
description: 'Number of HTTP errors',
|
|
92
|
-
unit: '1'
|
|
93
|
-
});
|
|
94
|
-
const dbQueryDuration = meter.createHistogram('c15t.db.query.duration', {
|
|
95
|
-
description: 'Database query latency',
|
|
96
|
-
unit: 'ms'
|
|
97
|
-
});
|
|
98
|
-
const dbQueryCount = meter.createCounter('c15t.db.query.count', {
|
|
99
|
-
description: 'Number of database queries',
|
|
100
|
-
unit: '1'
|
|
101
|
-
});
|
|
102
|
-
const dbErrorCount = meter.createCounter('c15t.db.error.count', {
|
|
103
|
-
description: 'Number of database errors',
|
|
104
|
-
unit: '1'
|
|
105
|
-
});
|
|
106
|
-
const cacheHit = meter.createCounter('c15t.cache.hit', {
|
|
107
|
-
description: 'Number of cache hits',
|
|
108
|
-
unit: '1'
|
|
109
|
-
});
|
|
110
|
-
const cacheMiss = meter.createCounter('c15t.cache.miss', {
|
|
111
|
-
description: 'Number of cache misses',
|
|
112
|
-
unit: '1'
|
|
113
|
-
});
|
|
114
|
-
const cacheLatency = meter.createHistogram('c15t.cache.latency', {
|
|
115
|
-
description: 'Cache operation latency',
|
|
116
|
-
unit: 'ms'
|
|
117
|
-
});
|
|
118
|
-
const gvlFetchDuration = meter.createHistogram('c15t.gvl.fetch.duration', {
|
|
119
|
-
description: 'GVL fetch latency',
|
|
120
|
-
unit: 'ms'
|
|
121
|
-
});
|
|
122
|
-
const gvlFetchCount = meter.createCounter('c15t.gvl.fetch.count', {
|
|
123
|
-
description: 'Number of GVL fetches',
|
|
124
|
-
unit: '1'
|
|
125
|
-
});
|
|
126
|
-
const gvlFetchError = meter.createCounter('c15t.gvl.fetch.error', {
|
|
127
|
-
description: 'Number of GVL fetch errors',
|
|
128
|
-
unit: '1'
|
|
129
|
-
});
|
|
130
|
-
return {
|
|
131
|
-
consentCreated,
|
|
132
|
-
consentAccepted,
|
|
133
|
-
consentRejected,
|
|
134
|
-
subjectCreated,
|
|
135
|
-
subjectLinked,
|
|
136
|
-
consentCheckCount,
|
|
137
|
-
initCount,
|
|
138
|
-
httpRequestDuration,
|
|
139
|
-
httpRequestCount,
|
|
140
|
-
httpErrorCount,
|
|
141
|
-
dbQueryDuration,
|
|
142
|
-
dbQueryCount,
|
|
143
|
-
dbErrorCount,
|
|
144
|
-
cacheHit,
|
|
145
|
-
cacheMiss,
|
|
146
|
-
cacheLatency,
|
|
147
|
-
gvlFetchDuration,
|
|
148
|
-
gvlFetchCount,
|
|
149
|
-
gvlFetchError,
|
|
150
|
-
recordConsentCreated (attributes) {
|
|
151
|
-
consentCreated.add(1, sanitizeAttributes(attributes));
|
|
152
|
-
},
|
|
153
|
-
recordConsentAccepted (attributes) {
|
|
154
|
-
consentAccepted.add(1, sanitizeAttributes(attributes));
|
|
155
|
-
},
|
|
156
|
-
recordConsentRejected (attributes) {
|
|
157
|
-
consentRejected.add(1, sanitizeAttributes(attributes));
|
|
158
|
-
},
|
|
159
|
-
recordSubjectCreated (attributes) {
|
|
160
|
-
subjectCreated.add(1, sanitizeAttributes(attributes));
|
|
161
|
-
},
|
|
162
|
-
recordSubjectLinked (identityProvider) {
|
|
163
|
-
subjectLinked.add(1, {
|
|
164
|
-
identityProvider: identityProvider || 'unknown'
|
|
165
|
-
});
|
|
166
|
-
},
|
|
167
|
-
recordConsentCheck (type, found) {
|
|
168
|
-
consentCheckCount.add(1, {
|
|
169
|
-
type,
|
|
170
|
-
found: String(found)
|
|
171
|
-
});
|
|
172
|
-
},
|
|
173
|
-
recordInit (attributes) {
|
|
174
|
-
initCount.add(1, sanitizeAttributes(attributes));
|
|
175
|
-
},
|
|
176
|
-
recordHttpRequest (attributes, durationMs) {
|
|
177
|
-
const attrs = sanitizeAttributes(attributes);
|
|
178
|
-
httpRequestCount.add(1, attrs);
|
|
179
|
-
httpRequestDuration.record(durationMs, attrs);
|
|
180
|
-
if (attributes.status >= 400) httpErrorCount.add(1, attrs);
|
|
181
|
-
},
|
|
182
|
-
recordDbQuery (attributes, durationMs) {
|
|
183
|
-
const attrs = sanitizeAttributes(attributes);
|
|
184
|
-
dbQueryCount.add(1, attrs);
|
|
185
|
-
dbQueryDuration.record(durationMs, attrs);
|
|
186
|
-
},
|
|
187
|
-
recordDbError (attributes) {
|
|
188
|
-
dbErrorCount.add(1, sanitizeAttributes(attributes));
|
|
189
|
-
},
|
|
190
|
-
recordCacheHit (layer) {
|
|
191
|
-
cacheHit.add(1, {
|
|
192
|
-
layer
|
|
193
|
-
});
|
|
194
|
-
},
|
|
195
|
-
recordCacheMiss (layer) {
|
|
196
|
-
cacheMiss.add(1, {
|
|
197
|
-
layer
|
|
198
|
-
});
|
|
199
|
-
},
|
|
200
|
-
recordCacheLatency (attributes, durationMs) {
|
|
201
|
-
cacheLatency.record(durationMs, sanitizeAttributes(attributes));
|
|
202
|
-
},
|
|
203
|
-
recordGvlFetch (attributes, durationMs) {
|
|
204
|
-
const attrs = sanitizeAttributes(attributes);
|
|
205
|
-
gvlFetchCount.add(1, attrs);
|
|
206
|
-
gvlFetchDuration.record(durationMs, attrs);
|
|
207
|
-
},
|
|
208
|
-
recordGvlError (attributes) {
|
|
209
|
-
gvlFetchError.add(1, sanitizeAttributes(attributes));
|
|
210
|
-
}
|
|
211
|
-
};
|
|
212
|
-
}
|
|
213
|
-
let metricsInstance = null;
|
|
214
|
-
function getMetrics(options) {
|
|
215
|
-
if (metricsInstance) return metricsInstance;
|
|
216
|
-
if (!create_telemetry_options_isTelemetryEnabled(options)) return null;
|
|
217
|
-
metricsInstance = createMetrics(getMeter(options));
|
|
218
|
-
return metricsInstance;
|
|
219
|
-
}
|
|
220
|
-
function parsePurposeIds(purposeIds) {
|
|
221
|
-
if (null == purposeIds) return [];
|
|
222
|
-
const ids = 'object' == typeof purposeIds && 'json' in purposeIds ? purposeIds.json : purposeIds;
|
|
223
|
-
return Array.isArray(ids) ? ids : [];
|
|
224
|
-
}
|
|
225
|
-
async function batchLoadPolicies(policyIds, ctx) {
|
|
226
|
-
const { db, registry } = ctx;
|
|
227
|
-
const policyMap = new Map();
|
|
228
|
-
if (policyIds.size > 0) {
|
|
229
|
-
const policies = await db.findMany('consentPolicy', {
|
|
230
|
-
where: (b)=>b('id', 'in', [
|
|
231
|
-
...policyIds
|
|
232
|
-
])
|
|
233
|
-
});
|
|
234
|
-
for (const p of policies)policyMap.set(p.id, p);
|
|
235
|
-
}
|
|
236
|
-
const uniqueTypes = new Set();
|
|
237
|
-
for (const p of policyMap.values())uniqueTypes.add(p.type);
|
|
238
|
-
const latestPolicyByType = new Map();
|
|
239
|
-
for (const type of uniqueTypes){
|
|
240
|
-
const latest = await registry.findOrCreatePolicy(type);
|
|
241
|
-
if (latest) latestPolicyByType.set(type, latest.id);
|
|
242
|
-
}
|
|
243
|
-
return {
|
|
244
|
-
policyMap,
|
|
245
|
-
latestPolicyByType
|
|
246
|
-
};
|
|
247
|
-
}
|
|
248
|
-
async function enrichConsents(consents, ctx) {
|
|
249
|
-
if (0 === consents.length) return [];
|
|
250
|
-
const policyIds = new Set();
|
|
251
|
-
for (const c of consents)if (c.policyId) policyIds.add(c.policyId);
|
|
252
|
-
const { policyMap, latestPolicyByType } = await batchLoadPolicies(policyIds, ctx);
|
|
253
|
-
const allPurposeIds = new Set();
|
|
254
|
-
for (const c of consents)for (const id of parsePurposeIds(c.purposeIds))allPurposeIds.add(id);
|
|
255
|
-
const purposeMap = new Map();
|
|
256
|
-
if (allPurposeIds.size > 0) {
|
|
257
|
-
const purposes = await ctx.db.findMany('consentPurpose', {
|
|
258
|
-
where: (b)=>b('id', 'in', [
|
|
259
|
-
...allPurposeIds
|
|
260
|
-
])
|
|
261
|
-
});
|
|
262
|
-
for (const p of purposes)purposeMap.set(p.id, p.code);
|
|
263
|
-
}
|
|
264
|
-
return consents.map((consent)=>{
|
|
265
|
-
let policyType = 'unknown';
|
|
266
|
-
let isLatestPolicy = false;
|
|
267
|
-
if (consent.policyId) {
|
|
268
|
-
const policy = policyMap.get(consent.policyId);
|
|
269
|
-
if (policy) {
|
|
270
|
-
policyType = policy.type;
|
|
271
|
-
isLatestPolicy = latestPolicyByType.get(policyType) === consent.policyId;
|
|
272
|
-
}
|
|
273
|
-
}
|
|
274
|
-
let preferences;
|
|
275
|
-
const ids = parsePurposeIds(consent.purposeIds);
|
|
276
|
-
if (ids.length > 0) {
|
|
277
|
-
preferences = {};
|
|
278
|
-
for (const purposeId of ids){
|
|
279
|
-
const code = purposeMap.get(purposeId);
|
|
280
|
-
if (code) preferences[code] = true;
|
|
281
|
-
}
|
|
282
|
-
}
|
|
283
|
-
return {
|
|
284
|
-
id: consent.id,
|
|
285
|
-
type: policyType,
|
|
286
|
-
policyId: consent.policyId ?? void 0,
|
|
287
|
-
isLatestPolicy,
|
|
288
|
-
preferences,
|
|
289
|
-
givenAt: consent.givenAt
|
|
290
|
-
};
|
|
291
|
-
});
|
|
292
|
-
}
|
|
293
|
-
async function resolveConsentPolicies(consents, ctx) {
|
|
294
|
-
if (0 === consents.length) return [];
|
|
295
|
-
const policyIds = new Set();
|
|
296
|
-
for (const c of consents)if (c.policyId) policyIds.add(c.policyId);
|
|
297
|
-
const { policyMap, latestPolicyByType } = await batchLoadPolicies(policyIds, ctx);
|
|
298
|
-
return consents.map((consent)=>{
|
|
299
|
-
let policyType = 'unknown';
|
|
300
|
-
let isLatestPolicy = false;
|
|
301
|
-
if (consent.policyId) {
|
|
302
|
-
const policy = policyMap.get(consent.policyId);
|
|
303
|
-
if (policy) {
|
|
304
|
-
policyType = policy.type;
|
|
305
|
-
isLatestPolicy = latestPolicyByType.get(policyType) === consent.policyId;
|
|
306
|
-
}
|
|
307
|
-
}
|
|
308
|
-
return {
|
|
309
|
-
consentId: consent.id,
|
|
310
|
-
policyType,
|
|
311
|
-
policyId: consent.policyId ?? void 0,
|
|
312
|
-
isLatestPolicy
|
|
313
|
-
};
|
|
314
|
-
});
|
|
315
|
-
}
|
|
316
|
-
const checkConsentHandler = async (c)=>{
|
|
317
|
-
const ctx = c.get('c15tContext');
|
|
318
|
-
const logger = ctx.logger;
|
|
319
|
-
logger.info('Handling GET /consents/check request');
|
|
320
|
-
const { db, registry } = ctx;
|
|
321
|
-
const externalId = c.req.query('externalId');
|
|
322
|
-
const type = c.req.query('type');
|
|
323
|
-
if (!externalId) throw new HTTPException(422, {
|
|
324
|
-
message: 'externalId query parameter is required',
|
|
325
|
-
cause: {
|
|
326
|
-
code: 'EXTERNAL_ID_REQUIRED'
|
|
327
|
-
}
|
|
328
|
-
});
|
|
329
|
-
if (!type) throw new HTTPException(422, {
|
|
330
|
-
message: 'type query parameter is required',
|
|
331
|
-
cause: {
|
|
332
|
-
code: 'TYPE_REQUIRED'
|
|
333
|
-
}
|
|
334
|
-
});
|
|
335
|
-
const types = type.split(',').map((t)=>t.trim());
|
|
336
|
-
logger.debug('Request parameters', {
|
|
337
|
-
externalId,
|
|
338
|
-
types
|
|
339
|
-
});
|
|
340
|
-
try {
|
|
341
|
-
const subjects = await db.findMany('subject', {
|
|
342
|
-
where: (b)=>b('externalId', '=', externalId)
|
|
343
|
-
});
|
|
344
|
-
const subjectIds = subjects.map((s)=>s.id);
|
|
345
|
-
const results = {};
|
|
346
|
-
for (const t of types)results[t] = {
|
|
347
|
-
hasConsent: false,
|
|
348
|
-
isLatestPolicy: false
|
|
349
|
-
};
|
|
350
|
-
if (0 === subjectIds.length) {
|
|
351
|
-
logger.debug('No subjects found for externalId', {
|
|
352
|
-
externalId
|
|
353
|
-
});
|
|
354
|
-
return c.json({
|
|
355
|
-
results
|
|
356
|
-
});
|
|
357
|
-
}
|
|
358
|
-
const allConsents = await Promise.all(subjectIds.map((subjectId)=>db.findMany('consent', {
|
|
359
|
-
where: (b)=>b('subjectId', '=', subjectId)
|
|
360
|
-
})));
|
|
361
|
-
const consents = allConsents.flat();
|
|
362
|
-
const policyInfos = await resolveConsentPolicies(consents, {
|
|
363
|
-
db,
|
|
364
|
-
registry
|
|
365
|
-
});
|
|
366
|
-
for (const info of policyInfos){
|
|
367
|
-
if (!types.includes(info.policyType)) continue;
|
|
368
|
-
const entry = results[info.policyType];
|
|
369
|
-
if (entry) {
|
|
370
|
-
entry.hasConsent = true;
|
|
371
|
-
if (info.isLatestPolicy) entry.isLatestPolicy = true;
|
|
372
|
-
}
|
|
373
|
-
}
|
|
374
|
-
logger.debug('Consent check results', {
|
|
375
|
-
externalId,
|
|
376
|
-
results
|
|
377
|
-
});
|
|
378
|
-
const metrics = getMetrics();
|
|
379
|
-
if (metrics) for (const [type, result] of Object.entries(results))metrics.recordConsentCheck(type, result.hasConsent);
|
|
380
|
-
return c.json({
|
|
381
|
-
results
|
|
382
|
-
});
|
|
383
|
-
} catch (error) {
|
|
384
|
-
logger.error('Error in GET /consents/check handler', {
|
|
385
|
-
error: extractErrorMessage(error),
|
|
386
|
-
errorType: error instanceof Error ? error.constructor.name : typeof error
|
|
387
|
-
});
|
|
388
|
-
if (error instanceof HTTPException) throw error;
|
|
389
|
-
throw new HTTPException(500, {
|
|
390
|
-
message: 'Internal server error',
|
|
391
|
-
cause: {
|
|
392
|
-
code: 'INTERNAL_SERVER_ERROR'
|
|
393
|
-
}
|
|
394
|
-
});
|
|
395
|
-
}
|
|
396
|
-
};
|
|
397
|
-
const createConsentRoutes = ()=>{
|
|
398
|
-
const app = new Hono();
|
|
399
|
-
app.get('/check', describeRoute({
|
|
400
|
-
summary: 'Check consent by external user ID',
|
|
401
|
-
description: `Pre-banner cross-device consent check. Use to avoid showing the banner when the user has already consented on another device.
|
|
402
|
-
|
|
403
|
-
**Query parameters:**
|
|
404
|
-
- \`externalId\` – External user ID to check
|
|
405
|
-
- \`type\` – Consent type(s) to check (comma-separated)`,
|
|
406
|
-
tags: [
|
|
407
|
-
'Consent'
|
|
408
|
-
],
|
|
409
|
-
responses: {
|
|
410
|
-
200: {
|
|
411
|
-
description: 'Consent check result per requested type(s)',
|
|
412
|
-
content: {
|
|
413
|
-
'application/json': {
|
|
414
|
-
schema: resolver(checkConsentOutputSchema)
|
|
415
|
-
}
|
|
416
|
-
}
|
|
417
|
-
},
|
|
418
|
-
422: {
|
|
419
|
-
description: 'Invalid or missing query parameters'
|
|
420
|
-
}
|
|
421
|
-
}
|
|
422
|
-
}), validator('query', checkConsentQuerySchema), checkConsentHandler);
|
|
423
|
-
return app;
|
|
424
|
-
};
|
|
425
|
-
async function executeWithSpan(span, operation) {
|
|
426
|
-
try {
|
|
427
|
-
const result = await withSpanContext(span, operation);
|
|
428
|
-
span.setStatus({
|
|
429
|
-
code: api_SpanStatusCode.OK
|
|
430
|
-
});
|
|
431
|
-
return result;
|
|
432
|
-
} catch (error) {
|
|
433
|
-
handleSpanError(span, error);
|
|
434
|
-
throw error;
|
|
435
|
-
} finally{
|
|
436
|
-
span.end();
|
|
437
|
-
}
|
|
438
|
-
}
|
|
439
|
-
function resolveDefaultAttributes(options) {
|
|
440
|
-
return options?.telemetry?.defaultAttributes || getDefaultAttributes();
|
|
441
|
-
}
|
|
442
|
-
async function withExternalSpan(attributes, operation, options) {
|
|
443
|
-
if (!create_telemetry_options_isTelemetryEnabled(options)) return operation();
|
|
444
|
-
const tracer = create_telemetry_options_getTracer(options);
|
|
445
|
-
const url = new URL(attributes.url);
|
|
446
|
-
const spanName = `HTTP ${attributes.method} ${url.hostname}`;
|
|
447
|
-
const span = tracer.startSpan(spanName, {
|
|
448
|
-
kind: api_SpanKind.CLIENT,
|
|
449
|
-
attributes: {
|
|
450
|
-
'http.method': attributes.method,
|
|
451
|
-
'http.url': `${url.origin}${url.pathname}`,
|
|
452
|
-
'http.host': url.hostname,
|
|
453
|
-
...resolveDefaultAttributes(options),
|
|
454
|
-
...Object.fromEntries(Object.entries(attributes).filter(([key])=>![
|
|
455
|
-
'url',
|
|
456
|
-
'method'
|
|
457
|
-
].includes(key)))
|
|
458
|
-
}
|
|
459
|
-
});
|
|
460
|
-
return executeWithSpan(span, operation);
|
|
461
|
-
}
|
|
462
|
-
async function withCacheSpan(operation, layer, fn, options) {
|
|
463
|
-
if (!create_telemetry_options_isTelemetryEnabled(options)) return fn();
|
|
464
|
-
const tracer = create_telemetry_options_getTracer(options);
|
|
465
|
-
const spanName = `cache.${layer}.${operation}`;
|
|
466
|
-
const span = tracer.startSpan(spanName, {
|
|
467
|
-
kind: api_SpanKind.CLIENT,
|
|
468
|
-
attributes: {
|
|
469
|
-
'cache.operation': operation,
|
|
470
|
-
'cache.layer': layer,
|
|
471
|
-
...resolveDefaultAttributes(options)
|
|
472
|
-
}
|
|
473
|
-
});
|
|
474
|
-
return executeWithSpan(span, fn);
|
|
475
|
-
}
|
|
476
|
-
const GVL_TTL_MS = 259200000;
|
|
477
|
-
const memory_memoryCache = new Map();
|
|
478
|
-
function createMemoryCacheAdapter() {
|
|
479
|
-
return {
|
|
480
|
-
async get (key) {
|
|
481
|
-
const entry = memory_memoryCache.get(key);
|
|
482
|
-
if (!entry) return null;
|
|
483
|
-
if (Date.now() > entry.expiresAt) {
|
|
484
|
-
memory_memoryCache.delete(key);
|
|
485
|
-
return null;
|
|
486
|
-
}
|
|
487
|
-
return entry.value;
|
|
488
|
-
},
|
|
489
|
-
async set (key, value, ttlMs = 300000) {
|
|
490
|
-
memory_memoryCache.set(key, {
|
|
491
|
-
value,
|
|
492
|
-
expiresAt: Date.now() + ttlMs
|
|
493
|
-
});
|
|
494
|
-
},
|
|
495
|
-
async delete (key) {
|
|
496
|
-
memory_memoryCache.delete(key);
|
|
497
|
-
},
|
|
498
|
-
async has (key) {
|
|
499
|
-
const entry = memory_memoryCache.get(key);
|
|
500
|
-
if (!entry) return false;
|
|
501
|
-
if (Date.now() > entry.expiresAt) {
|
|
502
|
-
memory_memoryCache.delete(key);
|
|
503
|
-
return false;
|
|
504
|
-
}
|
|
505
|
-
return true;
|
|
506
|
-
}
|
|
507
|
-
};
|
|
508
|
-
}
|
|
509
|
-
function createGVLCacheKey(appName, language, vendorIds) {
|
|
510
|
-
const sortedIds = vendorIds ? [
|
|
511
|
-
...vendorIds
|
|
512
|
-
].sort((a, b)=>a - b).join(',') : 'all';
|
|
513
|
-
return `${appName}:gvl:${language}:${sortedIds}`;
|
|
514
|
-
}
|
|
515
|
-
const GVL_ENDPOINT = 'https://gvl.consent.io';
|
|
516
|
-
const inflightRequests = new Map();
|
|
517
|
-
async function fetchGVLWithLanguage(language, vendorIds, endpoint = GVL_ENDPOINT) {
|
|
518
|
-
const sortedVendorIds = vendorIds ? [
|
|
519
|
-
...vendorIds
|
|
520
|
-
].sort((a, b)=>a - b) : [];
|
|
521
|
-
const dedupeKey = `${endpoint}|${language}|${sortedVendorIds.join(',')}`;
|
|
522
|
-
const existingRequest = inflightRequests.get(dedupeKey);
|
|
523
|
-
if (existingRequest) return existingRequest;
|
|
524
|
-
const url = new URL(endpoint);
|
|
525
|
-
if (sortedVendorIds.length > 0) url.searchParams.set('vendorIds', sortedVendorIds.join(','));
|
|
526
|
-
const promise = (async ()=>{
|
|
527
|
-
const fetchStart = Date.now();
|
|
528
|
-
try {
|
|
529
|
-
const gvl = await withExternalSpan({
|
|
530
|
-
url: url.toString(),
|
|
531
|
-
method: 'GET'
|
|
532
|
-
}, async ()=>{
|
|
533
|
-
const response = await fetch(url.toString(), {
|
|
534
|
-
headers: {
|
|
535
|
-
'Accept-Language': language
|
|
536
|
-
}
|
|
537
|
-
});
|
|
538
|
-
if (204 === response.status) return null;
|
|
539
|
-
if (!response.ok) throw new Error(`Failed to fetch GVL: ${response.status} ${response.statusText}`);
|
|
540
|
-
const text = await response.text();
|
|
541
|
-
const trimmed = text.trim().replace(/^\uFEFF/, '');
|
|
542
|
-
let parsed;
|
|
543
|
-
try {
|
|
544
|
-
parsed = JSON.parse(trimmed);
|
|
545
|
-
} catch {
|
|
546
|
-
let depth = 0;
|
|
547
|
-
let end = -1;
|
|
548
|
-
const start = trimmed.indexOf('{');
|
|
549
|
-
if (start >= 0) for(let i = start; i < trimmed.length; i++){
|
|
550
|
-
const c = trimmed[i];
|
|
551
|
-
if ('{' === c) depth++;
|
|
552
|
-
else if ('}' === c) {
|
|
553
|
-
depth--;
|
|
554
|
-
if (0 === depth) {
|
|
555
|
-
end = i + 1;
|
|
556
|
-
break;
|
|
557
|
-
}
|
|
558
|
-
}
|
|
559
|
-
}
|
|
560
|
-
if (end > 0) parsed = JSON.parse(trimmed.slice(0, end));
|
|
561
|
-
else throw new SyntaxError('Invalid GVL response: not valid JSON');
|
|
562
|
-
}
|
|
563
|
-
if (!parsed.vendorListVersion || !parsed.purposes || !parsed.vendors) throw new Error('Invalid GVL response: missing required fields');
|
|
564
|
-
return parsed;
|
|
565
|
-
});
|
|
566
|
-
getMetrics()?.recordGvlFetch({
|
|
567
|
-
language,
|
|
568
|
-
source: 'fetch',
|
|
569
|
-
status: 200
|
|
570
|
-
}, Date.now() - fetchStart);
|
|
571
|
-
return gvl;
|
|
572
|
-
} catch (error) {
|
|
573
|
-
getMetrics()?.recordGvlError({
|
|
574
|
-
language,
|
|
575
|
-
errorType: error instanceof Error ? error.name : 'UnknownError'
|
|
576
|
-
});
|
|
577
|
-
throw error;
|
|
578
|
-
} finally{
|
|
579
|
-
inflightRequests.delete(dedupeKey);
|
|
580
|
-
}
|
|
581
|
-
})();
|
|
582
|
-
inflightRequests.set(dedupeKey, promise);
|
|
583
|
-
return promise;
|
|
584
|
-
}
|
|
585
|
-
function createGVLResolver(options) {
|
|
586
|
-
const { appName, bundled, cacheAdapter, vendorIds, endpoint } = options;
|
|
587
|
-
const memoryCache = createMemoryCacheAdapter();
|
|
588
|
-
return {
|
|
589
|
-
async get (language) {
|
|
590
|
-
const cacheKey = createGVLCacheKey(appName, language, vendorIds);
|
|
591
|
-
if (bundled?.[language]) return bundled[language];
|
|
592
|
-
const memoryHit = await withCacheSpan('get', 'memory', ()=>memoryCache.get(cacheKey));
|
|
593
|
-
if (memoryHit) {
|
|
594
|
-
getMetrics()?.recordCacheHit('memory');
|
|
595
|
-
return memoryHit;
|
|
596
|
-
}
|
|
597
|
-
getMetrics()?.recordCacheMiss('memory');
|
|
598
|
-
if (cacheAdapter) {
|
|
599
|
-
const externalHit = await withCacheSpan('get', 'external', ()=>cacheAdapter.get(cacheKey));
|
|
600
|
-
if (externalHit) {
|
|
601
|
-
getMetrics()?.recordCacheHit('external');
|
|
602
|
-
await withCacheSpan('set', 'memory', ()=>memoryCache.set(cacheKey, externalHit, 300000));
|
|
603
|
-
return externalHit;
|
|
604
|
-
}
|
|
605
|
-
getMetrics()?.recordCacheMiss('external');
|
|
606
|
-
}
|
|
607
|
-
const gvl = await fetchGVLWithLanguage(language, vendorIds, endpoint);
|
|
608
|
-
if (gvl) {
|
|
609
|
-
await withCacheSpan('set', 'memory', ()=>memoryCache.set(cacheKey, gvl, 300000));
|
|
610
|
-
if (cacheAdapter) await withCacheSpan('set', 'external', ()=>cacheAdapter.set(cacheKey, gvl, GVL_TTL_MS));
|
|
611
|
-
}
|
|
612
|
-
return gvl;
|
|
613
|
-
}
|
|
614
|
-
};
|
|
615
|
-
}
|
|
616
|
-
const POLICY_SNAPSHOT_JWT_HEADER = {
|
|
617
|
-
alg: 'HS256',
|
|
618
|
-
typ: 'JWT'
|
|
619
|
-
};
|
|
620
|
-
const DEFAULT_POLICY_SNAPSHOT_ISSUER = 'c15t';
|
|
621
|
-
const DEFAULT_POLICY_SNAPSHOT_AUDIENCE = 'c15t-policy-snapshot';
|
|
622
|
-
function resolveSnapshotIssuer(options) {
|
|
623
|
-
return options?.issuer?.trim() || DEFAULT_POLICY_SNAPSHOT_ISSUER;
|
|
624
|
-
}
|
|
625
|
-
function resolveSnapshotAudience(params) {
|
|
626
|
-
const configuredAudience = params.options?.audience?.trim();
|
|
627
|
-
if (configuredAudience) return configuredAudience;
|
|
628
|
-
return params.tenantId ? `${DEFAULT_POLICY_SNAPSHOT_AUDIENCE}:${params.tenantId}` : DEFAULT_POLICY_SNAPSHOT_AUDIENCE;
|
|
629
|
-
}
|
|
630
|
-
function getSigningKey(secret) {
|
|
631
|
-
return new TextEncoder().encode(secret);
|
|
632
|
-
}
|
|
633
|
-
function isPolicySnapshotPayload(payload) {
|
|
634
|
-
return 'string' == typeof payload.policyId && 'string' == typeof payload.fingerprint && 'string' == typeof payload.matchedBy && 'string' == typeof payload.jurisdiction && 'string' == typeof payload.model && 'string' == typeof payload.iss && 'string' == typeof payload.aud && 'string' == typeof payload.sub && 'number' == typeof payload.iat && 'number' == typeof payload.exp;
|
|
635
|
-
}
|
|
636
|
-
async function createPolicySnapshotToken(params) {
|
|
637
|
-
const { options } = params;
|
|
638
|
-
if (!options?.signingKey) return;
|
|
639
|
-
const iat = Math.floor(Date.now() / 1000);
|
|
640
|
-
const ttlSeconds = options.ttlSeconds ?? 1800;
|
|
641
|
-
const exp = iat + ttlSeconds;
|
|
642
|
-
const iss = resolveSnapshotIssuer(options);
|
|
643
|
-
const aud = resolveSnapshotAudience({
|
|
644
|
-
options,
|
|
645
|
-
tenantId: params.tenantId
|
|
646
|
-
});
|
|
647
|
-
const payload = {
|
|
648
|
-
iss,
|
|
649
|
-
aud,
|
|
650
|
-
sub: params.policyId,
|
|
651
|
-
tenantId: params.tenantId,
|
|
652
|
-
policyId: params.policyId,
|
|
653
|
-
fingerprint: params.fingerprint,
|
|
654
|
-
matchedBy: params.matchedBy,
|
|
655
|
-
country: params.country,
|
|
656
|
-
region: params.region,
|
|
657
|
-
jurisdiction: params.jurisdiction,
|
|
658
|
-
language: params.language,
|
|
659
|
-
model: params.model,
|
|
660
|
-
policyI18n: params.policyI18n,
|
|
661
|
-
expiryDays: params.expiryDays,
|
|
662
|
-
scopeMode: params.scopeMode,
|
|
663
|
-
uiMode: params.uiMode,
|
|
664
|
-
bannerUi: params.bannerUi,
|
|
665
|
-
dialogUi: params.dialogUi,
|
|
666
|
-
categories: params.categories,
|
|
667
|
-
preselectedCategories: params.preselectedCategories,
|
|
668
|
-
gpc: params.gpc,
|
|
669
|
-
proofConfig: params.proofConfig,
|
|
670
|
-
iat,
|
|
671
|
-
exp
|
|
672
|
-
};
|
|
673
|
-
const token = await new SignJWT(payload).setProtectedHeader(POLICY_SNAPSHOT_JWT_HEADER).setIssuedAt(iat).setExpirationTime(exp).sign(getSigningKey(options.signingKey));
|
|
674
|
-
return {
|
|
675
|
-
token,
|
|
676
|
-
payload
|
|
677
|
-
};
|
|
678
|
-
}
|
|
679
|
-
async function verifyPolicySnapshotToken(params) {
|
|
680
|
-
const { token, options, tenantId } = params;
|
|
681
|
-
if (!options?.signingKey) return {
|
|
682
|
-
valid: false,
|
|
683
|
-
reason: 'missing'
|
|
684
|
-
};
|
|
685
|
-
if (!token) return {
|
|
686
|
-
valid: false,
|
|
687
|
-
reason: 'missing'
|
|
688
|
-
};
|
|
689
|
-
if (3 !== token.split('.').length) return {
|
|
690
|
-
valid: false,
|
|
691
|
-
reason: 'malformed'
|
|
692
|
-
};
|
|
693
|
-
try {
|
|
694
|
-
const { payload, protectedHeader } = await jwtVerify(token, getSigningKey(options.signingKey), {
|
|
695
|
-
issuer: resolveSnapshotIssuer(options),
|
|
696
|
-
audience: resolveSnapshotAudience({
|
|
697
|
-
options,
|
|
698
|
-
tenantId
|
|
699
|
-
})
|
|
700
|
-
});
|
|
701
|
-
const header = protectedHeader;
|
|
702
|
-
if ('HS256' !== header.alg || 'JWT' !== header.typ) return {
|
|
703
|
-
valid: false,
|
|
704
|
-
reason: 'invalid'
|
|
705
|
-
};
|
|
706
|
-
if (!isPolicySnapshotPayload(payload)) return {
|
|
707
|
-
valid: false,
|
|
708
|
-
reason: 'invalid'
|
|
709
|
-
};
|
|
710
|
-
if (payload.sub !== payload.policyId) return {
|
|
711
|
-
valid: false,
|
|
712
|
-
reason: 'invalid'
|
|
713
|
-
};
|
|
714
|
-
if ((tenantId ?? void 0) !== (payload.tenantId ?? void 0)) return {
|
|
715
|
-
valid: false,
|
|
716
|
-
reason: 'invalid'
|
|
717
|
-
};
|
|
718
|
-
return {
|
|
719
|
-
valid: true,
|
|
720
|
-
payload
|
|
721
|
-
};
|
|
722
|
-
} catch (error) {
|
|
723
|
-
if (error instanceof errors.JWTExpired) return {
|
|
724
|
-
valid: false,
|
|
725
|
-
reason: 'expired'
|
|
726
|
-
};
|
|
727
|
-
return {
|
|
728
|
-
valid: false,
|
|
729
|
-
reason: 'invalid'
|
|
730
|
-
};
|
|
731
|
-
}
|
|
732
|
-
}
|
|
733
|
-
function geo_normalizeHeader(value) {
|
|
734
|
-
if (!value) return null;
|
|
735
|
-
return Array.isArray(value) ? value[0] ?? null : value;
|
|
736
|
-
}
|
|
737
|
-
function getGeoHeaders(headers) {
|
|
738
|
-
const countryCode = geo_normalizeHeader(headers.get('x-c15t-country')) ?? geo_normalizeHeader(headers.get('cf-ipcountry')) ?? geo_normalizeHeader(headers.get('x-vercel-ip-country')) ?? geo_normalizeHeader(headers.get('x-amz-cf-ipcountry')) ?? geo_normalizeHeader(headers.get('x-country-code'));
|
|
739
|
-
const regionCode = geo_normalizeHeader(headers.get('x-c15t-region')) ?? geo_normalizeHeader(headers.get('x-vercel-ip-country-region')) ?? geo_normalizeHeader(headers.get('x-region-code'));
|
|
740
|
-
return {
|
|
741
|
-
countryCode,
|
|
742
|
-
regionCode
|
|
743
|
-
};
|
|
744
|
-
}
|
|
745
|
-
function checkJurisdiction(countryCode, regionCode) {
|
|
746
|
-
const jurisdictions = {
|
|
747
|
-
EU: new Set([
|
|
748
|
-
'AT',
|
|
749
|
-
'BE',
|
|
750
|
-
'BG',
|
|
751
|
-
'HR',
|
|
752
|
-
'CY',
|
|
753
|
-
'CZ',
|
|
754
|
-
'DK',
|
|
755
|
-
'EE',
|
|
756
|
-
'FI',
|
|
757
|
-
'FR',
|
|
758
|
-
'DE',
|
|
759
|
-
'GR',
|
|
760
|
-
'HU',
|
|
761
|
-
'IE',
|
|
762
|
-
'IT',
|
|
763
|
-
'LV',
|
|
764
|
-
'LT',
|
|
765
|
-
'LU',
|
|
766
|
-
'MT',
|
|
767
|
-
'NL',
|
|
768
|
-
'PL',
|
|
769
|
-
'PT',
|
|
770
|
-
'RO',
|
|
771
|
-
'SK',
|
|
772
|
-
'SI',
|
|
773
|
-
'ES',
|
|
774
|
-
'SE'
|
|
775
|
-
]),
|
|
776
|
-
EEA: new Set([
|
|
777
|
-
'IS',
|
|
778
|
-
'NO',
|
|
779
|
-
'LI'
|
|
780
|
-
]),
|
|
781
|
-
UK: new Set([
|
|
782
|
-
'GB'
|
|
783
|
-
]),
|
|
784
|
-
CH: new Set([
|
|
785
|
-
'CH'
|
|
786
|
-
]),
|
|
787
|
-
BR: new Set([
|
|
788
|
-
'BR'
|
|
789
|
-
]),
|
|
790
|
-
CA: new Set([
|
|
791
|
-
'CA'
|
|
792
|
-
]),
|
|
793
|
-
AU: new Set([
|
|
794
|
-
'AU'
|
|
795
|
-
]),
|
|
796
|
-
JP: new Set([
|
|
797
|
-
'JP'
|
|
798
|
-
]),
|
|
799
|
-
KR: new Set([
|
|
800
|
-
'KR'
|
|
801
|
-
]),
|
|
802
|
-
US_CCPA_REGIONS: new Set([
|
|
803
|
-
'CA'
|
|
804
|
-
]),
|
|
805
|
-
CA_QC_REGIONS: new Set([
|
|
806
|
-
'QC'
|
|
807
|
-
])
|
|
808
|
-
};
|
|
809
|
-
let jurisdiction = 'NONE';
|
|
810
|
-
if (countryCode) {
|
|
811
|
-
const normalizedCountryCode = countryCode.toUpperCase();
|
|
812
|
-
const normalizedRegionCode = regionCode && 'string' == typeof regionCode ? (regionCode.includes('-') ? regionCode.split('-').pop() : regionCode).toUpperCase() : null;
|
|
813
|
-
if ('US' === normalizedCountryCode && normalizedRegionCode && jurisdictions.US_CCPA_REGIONS.has(normalizedRegionCode)) return 'CCPA';
|
|
814
|
-
if ('CA' === normalizedCountryCode && normalizedRegionCode && jurisdictions.CA_QC_REGIONS.has(normalizedRegionCode)) return 'QC_LAW25';
|
|
815
|
-
const jurisdictionMap = [
|
|
816
|
-
{
|
|
817
|
-
sets: [
|
|
818
|
-
jurisdictions.UK
|
|
819
|
-
],
|
|
820
|
-
code: 'UK_GDPR'
|
|
821
|
-
},
|
|
822
|
-
{
|
|
823
|
-
sets: [
|
|
824
|
-
jurisdictions.EU,
|
|
825
|
-
jurisdictions.EEA
|
|
826
|
-
],
|
|
827
|
-
code: 'GDPR'
|
|
828
|
-
},
|
|
829
|
-
{
|
|
830
|
-
sets: [
|
|
831
|
-
jurisdictions.CH
|
|
832
|
-
],
|
|
833
|
-
code: 'CH'
|
|
834
|
-
},
|
|
835
|
-
{
|
|
836
|
-
sets: [
|
|
837
|
-
jurisdictions.BR
|
|
838
|
-
],
|
|
839
|
-
code: 'BR'
|
|
840
|
-
},
|
|
841
|
-
{
|
|
842
|
-
sets: [
|
|
843
|
-
jurisdictions.CA
|
|
844
|
-
],
|
|
845
|
-
code: 'PIPEDA'
|
|
846
|
-
},
|
|
847
|
-
{
|
|
848
|
-
sets: [
|
|
849
|
-
jurisdictions.AU
|
|
850
|
-
],
|
|
851
|
-
code: 'AU'
|
|
852
|
-
},
|
|
853
|
-
{
|
|
854
|
-
sets: [
|
|
855
|
-
jurisdictions.JP
|
|
856
|
-
],
|
|
857
|
-
code: 'APPI'
|
|
858
|
-
},
|
|
859
|
-
{
|
|
860
|
-
sets: [
|
|
861
|
-
jurisdictions.KR
|
|
862
|
-
],
|
|
863
|
-
code: 'PIPA'
|
|
864
|
-
}
|
|
865
|
-
];
|
|
866
|
-
for (const { sets, code } of jurisdictionMap)if (sets.some((set)=>set.has(normalizedCountryCode))) {
|
|
867
|
-
jurisdiction = code;
|
|
868
|
-
break;
|
|
869
|
-
}
|
|
870
|
-
}
|
|
871
|
-
return jurisdiction;
|
|
872
|
-
}
|
|
873
|
-
async function getLocation(request, options) {
|
|
874
|
-
if (options.disableGeoLocation) return {
|
|
875
|
-
countryCode: null,
|
|
876
|
-
regionCode: null
|
|
877
|
-
};
|
|
878
|
-
const { countryCode, regionCode } = getGeoHeaders(request.headers);
|
|
879
|
-
return {
|
|
880
|
-
countryCode,
|
|
881
|
-
regionCode
|
|
882
|
-
};
|
|
883
|
-
}
|
|
884
|
-
function getJurisdiction(location, options) {
|
|
885
|
-
if (options.disableGeoLocation) return 'GDPR';
|
|
886
|
-
return checkJurisdiction(location.countryCode, location.regionCode);
|
|
887
|
-
}
|
|
888
|
-
async function policy_resolvePolicyDecision(params) {
|
|
889
|
-
return resolvePolicyDecision({
|
|
890
|
-
policies: params.policies,
|
|
891
|
-
countryCode: params.countryCode,
|
|
892
|
-
regionCode: params.regionCode,
|
|
893
|
-
jurisdiction: params.jurisdiction,
|
|
894
|
-
iabEnabled: params.iabEnabled
|
|
895
|
-
});
|
|
896
|
-
}
|
|
897
|
-
const DEFAULT_PROFILE = 'default';
|
|
898
|
-
const warnedKeys = new Set();
|
|
899
|
-
function isSupportedBaseLanguage(lang) {
|
|
900
|
-
return lang in baseTranslations;
|
|
901
|
-
}
|
|
902
|
-
function warnOnce(logger, key, message, metadata) {
|
|
903
|
-
if (!logger || warnedKeys.has(key)) return;
|
|
904
|
-
warnedKeys.add(key);
|
|
905
|
-
logger.warn(message, metadata);
|
|
906
|
-
}
|
|
907
|
-
function normalizeLanguage(value) {
|
|
908
|
-
if (!value) return;
|
|
909
|
-
const normalized = value.split(',')[0]?.split(';')[0]?.trim().toLowerCase();
|
|
910
|
-
if (!normalized) return;
|
|
911
|
-
return normalized.split('-')[0] ?? void 0;
|
|
912
|
-
}
|
|
913
|
-
function normalizeProfiles(params) {
|
|
914
|
-
const profiles = params.i18n?.messages;
|
|
915
|
-
const legacy = params.customTranslations;
|
|
916
|
-
if (profiles && Object.keys(profiles).length > 0) {
|
|
917
|
-
if (legacy && Object.keys(legacy).length > 0) warnOnce(params.logger, 'i18n.customTranslations.ignored', '`customTranslations` is deprecated and ignored when `i18n.messages` is configured.');
|
|
918
|
-
return profiles;
|
|
919
|
-
}
|
|
920
|
-
if (legacy && Object.keys(legacy).length > 0) {
|
|
921
|
-
warnOnce(params.logger, 'i18n.customTranslations.deprecated', '`customTranslations` is deprecated. Use `i18n.messages` instead.');
|
|
922
|
-
return {
|
|
923
|
-
[DEFAULT_PROFILE]: {
|
|
924
|
-
translations: legacy
|
|
925
|
-
}
|
|
926
|
-
};
|
|
927
|
-
}
|
|
928
|
-
return {};
|
|
929
|
-
}
|
|
930
|
-
function buildCandidates(input) {
|
|
931
|
-
const raw = [
|
|
932
|
-
{
|
|
933
|
-
language: input.language,
|
|
934
|
-
reason: 'profile_language'
|
|
935
|
-
},
|
|
936
|
-
{
|
|
937
|
-
language: input.fallbackLanguage,
|
|
938
|
-
reason: 'profile_fallback'
|
|
939
|
-
}
|
|
940
|
-
];
|
|
941
|
-
const dedupe = new Set();
|
|
942
|
-
return raw.filter((candidate)=>{
|
|
943
|
-
const key = candidate.language;
|
|
944
|
-
if (dedupe.has(key)) return false;
|
|
945
|
-
dedupe.add(key);
|
|
946
|
-
return true;
|
|
947
|
-
});
|
|
948
|
-
}
|
|
949
|
-
function getProfileLanguages(profiles, profile) {
|
|
950
|
-
return Object.keys(profiles[profile]?.translations ?? {}).sort();
|
|
951
|
-
}
|
|
952
|
-
function getSelectableLanguages(input) {
|
|
953
|
-
return getProfileLanguages(input.profiles, input.profile);
|
|
954
|
-
}
|
|
955
|
-
function resolveFallbackLanguage(input) {
|
|
956
|
-
const configuredFallbackLanguage = normalizeLanguage(input.profile?.fallbackLanguage) ?? 'en';
|
|
957
|
-
const profileLanguages = Object.keys(input.profile?.translations ?? {}).sort();
|
|
958
|
-
if (profileLanguages.includes(configuredFallbackLanguage)) return configuredFallbackLanguage;
|
|
959
|
-
if (profileLanguages.includes('en')) return 'en';
|
|
960
|
-
return profileLanguages[0] ?? configuredFallbackLanguage;
|
|
961
|
-
}
|
|
962
|
-
function resolveActiveProfile(input) {
|
|
963
|
-
const requestedProfile = input.policyProfile ?? input.defaultProfile;
|
|
964
|
-
if (input.profiles[requestedProfile]) return requestedProfile;
|
|
965
|
-
if (input.policyProfile) warnOnce(input.logger, `i18n.profile.missing:${requestedProfile}`, `Policy i18n profile '${requestedProfile}' does not exist. Falling back to default profile '${input.defaultProfile}'.`);
|
|
966
|
-
return input.defaultProfile;
|
|
967
|
-
}
|
|
968
|
-
function translations_getTranslationsData(acceptLanguage, customTranslations, options) {
|
|
969
|
-
const profiles = normalizeProfiles({
|
|
970
|
-
customTranslations,
|
|
971
|
-
i18n: options?.i18n,
|
|
972
|
-
logger: options?.logger
|
|
973
|
-
});
|
|
974
|
-
const defaultProfile = options?.i18n?.defaultProfile ?? DEFAULT_PROFILE;
|
|
975
|
-
const profile = resolveActiveProfile({
|
|
976
|
-
profiles,
|
|
977
|
-
defaultProfile,
|
|
978
|
-
policyProfile: options?.policyI18n?.messageProfile,
|
|
979
|
-
logger: options?.logger
|
|
980
|
-
});
|
|
981
|
-
const configuredLanguages = Object.keys(profiles).length > 0 ? getSelectableLanguages({
|
|
982
|
-
profiles,
|
|
983
|
-
profile
|
|
984
|
-
}) : Object.keys(baseTranslations);
|
|
985
|
-
const fallbackLanguage = Object.keys(profiles).length > 0 ? resolveFallbackLanguage({
|
|
986
|
-
profile: profiles[profile]
|
|
987
|
-
}) : 'en';
|
|
988
|
-
const policyLanguage = normalizeLanguage(options?.policyI18n?.language);
|
|
989
|
-
const requestedLanguage = policyLanguage ?? selectLanguage(configuredLanguages, {
|
|
990
|
-
header: acceptLanguage,
|
|
991
|
-
fallback: fallbackLanguage
|
|
992
|
-
});
|
|
993
|
-
const candidates = buildCandidates({
|
|
994
|
-
language: requestedLanguage,
|
|
995
|
-
fallbackLanguage
|
|
996
|
-
});
|
|
997
|
-
const selectedCandidate = candidates.find((candidate)=>!!profiles[profile]?.translations[candidate.language]);
|
|
998
|
-
if (selectedCandidate && 'profile_language' !== selectedCandidate.reason) warnOnce(options?.logger, `i18n.fallback:${profile}:${requestedLanguage}:${selectedCandidate.language}`, `Policy translation fallback used (${selectedCandidate.reason}).`, {
|
|
999
|
-
requestedProfile: profile,
|
|
1000
|
-
requestedLanguage,
|
|
1001
|
-
resolvedProfile: profile,
|
|
1002
|
-
resolvedLanguage: selectedCandidate.language
|
|
1003
|
-
});
|
|
1004
|
-
let language = selectedCandidate?.language ?? requestedLanguage;
|
|
1005
|
-
if (!selectedCandidate && !isSupportedBaseLanguage(language)) {
|
|
1006
|
-
warnOnce(options?.logger, `i18n.base-fallback:${language}`, `No translation found for '${language}'. Falling back to base English translations.`);
|
|
1007
|
-
language = 'en';
|
|
1008
|
-
}
|
|
1009
|
-
const base = isSupportedBaseLanguage(language) ? baseTranslations[language] : baseTranslations.en;
|
|
1010
|
-
const custom = selectedCandidate ? profiles[profile]?.translations[selectedCandidate.language] : void 0;
|
|
1011
|
-
const translations = custom ? deepMergeTranslations(base, custom) : base;
|
|
1012
|
-
return {
|
|
1013
|
-
translations: translations,
|
|
1014
|
-
language
|
|
1015
|
-
};
|
|
1016
|
-
}
|
|
1017
|
-
function stripIabTranslations(translations) {
|
|
1018
|
-
const { iab: _iab, ...rest } = translations;
|
|
1019
|
-
return rest;
|
|
1020
|
-
}
|
|
1021
|
-
function resolveNoPolicyFallback() {
|
|
1022
|
-
return {
|
|
1023
|
-
id: 'no_banner',
|
|
1024
|
-
model: 'none',
|
|
1025
|
-
ui: {
|
|
1026
|
-
mode: 'none'
|
|
1027
|
-
}
|
|
1028
|
-
};
|
|
1029
|
-
}
|
|
1030
|
-
async function resolveInitPayload(request, options, logger) {
|
|
1031
|
-
const acceptLanguage = request.headers.get('accept-language') || 'en';
|
|
1032
|
-
const location = await getLocation(request, options);
|
|
1033
|
-
const jurisdiction = getJurisdiction(location, options);
|
|
1034
|
-
const hasExplicitPolicyPack = void 0 !== options.policyPacks;
|
|
1035
|
-
const isExplicitEmptyPolicyPack = hasExplicitPolicyPack && (options.policyPacks?.length ?? 0) === 0;
|
|
1036
|
-
const policyDecision = isExplicitEmptyPolicyPack ? void 0 : await policy_resolvePolicyDecision({
|
|
1037
|
-
policies: options.policyPacks,
|
|
1038
|
-
countryCode: location.countryCode,
|
|
1039
|
-
regionCode: location.regionCode,
|
|
1040
|
-
jurisdiction,
|
|
1041
|
-
iabEnabled: options.iab?.enabled === true
|
|
1042
|
-
});
|
|
1043
|
-
if (hasExplicitPolicyPack && !isExplicitEmptyPolicyPack && !policyDecision) logger?.warn('Policy packs configured but no policy matched', {
|
|
1044
|
-
country: location.countryCode,
|
|
1045
|
-
region: location.regionCode
|
|
1046
|
-
});
|
|
1047
|
-
const resolvedPolicy = hasExplicitPolicyPack ? policyDecision?.policy ?? resolveNoPolicyFallback() : void 0;
|
|
1048
|
-
const iabOptions = options.iab;
|
|
1049
|
-
const shouldIncludeIabPayload = iabOptions?.enabled === true && (!hasExplicitPolicyPack || resolvedPolicy?.model === 'iab');
|
|
1050
|
-
const translationsResult = translations_getTranslationsData(acceptLanguage, options.customTranslations, {
|
|
1051
|
-
i18n: options.i18n,
|
|
1052
|
-
policyI18n: resolvedPolicy?.i18n,
|
|
1053
|
-
logger
|
|
1054
|
-
});
|
|
1055
|
-
const responseTranslations = shouldIncludeIabPayload ? translationsResult : {
|
|
1056
|
-
...translationsResult,
|
|
1057
|
-
translations: stripIabTranslations(translationsResult.translations)
|
|
1058
|
-
};
|
|
1059
|
-
let gvl = null;
|
|
1060
|
-
if (shouldIncludeIabPayload && iabOptions) {
|
|
1061
|
-
const language = translationsResult.language.split('-')[0] || 'en';
|
|
1062
|
-
const gvlResolver = createGVLResolver({
|
|
1063
|
-
appName: options.appName || 'c15t',
|
|
1064
|
-
bundled: iabOptions.bundled,
|
|
1065
|
-
cacheAdapter: options.cache?.adapter,
|
|
1066
|
-
vendorIds: iabOptions.vendorIds,
|
|
1067
|
-
endpoint: iabOptions.endpoint
|
|
1068
|
-
});
|
|
1069
|
-
gvl = await gvlResolver.get(language);
|
|
1070
|
-
}
|
|
1071
|
-
const customVendors = shouldIncludeIabPayload ? iabOptions?.customVendors : void 0;
|
|
1072
|
-
const snapshot = policyDecision ? await createPolicySnapshotToken({
|
|
1073
|
-
options: options.policySnapshot,
|
|
1074
|
-
tenantId: options.tenantId,
|
|
1075
|
-
policyId: policyDecision.policy.id,
|
|
1076
|
-
fingerprint: policyDecision.fingerprint,
|
|
1077
|
-
matchedBy: policyDecision.matchedBy,
|
|
1078
|
-
country: location?.countryCode ?? null,
|
|
1079
|
-
region: location?.regionCode ?? null,
|
|
1080
|
-
jurisdiction,
|
|
1081
|
-
language: translationsResult.language,
|
|
1082
|
-
model: policyDecision.policy.model,
|
|
1083
|
-
policyI18n: policyDecision.policy.i18n,
|
|
1084
|
-
expiryDays: policyDecision.policy.consent?.expiryDays,
|
|
1085
|
-
scopeMode: policyDecision.policy.consent?.scopeMode,
|
|
1086
|
-
uiMode: policyDecision.policy.ui?.mode,
|
|
1087
|
-
bannerUi: policyDecision.policy.ui?.banner,
|
|
1088
|
-
dialogUi: policyDecision.policy.ui?.dialog,
|
|
1089
|
-
categories: policyDecision.policy.consent?.categories,
|
|
1090
|
-
preselectedCategories: policyDecision.policy.consent?.preselectedCategories,
|
|
1091
|
-
gpc: policyDecision.policy.consent?.gpc,
|
|
1092
|
-
proofConfig: policyDecision.policy.proof
|
|
1093
|
-
}) : void 0;
|
|
1094
|
-
const gpc = '1' === request.headers.get('sec-gpc');
|
|
1095
|
-
getMetrics()?.recordInit({
|
|
1096
|
-
jurisdiction,
|
|
1097
|
-
country: location?.countryCode ?? void 0,
|
|
1098
|
-
region: location?.regionCode ?? void 0,
|
|
1099
|
-
gpc
|
|
1100
|
-
});
|
|
1101
|
-
return {
|
|
1102
|
-
jurisdiction,
|
|
1103
|
-
location,
|
|
1104
|
-
translations: responseTranslations,
|
|
1105
|
-
branding: options.branding || 'c15t',
|
|
1106
|
-
...shouldIncludeIabPayload && {
|
|
1107
|
-
gvl,
|
|
1108
|
-
customVendors
|
|
1109
|
-
},
|
|
1110
|
-
...resolvedPolicy && {
|
|
1111
|
-
policy: resolvedPolicy
|
|
1112
|
-
},
|
|
1113
|
-
...policyDecision && {
|
|
1114
|
-
policyDecision: {
|
|
1115
|
-
policyId: policyDecision.policy.id,
|
|
1116
|
-
fingerprint: policyDecision.fingerprint,
|
|
1117
|
-
matchedBy: policyDecision.matchedBy,
|
|
1118
|
-
country: location.countryCode,
|
|
1119
|
-
region: location.regionCode,
|
|
1120
|
-
jurisdiction
|
|
1121
|
-
}
|
|
1122
|
-
},
|
|
1123
|
-
...snapshot?.token && {
|
|
1124
|
-
policySnapshotToken: snapshot.token
|
|
1125
|
-
},
|
|
1126
|
-
...shouldIncludeIabPayload && iabOptions?.cmpId != null && {
|
|
1127
|
-
cmpId: iabOptions.cmpId
|
|
1128
|
-
}
|
|
1129
|
-
};
|
|
1130
|
-
}
|
|
1131
|
-
const createInitRoute = (options)=>{
|
|
1132
|
-
const app = new Hono();
|
|
1133
|
-
app.get('/', describeRoute({
|
|
1134
|
-
summary: 'Get initial consent manager state',
|
|
1135
|
-
description: `Returns the initial state required to render the consent manager.
|
|
1136
|
-
|
|
1137
|
-
- **Jurisdiction** – User's jurisdiction (defaults to GDPR if geo-location is disabled)
|
|
1138
|
-
- **Location** – User's location (null if geo-location is disabled)
|
|
1139
|
-
- **Translations** – Consent manager copy (from \`Accept-Language\` header)
|
|
1140
|
-
- **Branding** – Configured branding key
|
|
1141
|
-
- **GVL** – Global Vendor List when IAB is active for the request
|
|
1142
|
-
|
|
1143
|
-
Use for geo-targeted consent banners and regional compliance.`,
|
|
1144
|
-
tags: [
|
|
1145
|
-
'Init'
|
|
1146
|
-
],
|
|
1147
|
-
responses: {
|
|
1148
|
-
200: {
|
|
1149
|
-
description: 'Initialization payload (jurisdiction, location, translations, branding, GVL)',
|
|
1150
|
-
content: {
|
|
1151
|
-
'application/json': {
|
|
1152
|
-
schema: resolver(initOutputSchema)
|
|
1153
|
-
}
|
|
1154
|
-
}
|
|
1155
|
-
}
|
|
1156
|
-
}
|
|
1157
|
-
}), async (c)=>{
|
|
1158
|
-
const ctx = c.get('c15tContext');
|
|
1159
|
-
const payload = await resolveInitPayload(c.req.raw, options, ctx?.logger);
|
|
1160
|
-
return c.json(payload);
|
|
1161
|
-
});
|
|
1162
|
-
return app;
|
|
1163
|
-
};
|
|
1164
|
-
function getHeaders(headers) {
|
|
1165
|
-
if (!headers) return {
|
|
1166
|
-
countryCode: null,
|
|
1167
|
-
regionCode: null,
|
|
1168
|
-
acceptLanguage: null
|
|
1169
|
-
};
|
|
1170
|
-
const normalizeHeader = (value)=>{
|
|
1171
|
-
if (!value) return null;
|
|
1172
|
-
return Array.isArray(value) ? value[0] ?? null : value;
|
|
1173
|
-
};
|
|
1174
|
-
const countryCode = normalizeHeader(headers.get('x-c15t-country')) ?? normalizeHeader(headers.get('cf-ipcountry')) ?? normalizeHeader(headers.get('x-vercel-ip-country')) ?? normalizeHeader(headers.get('x-amz-cf-ipcountry')) ?? normalizeHeader(headers.get('x-country-code'));
|
|
1175
|
-
const regionCode = normalizeHeader(headers.get('x-c15t-region')) ?? normalizeHeader(headers.get('x-vercel-ip-country-region')) ?? normalizeHeader(headers.get('x-region-code'));
|
|
1176
|
-
const acceptLanguage = normalizeHeader(headers.get('accept-language'));
|
|
1177
|
-
return {
|
|
1178
|
-
countryCode,
|
|
1179
|
-
regionCode,
|
|
1180
|
-
acceptLanguage
|
|
1181
|
-
};
|
|
1182
|
-
}
|
|
1183
|
-
const statusHandler = async (c)=>{
|
|
1184
|
-
const ctx = c.get('c15tContext');
|
|
1185
|
-
const { countryCode, regionCode, acceptLanguage } = getHeaders(ctx.headers);
|
|
1186
|
-
const clientInfo = {
|
|
1187
|
-
ip: ctx.ipAddress ?? null,
|
|
1188
|
-
acceptLanguage,
|
|
1189
|
-
userAgent: ctx.userAgent ?? null,
|
|
1190
|
-
region: {
|
|
1191
|
-
countryCode,
|
|
1192
|
-
regionCode
|
|
1193
|
-
}
|
|
1194
|
-
};
|
|
1195
|
-
try {
|
|
1196
|
-
await ctx.db.findFirst('subject', {});
|
|
1197
|
-
return c.json({
|
|
1198
|
-
version: version_version,
|
|
1199
|
-
timestamp: new Date(),
|
|
1200
|
-
client: clientInfo
|
|
1201
|
-
});
|
|
1202
|
-
} catch (error) {
|
|
1203
|
-
ctx.logger.error('Database health check failed', {
|
|
1204
|
-
error
|
|
1205
|
-
});
|
|
1206
|
-
throw new HTTPException(503, {
|
|
1207
|
-
message: 'Database health check failed',
|
|
1208
|
-
cause: {
|
|
1209
|
-
code: 'SERVICE_UNAVAILABLE',
|
|
1210
|
-
error
|
|
1211
|
-
}
|
|
1212
|
-
});
|
|
1213
|
-
}
|
|
1214
|
-
};
|
|
1215
|
-
const createStatusRoute = ()=>{
|
|
1216
|
-
const app = new Hono();
|
|
1217
|
-
app.get('/', describeRoute({
|
|
1218
|
-
summary: 'Health check and API status',
|
|
1219
|
-
description: `Returns API version, timestamp, and client info (IP, region, user agent).
|
|
1220
|
-
|
|
1221
|
-
Use for health checks, load balancer probes, and debugging. Performs a lightweight DB check; returns 503 if the database is unreachable.`,
|
|
1222
|
-
tags: [
|
|
1223
|
-
'Status'
|
|
1224
|
-
],
|
|
1225
|
-
responses: {
|
|
1226
|
-
200: {
|
|
1227
|
-
description: 'API is healthy (version, timestamp, client info)',
|
|
1228
|
-
content: {
|
|
1229
|
-
'application/json': {
|
|
1230
|
-
schema: resolver(statusOutputSchema)
|
|
1231
|
-
}
|
|
1232
|
-
}
|
|
1233
|
-
},
|
|
1234
|
-
503: {
|
|
1235
|
-
description: 'Service unavailable (e.g. database unreachable)'
|
|
1236
|
-
}
|
|
1237
|
-
}
|
|
1238
|
-
}), statusHandler);
|
|
1239
|
-
return app;
|
|
1240
|
-
};
|
|
1241
|
-
const getSubjectHandler = async (c)=>{
|
|
1242
|
-
const ctx = c.get('c15tContext');
|
|
1243
|
-
const logger = ctx.logger;
|
|
1244
|
-
logger.info('Handling GET /subjects/:id request');
|
|
1245
|
-
const { db, registry } = ctx;
|
|
1246
|
-
const subjectId = c.req.param('id');
|
|
1247
|
-
const type = c.req.query('type');
|
|
1248
|
-
const typeFilter = type?.split(',').map((t)=>t.trim()) || [];
|
|
1249
|
-
logger.debug('Request parameters', {
|
|
1250
|
-
subjectId,
|
|
1251
|
-
typeFilter
|
|
1252
|
-
});
|
|
1253
|
-
try {
|
|
1254
|
-
const subject = await db.findFirst('subject', {
|
|
1255
|
-
where: (b)=>b('id', '=', subjectId)
|
|
1256
|
-
});
|
|
1257
|
-
if (!subject) throw new HTTPException(404, {
|
|
1258
|
-
message: 'Subject not found',
|
|
1259
|
-
cause: {
|
|
1260
|
-
code: 'SUBJECT_NOT_FOUND',
|
|
1261
|
-
subjectId
|
|
1262
|
-
}
|
|
1263
|
-
});
|
|
1264
|
-
const consents = await db.findMany('consent', {
|
|
1265
|
-
where: (b)=>b('subjectId', '=', subjectId)
|
|
1266
|
-
});
|
|
1267
|
-
const consentItems = await enrichConsents(consents, {
|
|
1268
|
-
db,
|
|
1269
|
-
registry
|
|
1270
|
-
});
|
|
1271
|
-
const filteredConsents = typeFilter.length > 0 ? consentItems.filter((consent)=>typeFilter.includes(consent.type)) : consentItems;
|
|
1272
|
-
const isValid = 0 === typeFilter.length || typeFilter.every((t)=>filteredConsents.some((consent)=>consent.type === t && consent.isLatestPolicy));
|
|
1273
|
-
return c.json({
|
|
1274
|
-
subject: {
|
|
1275
|
-
id: subject.id,
|
|
1276
|
-
externalId: subject.externalId ?? void 0,
|
|
1277
|
-
createdAt: subject.createdAt
|
|
1278
|
-
},
|
|
1279
|
-
consents: filteredConsents,
|
|
1280
|
-
isValid
|
|
1281
|
-
});
|
|
1282
|
-
} catch (error) {
|
|
1283
|
-
logger.error('Error in GET /subjects/:id handler', {
|
|
1284
|
-
error: extractErrorMessage(error),
|
|
1285
|
-
errorType: error instanceof Error ? error.constructor.name : typeof error
|
|
1286
|
-
});
|
|
1287
|
-
if (error instanceof HTTPException) throw error;
|
|
1288
|
-
throw new HTTPException(500, {
|
|
1289
|
-
message: 'Internal server error',
|
|
1290
|
-
cause: {
|
|
1291
|
-
code: 'INTERNAL_SERVER_ERROR'
|
|
1292
|
-
}
|
|
1293
|
-
});
|
|
1294
|
-
}
|
|
1295
|
-
};
|
|
1296
|
-
const listSubjectsHandler = async (c)=>{
|
|
1297
|
-
const ctx = c.get('c15tContext');
|
|
1298
|
-
const logger = ctx.logger;
|
|
1299
|
-
logger.info('Handling GET /subjects request');
|
|
1300
|
-
const { db, registry } = ctx;
|
|
1301
|
-
if (!ctx.apiKeyAuthenticated) throw new HTTPException(401, {
|
|
1302
|
-
message: 'API key required. Use Authorization: Bearer <api_key>',
|
|
1303
|
-
cause: {
|
|
1304
|
-
code: 'UNAUTHORIZED'
|
|
1305
|
-
}
|
|
1306
|
-
});
|
|
1307
|
-
const externalId = c.req.query('externalId');
|
|
1308
|
-
if (!externalId) throw new HTTPException(422, {
|
|
1309
|
-
message: 'externalId query parameter is required',
|
|
1310
|
-
cause: {
|
|
1311
|
-
code: 'EXTERNAL_ID_REQUIRED'
|
|
1312
|
-
}
|
|
1313
|
-
});
|
|
1314
|
-
logger.debug('Request parameters', {
|
|
1315
|
-
externalId
|
|
1316
|
-
});
|
|
1317
|
-
try {
|
|
1318
|
-
const subjects = await db.findMany('subject', {
|
|
1319
|
-
where: (b)=>b('externalId', '=', externalId)
|
|
1320
|
-
});
|
|
1321
|
-
const subjectItems = await Promise.all(subjects.map(async (subject)=>{
|
|
1322
|
-
const consents = await db.findMany('consent', {
|
|
1323
|
-
where: (b)=>b('subjectId', '=', subject.id)
|
|
1324
|
-
});
|
|
1325
|
-
const consentItems = await enrichConsents(consents, {
|
|
1326
|
-
db,
|
|
1327
|
-
registry
|
|
1328
|
-
});
|
|
1329
|
-
return {
|
|
1330
|
-
id: subject.id,
|
|
1331
|
-
externalId: subject.externalId ?? externalId,
|
|
1332
|
-
createdAt: subject.createdAt,
|
|
1333
|
-
consents: consentItems
|
|
1334
|
-
};
|
|
1335
|
-
}));
|
|
1336
|
-
logger.info('Found subjects for externalId', {
|
|
1337
|
-
externalId,
|
|
1338
|
-
count: subjectItems.length
|
|
1339
|
-
});
|
|
1340
|
-
return c.json({
|
|
1341
|
-
subjects: subjectItems
|
|
1342
|
-
});
|
|
1343
|
-
} catch (error) {
|
|
1344
|
-
logger.error('Error in GET /subjects handler', {
|
|
1345
|
-
error: extractErrorMessage(error),
|
|
1346
|
-
errorType: error instanceof Error ? error.constructor.name : typeof error
|
|
1347
|
-
});
|
|
1348
|
-
if (error instanceof HTTPException) throw error;
|
|
1349
|
-
throw new HTTPException(500, {
|
|
1350
|
-
message: 'Internal server error',
|
|
1351
|
-
cause: {
|
|
1352
|
-
code: 'INTERNAL_SERVER_ERROR'
|
|
1353
|
-
}
|
|
1354
|
-
});
|
|
1355
|
-
}
|
|
1356
|
-
};
|
|
1357
|
-
const prefixes = {
|
|
1358
|
-
auditLog: 'log',
|
|
1359
|
-
consent: 'cns',
|
|
1360
|
-
consentPolicy: 'pol',
|
|
1361
|
-
consentPurpose: 'pur',
|
|
1362
|
-
domain: 'dom',
|
|
1363
|
-
subject: 'sub'
|
|
1364
|
-
};
|
|
1365
|
-
const b58 = base_x('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');
|
|
1366
|
-
function generateId(model) {
|
|
1367
|
-
const buf = crypto.getRandomValues(new Uint8Array(20));
|
|
1368
|
-
const prefix = prefixes[model];
|
|
1369
|
-
const EPOCH_TIMESTAMP = 1700000000000;
|
|
1370
|
-
const t = Date.now() - EPOCH_TIMESTAMP;
|
|
1371
|
-
const high = Math.floor(t / 0x100000000);
|
|
1372
|
-
const low = t >>> 0;
|
|
1373
|
-
buf[0] = high >>> 24 & 255;
|
|
1374
|
-
buf[1] = high >>> 16 & 255;
|
|
1375
|
-
buf[2] = high >>> 8 & 255;
|
|
1376
|
-
buf[3] = 255 & high;
|
|
1377
|
-
buf[4] = low >>> 24 & 255;
|
|
1378
|
-
buf[5] = low >>> 16 & 255;
|
|
1379
|
-
buf[6] = low >>> 8 & 255;
|
|
1380
|
-
buf[7] = 255 & low;
|
|
1381
|
-
return `${prefix}_${b58.encode(buf)}`;
|
|
1382
|
-
}
|
|
1383
|
-
async function generateUniqueId(db, model, ctx, options = {}) {
|
|
1384
|
-
const { maxRetries = 10, attempt = 0, baseDelay = 5 } = options;
|
|
1385
|
-
if (attempt >= maxRetries) {
|
|
1386
|
-
const error = new Error(`Failed to generate unique ID for ${model} after ${maxRetries} attempts`);
|
|
1387
|
-
ctx?.logger?.error?.('ID generation failed', {
|
|
1388
|
-
model,
|
|
1389
|
-
maxRetries
|
|
1390
|
-
});
|
|
1391
|
-
throw error;
|
|
1392
|
-
}
|
|
1393
|
-
const id = generateId(model);
|
|
1394
|
-
try {
|
|
1395
|
-
const existing = await db.findFirst(model, {
|
|
1396
|
-
where: (b)=>b('id', '=', id)
|
|
1397
|
-
});
|
|
1398
|
-
if (existing) {
|
|
1399
|
-
ctx?.logger?.debug?.('ID conflict detected', {
|
|
1400
|
-
id,
|
|
1401
|
-
model,
|
|
1402
|
-
attempt: attempt + 1,
|
|
1403
|
-
maxRetries
|
|
1404
|
-
});
|
|
1405
|
-
const delay = Math.min(baseDelay * 2 ** attempt, 1000);
|
|
1406
|
-
await new Promise((resolve)=>setTimeout(resolve, delay));
|
|
1407
|
-
return generateUniqueId(db, model, ctx, {
|
|
1408
|
-
maxRetries,
|
|
1409
|
-
attempt: attempt + 1,
|
|
1410
|
-
baseDelay
|
|
1411
|
-
});
|
|
1412
|
-
}
|
|
1413
|
-
return id;
|
|
1414
|
-
} catch (error) {
|
|
1415
|
-
ctx?.logger?.error?.('Error checking ID uniqueness', {
|
|
1416
|
-
error: error.message,
|
|
1417
|
-
model,
|
|
1418
|
-
attempt
|
|
1419
|
-
});
|
|
1420
|
-
if (attempt < maxRetries - 1) {
|
|
1421
|
-
const delay = Math.min(baseDelay * 2 ** attempt, 2000);
|
|
1422
|
-
await new Promise((resolve)=>setTimeout(resolve, delay));
|
|
1423
|
-
return generateUniqueId(db, model, ctx, {
|
|
1424
|
-
maxRetries,
|
|
1425
|
-
attempt: attempt + 1,
|
|
1426
|
-
baseDelay
|
|
1427
|
-
});
|
|
1428
|
-
}
|
|
1429
|
-
throw error;
|
|
1430
|
-
}
|
|
1431
|
-
}
|
|
1432
|
-
const patchSubjectHandler = async (c)=>{
|
|
1433
|
-
const ctx = c.get('c15tContext');
|
|
1434
|
-
const logger = ctx.logger;
|
|
1435
|
-
logger.info('Handling PATCH /subjects/:id request');
|
|
1436
|
-
const { db } = ctx;
|
|
1437
|
-
const subjectId = c.req.param('id');
|
|
1438
|
-
const body = await c.req.json();
|
|
1439
|
-
const { externalId, identityProvider = 'external' } = body;
|
|
1440
|
-
logger.debug('Request parameters', {
|
|
1441
|
-
subjectId,
|
|
1442
|
-
externalId,
|
|
1443
|
-
identityProvider
|
|
1444
|
-
});
|
|
1445
|
-
try {
|
|
1446
|
-
const subject = await db.findFirst('subject', {
|
|
1447
|
-
where: (b)=>b('id', '=', subjectId)
|
|
1448
|
-
});
|
|
1449
|
-
if (!subject) throw new HTTPException(404, {
|
|
1450
|
-
message: 'Subject not found',
|
|
1451
|
-
cause: {
|
|
1452
|
-
code: 'SUBJECT_NOT_FOUND',
|
|
1453
|
-
subjectId
|
|
1454
|
-
}
|
|
1455
|
-
});
|
|
1456
|
-
await db.transaction(async (tx)=>{
|
|
1457
|
-
await tx.updateMany('subject', {
|
|
1458
|
-
where: (b)=>b('id', '=', subjectId),
|
|
1459
|
-
set: {
|
|
1460
|
-
externalId,
|
|
1461
|
-
identityProvider,
|
|
1462
|
-
updatedAt: new Date()
|
|
1463
|
-
}
|
|
1464
|
-
});
|
|
1465
|
-
await tx.create('auditLog', {
|
|
1466
|
-
id: await generateUniqueId(tx, 'auditLog', ctx),
|
|
1467
|
-
subjectId,
|
|
1468
|
-
entityType: 'subject',
|
|
1469
|
-
entityId: subjectId,
|
|
1470
|
-
actionType: 'identify_user',
|
|
1471
|
-
ipAddress: ctx.ipAddress || null,
|
|
1472
|
-
userAgent: ctx.userAgent || null,
|
|
1473
|
-
changes: {
|
|
1474
|
-
externalId: {
|
|
1475
|
-
from: subject.externalId,
|
|
1476
|
-
to: externalId
|
|
1477
|
-
},
|
|
1478
|
-
identityProvider: {
|
|
1479
|
-
from: subject.identityProvider,
|
|
1480
|
-
to: identityProvider
|
|
1481
|
-
}
|
|
1482
|
-
},
|
|
1483
|
-
metadata: {
|
|
1484
|
-
externalId,
|
|
1485
|
-
identityProvider
|
|
1486
|
-
}
|
|
1487
|
-
});
|
|
1488
|
-
});
|
|
1489
|
-
logger.info('Subject linked to external ID', {
|
|
1490
|
-
subjectId,
|
|
1491
|
-
externalId,
|
|
1492
|
-
identityProvider
|
|
1493
|
-
});
|
|
1494
|
-
getMetrics()?.recordSubjectLinked(identityProvider);
|
|
1495
|
-
return c.json({
|
|
1496
|
-
success: true,
|
|
1497
|
-
subject: {
|
|
1498
|
-
id: subjectId,
|
|
1499
|
-
externalId
|
|
1500
|
-
}
|
|
1501
|
-
});
|
|
1502
|
-
} catch (error) {
|
|
1503
|
-
logger.error('Error in PATCH /subjects/:id handler', {
|
|
1504
|
-
error: extractErrorMessage(error),
|
|
1505
|
-
errorType: error instanceof Error ? error.constructor.name : typeof error
|
|
1506
|
-
});
|
|
1507
|
-
if (error instanceof HTTPException) throw error;
|
|
1508
|
-
throw new HTTPException(500, {
|
|
1509
|
-
message: 'Internal server error',
|
|
1510
|
-
cause: {
|
|
1511
|
-
code: 'INTERNAL_SERVER_ERROR'
|
|
1512
|
-
}
|
|
1513
|
-
});
|
|
1514
|
-
}
|
|
1515
|
-
};
|
|
1516
|
-
function buildRuntimeDecisionDedupeKey(input) {
|
|
1517
|
-
return [
|
|
1518
|
-
input.tenantId ?? 'default',
|
|
1519
|
-
input.fingerprint,
|
|
1520
|
-
input.matchedBy,
|
|
1521
|
-
input.countryCode ?? 'none',
|
|
1522
|
-
input.regionCode ?? 'none',
|
|
1523
|
-
input.jurisdiction,
|
|
1524
|
-
input.language ?? 'none'
|
|
1525
|
-
].join('|');
|
|
1526
|
-
}
|
|
1527
|
-
function buildDecisionPayload(params) {
|
|
1528
|
-
const { tenantId, snapshot, decision, location, jurisdiction, language, proofConfig } = params;
|
|
1529
|
-
if (snapshot?.valid && snapshot.payload) {
|
|
1530
|
-
const sp = snapshot.payload;
|
|
1531
|
-
return {
|
|
1532
|
-
tenantId,
|
|
1533
|
-
policyId: sp.policyId,
|
|
1534
|
-
fingerprint: sp.fingerprint,
|
|
1535
|
-
matchedBy: sp.matchedBy,
|
|
1536
|
-
countryCode: sp.country,
|
|
1537
|
-
regionCode: sp.region,
|
|
1538
|
-
jurisdiction: sp.jurisdiction,
|
|
1539
|
-
language: sp.language,
|
|
1540
|
-
model: sp.model,
|
|
1541
|
-
policyI18n: sp.policyI18n,
|
|
1542
|
-
uiMode: sp.uiMode,
|
|
1543
|
-
bannerUi: sp.bannerUi,
|
|
1544
|
-
dialogUi: sp.dialogUi,
|
|
1545
|
-
categories: sp.categories,
|
|
1546
|
-
preselectedCategories: sp.preselectedCategories,
|
|
1547
|
-
proofConfig: sp.proofConfig,
|
|
1548
|
-
dedupeKey: buildRuntimeDecisionDedupeKey({
|
|
1549
|
-
tenantId,
|
|
1550
|
-
fingerprint: sp.fingerprint,
|
|
1551
|
-
matchedBy: sp.matchedBy,
|
|
1552
|
-
countryCode: sp.country,
|
|
1553
|
-
regionCode: sp.region,
|
|
1554
|
-
jurisdiction: sp.jurisdiction,
|
|
1555
|
-
language: sp.language
|
|
1556
|
-
}),
|
|
1557
|
-
source: 'snapshot_token'
|
|
1558
|
-
};
|
|
1559
|
-
}
|
|
1560
|
-
if (decision) return {
|
|
1561
|
-
tenantId,
|
|
1562
|
-
policyId: decision.policy.id,
|
|
1563
|
-
fingerprint: decision.fingerprint,
|
|
1564
|
-
matchedBy: decision.matchedBy,
|
|
1565
|
-
countryCode: location.countryCode,
|
|
1566
|
-
regionCode: location.regionCode,
|
|
1567
|
-
jurisdiction,
|
|
1568
|
-
language,
|
|
1569
|
-
model: decision.policy.model,
|
|
1570
|
-
policyI18n: decision.policy.i18n,
|
|
1571
|
-
uiMode: decision.policy.ui?.mode,
|
|
1572
|
-
bannerUi: decision.policy.ui?.banner,
|
|
1573
|
-
dialogUi: decision.policy.ui?.dialog,
|
|
1574
|
-
categories: decision.policy.consent?.categories,
|
|
1575
|
-
preselectedCategories: decision.policy.consent?.preselectedCategories,
|
|
1576
|
-
proofConfig,
|
|
1577
|
-
dedupeKey: buildRuntimeDecisionDedupeKey({
|
|
1578
|
-
tenantId,
|
|
1579
|
-
fingerprint: decision.fingerprint,
|
|
1580
|
-
matchedBy: decision.matchedBy,
|
|
1581
|
-
countryCode: location.countryCode,
|
|
1582
|
-
regionCode: location.regionCode,
|
|
1583
|
-
jurisdiction,
|
|
1584
|
-
language
|
|
1585
|
-
}),
|
|
1586
|
-
source: 'write_time_fallback'
|
|
1587
|
-
};
|
|
1588
|
-
}
|
|
1589
|
-
function parseLanguageFromHeader(header) {
|
|
1590
|
-
if (!header) return;
|
|
1591
|
-
const firstLanguage = header.split(',')[0]?.split(';')[0]?.trim();
|
|
1592
|
-
if (!firstLanguage) return;
|
|
1593
|
-
return firstLanguage.split('-')[0]?.toLowerCase();
|
|
1594
|
-
}
|
|
1595
|
-
function resolveSnapshotFailureMode(ctx) {
|
|
1596
|
-
return ctx.policySnapshot?.onValidationFailure ?? 'reject';
|
|
1597
|
-
}
|
|
1598
|
-
function buildSnapshotHttpException(reason) {
|
|
1599
|
-
switch(reason){
|
|
1600
|
-
case 'missing':
|
|
1601
|
-
return new HTTPException(409, {
|
|
1602
|
-
message: 'Policy snapshot token is required',
|
|
1603
|
-
cause: {
|
|
1604
|
-
code: 'POLICY_SNAPSHOT_REQUIRED'
|
|
1605
|
-
}
|
|
1606
|
-
});
|
|
1607
|
-
case 'expired':
|
|
1608
|
-
return new HTTPException(409, {
|
|
1609
|
-
message: 'Policy snapshot token has expired',
|
|
1610
|
-
cause: {
|
|
1611
|
-
code: 'POLICY_SNAPSHOT_EXPIRED'
|
|
1612
|
-
}
|
|
1613
|
-
});
|
|
1614
|
-
case 'malformed':
|
|
1615
|
-
case 'invalid':
|
|
1616
|
-
return new HTTPException(409, {
|
|
1617
|
-
message: 'Policy snapshot token is invalid',
|
|
1618
|
-
cause: {
|
|
1619
|
-
code: 'POLICY_SNAPSHOT_INVALID'
|
|
1620
|
-
}
|
|
1621
|
-
});
|
|
1622
|
-
default:
|
|
1623
|
-
{
|
|
1624
|
-
const _exhaustive = reason;
|
|
1625
|
-
throw new Error(`Unhandled policy snapshot verification failure reason: ${_exhaustive}`);
|
|
1626
|
-
}
|
|
1627
|
-
}
|
|
1628
|
-
}
|
|
1629
|
-
const postSubjectHandler = async (c)=>{
|
|
1630
|
-
const ctx = c.get('c15tContext');
|
|
1631
|
-
const logger = ctx.logger;
|
|
1632
|
-
logger.info('Handling POST /subjects request');
|
|
1633
|
-
const { db, registry } = ctx;
|
|
1634
|
-
const input = await c.req.json();
|
|
1635
|
-
const { type, subjectId, identityProvider, externalSubjectId, domain, metadata, givenAt: givenAtEpoch } = input;
|
|
1636
|
-
const preferences = 'preferences' in input ? input.preferences : void 0;
|
|
1637
|
-
const givenAt = new Date(givenAtEpoch);
|
|
1638
|
-
const rawConsentAction = 'consentAction' in input ? input.consentAction : void 0;
|
|
1639
|
-
let derivedConsentAction;
|
|
1640
|
-
logger.debug('Request parameters', {
|
|
1641
|
-
type,
|
|
1642
|
-
subjectId,
|
|
1643
|
-
identityProvider,
|
|
1644
|
-
externalSubjectId,
|
|
1645
|
-
domain
|
|
1646
|
-
});
|
|
1647
|
-
try {
|
|
1648
|
-
if ('cookie_banner' === type) logger.warn('`cookie_banner` policy type is deprecated in 2.0 RC and will be removed in 2.0 GA. Use backend runtime `policyPacks` for banner behavior.');
|
|
1649
|
-
const request = c.req.raw ?? new Request('https://c15t.local/subjects');
|
|
1650
|
-
const acceptLanguage = request.headers.get('accept-language');
|
|
1651
|
-
const requestLanguage = parseLanguageFromHeader(acceptLanguage);
|
|
1652
|
-
const location = await getLocation(request, ctx);
|
|
1653
|
-
const resolvedJurisdiction = getJurisdiction(location, ctx);
|
|
1654
|
-
const snapshotVerification = await verifyPolicySnapshotToken({
|
|
1655
|
-
token: input.policySnapshotToken,
|
|
1656
|
-
options: ctx.policySnapshot,
|
|
1657
|
-
tenantId: ctx.tenantId
|
|
1658
|
-
});
|
|
1659
|
-
const hasValidSnapshot = snapshotVerification.valid;
|
|
1660
|
-
const snapshotPayload = snapshotVerification.valid ? snapshotVerification.payload : null;
|
|
1661
|
-
const shouldRequireSnapshot = !!ctx.policySnapshot?.signingKey && 'reject' === resolveSnapshotFailureMode(ctx);
|
|
1662
|
-
if (!hasValidSnapshot && shouldRequireSnapshot) throw buildSnapshotHttpException(snapshotVerification.reason);
|
|
1663
|
-
const resolvedPolicyDecision = hasValidSnapshot ? void 0 : await policy_resolvePolicyDecision({
|
|
1664
|
-
policies: ctx.policyPacks,
|
|
1665
|
-
countryCode: location.countryCode,
|
|
1666
|
-
regionCode: location.regionCode,
|
|
1667
|
-
jurisdiction: resolvedJurisdiction,
|
|
1668
|
-
iabEnabled: ctx.iab?.enabled === true
|
|
1669
|
-
});
|
|
1670
|
-
const effectivePolicy = hasValidSnapshot && snapshotPayload ? {
|
|
1671
|
-
id: snapshotPayload.policyId,
|
|
1672
|
-
model: snapshotPayload.model,
|
|
1673
|
-
i18n: snapshotPayload.policyI18n,
|
|
1674
|
-
consent: {
|
|
1675
|
-
expiryDays: snapshotPayload.expiryDays,
|
|
1676
|
-
scopeMode: snapshotPayload.scopeMode,
|
|
1677
|
-
categories: snapshotPayload.categories,
|
|
1678
|
-
preselectedCategories: snapshotPayload.preselectedCategories,
|
|
1679
|
-
gpc: snapshotPayload.gpc
|
|
1680
|
-
},
|
|
1681
|
-
ui: {
|
|
1682
|
-
mode: snapshotPayload.uiMode,
|
|
1683
|
-
banner: snapshotPayload.bannerUi,
|
|
1684
|
-
dialog: snapshotPayload.dialogUi
|
|
1685
|
-
},
|
|
1686
|
-
proof: snapshotPayload.proofConfig
|
|
1687
|
-
} : resolvedPolicyDecision?.policy;
|
|
1688
|
-
const effectiveModel = effectivePolicy?.model ?? ('opt-in' === input.jurisdictionModel || 'opt-out' === input.jurisdictionModel || 'iab' === input.jurisdictionModel ? input.jurisdictionModel : void 0);
|
|
1689
|
-
if ('all' === rawConsentAction) derivedConsentAction = 'accept_all';
|
|
1690
|
-
else if ('necessary' === rawConsentAction) derivedConsentAction = 'opt-out' === effectiveModel ? 'opt_out' : 'reject_all';
|
|
1691
|
-
else if ('custom' === rawConsentAction) derivedConsentAction = 'custom';
|
|
1692
|
-
const subject = await registry.findOrCreateSubject({
|
|
1693
|
-
subjectId,
|
|
1694
|
-
externalSubjectId,
|
|
1695
|
-
identityProvider,
|
|
1696
|
-
ipAddress: ctx.ipAddress
|
|
1697
|
-
});
|
|
1698
|
-
if (!subject) throw new HTTPException(500, {
|
|
1699
|
-
message: 'Failed to create subject',
|
|
1700
|
-
cause: {
|
|
1701
|
-
code: 'SUBJECT_CREATION_FAILED',
|
|
1702
|
-
subjectId
|
|
1703
|
-
}
|
|
1704
|
-
});
|
|
1705
|
-
logger.debug('Subject found/created', {
|
|
1706
|
-
subjectId: subject.id
|
|
1707
|
-
});
|
|
1708
|
-
const domainRecord = await registry.findOrCreateDomain(domain);
|
|
1709
|
-
if (!domainRecord) throw new HTTPException(500, {
|
|
1710
|
-
message: 'Failed to create domain',
|
|
1711
|
-
cause: {
|
|
1712
|
-
code: 'DOMAIN_CREATION_FAILED',
|
|
1713
|
-
domain
|
|
1714
|
-
}
|
|
1715
|
-
});
|
|
1716
|
-
let policyId;
|
|
1717
|
-
let purposeIds = [];
|
|
1718
|
-
let appliedPreferences;
|
|
1719
|
-
const inputPolicyId = 'policyId' in input ? input.policyId : void 0;
|
|
1720
|
-
if (inputPolicyId) {
|
|
1721
|
-
policyId = inputPolicyId;
|
|
1722
|
-
const policy = await registry.findConsentPolicyById(inputPolicyId);
|
|
1723
|
-
if (!policy) throw new HTTPException(404, {
|
|
1724
|
-
message: 'Policy not found',
|
|
1725
|
-
cause: {
|
|
1726
|
-
code: 'POLICY_NOT_FOUND',
|
|
1727
|
-
policyId,
|
|
1728
|
-
type
|
|
1729
|
-
}
|
|
1730
|
-
});
|
|
1731
|
-
if (!policy.isActive) throw new HTTPException(400, {
|
|
1732
|
-
message: 'Policy is inactive',
|
|
1733
|
-
cause: {
|
|
1734
|
-
code: 'POLICY_INACTIVE',
|
|
1735
|
-
policyId,
|
|
1736
|
-
type
|
|
1737
|
-
}
|
|
1738
|
-
});
|
|
1739
|
-
} else {
|
|
1740
|
-
const policy = await registry.findOrCreatePolicy(type);
|
|
1741
|
-
if (!policy) throw new HTTPException(500, {
|
|
1742
|
-
message: 'Failed to create policy',
|
|
1743
|
-
cause: {
|
|
1744
|
-
code: 'POLICY_CREATION_FAILED',
|
|
1745
|
-
type
|
|
1746
|
-
}
|
|
1747
|
-
});
|
|
1748
|
-
policyId = policy.id;
|
|
1749
|
-
}
|
|
1750
|
-
if (preferences) {
|
|
1751
|
-
const allowedCategories = effectivePolicy?.consent?.categories;
|
|
1752
|
-
const effectiveScopeMode = effectivePolicy?.consent?.scopeMode ?? 'permissive';
|
|
1753
|
-
const hasWildcardCategoryScope = allowedCategories?.includes('*') === true;
|
|
1754
|
-
const appliedPreferenceEntries = Object.entries(preferences);
|
|
1755
|
-
let filteredAppliedPreferenceEntries = appliedPreferenceEntries;
|
|
1756
|
-
if (allowedCategories && allowedCategories.length > 0 && !hasWildcardCategoryScope) {
|
|
1757
|
-
const disallowed = appliedPreferenceEntries.map(([purpose])=>purpose).filter((purpose)=>!allowedCategories.includes(purpose));
|
|
1758
|
-
filteredAppliedPreferenceEntries = appliedPreferenceEntries.filter(([purpose])=>allowedCategories.includes(purpose));
|
|
1759
|
-
if (disallowed.length > 0 && 'strict' === effectiveScopeMode) throw new HTTPException(400, {
|
|
1760
|
-
message: 'Preferences include categories not allowed by policy',
|
|
1761
|
-
cause: {
|
|
1762
|
-
code: 'PURPOSE_NOT_ALLOWED',
|
|
1763
|
-
disallowed
|
|
1764
|
-
}
|
|
1765
|
-
});
|
|
1766
|
-
}
|
|
1767
|
-
appliedPreferences = Object.fromEntries(filteredAppliedPreferenceEntries);
|
|
1768
|
-
const filteredConsentedPurposeCodes = filteredAppliedPreferenceEntries.filter(([_, isConsented])=>isConsented).map(([purposeCode])=>purposeCode);
|
|
1769
|
-
logger.debug('Consented purposes', {
|
|
1770
|
-
consentedPurposes: filteredConsentedPurposeCodes
|
|
1771
|
-
});
|
|
1772
|
-
const purposesRaw = await Promise.all(filteredConsentedPurposeCodes.map((purposeCode)=>registry.findOrCreateConsentPurposeByCode(purposeCode)));
|
|
1773
|
-
const purposes = purposesRaw.map((purpose)=>purpose?.id ?? null).filter((id)=>Boolean(id));
|
|
1774
|
-
logger.debug('Filtered purposes', {
|
|
1775
|
-
purposes
|
|
1776
|
-
});
|
|
1777
|
-
if (0 === purposes.length) logger.warn('No valid purpose IDs found after filtering. Using empty list.', {
|
|
1778
|
-
consentedPurposes: filteredConsentedPurposeCodes
|
|
1779
|
-
});
|
|
1780
|
-
purposeIds = purposes;
|
|
1781
|
-
}
|
|
1782
|
-
const expiryDays = effectivePolicy?.consent?.expiryDays;
|
|
1783
|
-
const validUntil = 'number' == typeof expiryDays && Number.isFinite(expiryDays) ? new Date(givenAt.getTime() + 86400000 * Math.max(0, expiryDays)) : void 0;
|
|
1784
|
-
const proofConfig = effectivePolicy?.proof;
|
|
1785
|
-
const shouldStoreIp = proofConfig?.storeIp ?? true;
|
|
1786
|
-
const shouldStoreUserAgent = proofConfig?.storeUserAgent ?? true;
|
|
1787
|
-
const shouldStoreLanguage = proofConfig?.storeLanguage ?? false;
|
|
1788
|
-
const effectiveLanguage = (snapshotPayload?.language && hasValidSnapshot ? snapshotPayload.language : requestLanguage) ?? void 0;
|
|
1789
|
-
const metadataWithPolicy = {
|
|
1790
|
-
...metadata ?? {},
|
|
1791
|
-
...shouldStoreLanguage && effectiveLanguage ? {
|
|
1792
|
-
policyLanguage: effectiveLanguage
|
|
1793
|
-
} : {}
|
|
1794
|
-
};
|
|
1795
|
-
const effectiveJurisdiction = hasValidSnapshot && snapshotPayload ? snapshotPayload.jurisdiction : resolvedJurisdiction;
|
|
1796
|
-
const decisionPayload = buildDecisionPayload({
|
|
1797
|
-
tenantId: ctx.tenantId,
|
|
1798
|
-
snapshot: hasValidSnapshot && snapshotPayload ? {
|
|
1799
|
-
valid: true,
|
|
1800
|
-
payload: snapshotPayload
|
|
1801
|
-
} : null,
|
|
1802
|
-
decision: resolvedPolicyDecision,
|
|
1803
|
-
location: {
|
|
1804
|
-
countryCode: location.countryCode,
|
|
1805
|
-
regionCode: location.regionCode
|
|
1806
|
-
},
|
|
1807
|
-
jurisdiction: resolvedJurisdiction,
|
|
1808
|
-
language: effectiveLanguage,
|
|
1809
|
-
proofConfig
|
|
1810
|
-
});
|
|
1811
|
-
const existingConsent = await db.findFirst('consent', {
|
|
1812
|
-
where: (b)=>b.and(b('subjectId', '=', subject.id), b('domainId', '=', domainRecord.id), b('policyId', '=', policyId), b('givenAt', '=', givenAt))
|
|
1813
|
-
});
|
|
1814
|
-
if (existingConsent) {
|
|
1815
|
-
logger.debug('Duplicate consent detected, returning existing record', {
|
|
1816
|
-
consentId: existingConsent.id
|
|
1817
|
-
});
|
|
1818
|
-
return c.json({
|
|
1819
|
-
subjectId: subject.id,
|
|
1820
|
-
consentId: existingConsent.id,
|
|
1821
|
-
domainId: domainRecord.id,
|
|
1822
|
-
domain: domainRecord.name,
|
|
1823
|
-
type,
|
|
1824
|
-
metadata,
|
|
1825
|
-
appliedPreferences,
|
|
1826
|
-
uiSource: input.uiSource,
|
|
1827
|
-
givenAt: existingConsent.givenAt
|
|
1828
|
-
});
|
|
1829
|
-
}
|
|
1830
|
-
const result = await db.transaction(async (tx)=>{
|
|
1831
|
-
logger.debug('Creating consent record', {
|
|
1832
|
-
subjectId: subject.id,
|
|
1833
|
-
domainId: domainRecord.id,
|
|
1834
|
-
policyId,
|
|
1835
|
-
purposeIds
|
|
1836
|
-
});
|
|
1837
|
-
const runtimePolicyDecision = decisionPayload ? await tx.findFirst('runtimePolicyDecision', {
|
|
1838
|
-
where: (b)=>b('dedupeKey', '=', decisionPayload.dedupeKey)
|
|
1839
|
-
}) ?? await tx.create('runtimePolicyDecision', {
|
|
1840
|
-
id: `rpd_${crypto.randomUUID().replaceAll('-', '')}`,
|
|
1841
|
-
tenantId: decisionPayload.tenantId,
|
|
1842
|
-
policyId: decisionPayload.policyId,
|
|
1843
|
-
fingerprint: decisionPayload.fingerprint,
|
|
1844
|
-
matchedBy: decisionPayload.matchedBy,
|
|
1845
|
-
countryCode: decisionPayload.countryCode,
|
|
1846
|
-
regionCode: decisionPayload.regionCode,
|
|
1847
|
-
jurisdiction: decisionPayload.jurisdiction,
|
|
1848
|
-
language: decisionPayload.language,
|
|
1849
|
-
model: decisionPayload.model,
|
|
1850
|
-
policyI18n: decisionPayload.policyI18n ? {
|
|
1851
|
-
json: decisionPayload.policyI18n
|
|
1852
|
-
} : void 0,
|
|
1853
|
-
uiMode: decisionPayload.uiMode,
|
|
1854
|
-
bannerUi: decisionPayload.bannerUi ? {
|
|
1855
|
-
json: decisionPayload.bannerUi
|
|
1856
|
-
} : void 0,
|
|
1857
|
-
dialogUi: decisionPayload.dialogUi ? {
|
|
1858
|
-
json: decisionPayload.dialogUi
|
|
1859
|
-
} : void 0,
|
|
1860
|
-
categories: decisionPayload.categories ? {
|
|
1861
|
-
json: decisionPayload.categories
|
|
1862
|
-
} : void 0,
|
|
1863
|
-
preselectedCategories: decisionPayload.preselectedCategories ? {
|
|
1864
|
-
json: decisionPayload.preselectedCategories
|
|
1865
|
-
} : void 0,
|
|
1866
|
-
proofConfig: decisionPayload.proofConfig ? {
|
|
1867
|
-
json: decisionPayload.proofConfig
|
|
1868
|
-
} : void 0,
|
|
1869
|
-
dedupeKey: decisionPayload.dedupeKey
|
|
1870
|
-
}).catch(async ()=>tx.findFirst('runtimePolicyDecision', {
|
|
1871
|
-
where: (b)=>b('dedupeKey', '=', decisionPayload.dedupeKey)
|
|
1872
|
-
})) : void 0;
|
|
1873
|
-
const consentRecord = await tx.create('consent', {
|
|
1874
|
-
id: await generateUniqueId(tx, 'consent', ctx),
|
|
1875
|
-
subjectId: subject.id,
|
|
1876
|
-
domainId: domainRecord.id,
|
|
1877
|
-
policyId,
|
|
1878
|
-
purposeIds: {
|
|
1879
|
-
json: purposeIds
|
|
1880
|
-
},
|
|
1881
|
-
metadata: Object.keys(metadataWithPolicy).length > 0 ? {
|
|
1882
|
-
json: metadataWithPolicy
|
|
1883
|
-
} : void 0,
|
|
1884
|
-
ipAddress: shouldStoreIp ? ctx.ipAddress : null,
|
|
1885
|
-
userAgent: shouldStoreUserAgent ? ctx.userAgent : null,
|
|
1886
|
-
jurisdiction: effectiveJurisdiction,
|
|
1887
|
-
jurisdictionModel: effectiveModel,
|
|
1888
|
-
tcString: input.tcString,
|
|
1889
|
-
uiSource: input.uiSource,
|
|
1890
|
-
consentAction: derivedConsentAction,
|
|
1891
|
-
givenAt,
|
|
1892
|
-
validUntil,
|
|
1893
|
-
runtimePolicyDecisionId: runtimePolicyDecision?.id,
|
|
1894
|
-
runtimePolicySource: decisionPayload?.source
|
|
1895
|
-
});
|
|
1896
|
-
logger.debug('Created consent', {
|
|
1897
|
-
consentRecord: consentRecord.id
|
|
1898
|
-
});
|
|
1899
|
-
if (!consentRecord) throw new HTTPException(500, {
|
|
1900
|
-
message: 'Failed to create consent',
|
|
1901
|
-
cause: {
|
|
1902
|
-
code: 'CONSENT_CREATION_FAILED',
|
|
1903
|
-
subjectId: subject.id,
|
|
1904
|
-
domain
|
|
1905
|
-
}
|
|
1906
|
-
});
|
|
1907
|
-
return {
|
|
1908
|
-
consent: consentRecord
|
|
1909
|
-
};
|
|
1910
|
-
});
|
|
1911
|
-
const metrics = getMetrics();
|
|
1912
|
-
if (metrics) {
|
|
1913
|
-
const jurisdiction = effectiveJurisdiction;
|
|
1914
|
-
metrics.recordConsentCreated({
|
|
1915
|
-
type,
|
|
1916
|
-
jurisdiction
|
|
1917
|
-
});
|
|
1918
|
-
const hasAccepted = preferences && Object.values(preferences).some(Boolean);
|
|
1919
|
-
if (hasAccepted) metrics.recordConsentAccepted({
|
|
1920
|
-
type,
|
|
1921
|
-
jurisdiction
|
|
1922
|
-
});
|
|
1923
|
-
else metrics.recordConsentRejected({
|
|
1924
|
-
type,
|
|
1925
|
-
jurisdiction
|
|
1926
|
-
});
|
|
1927
|
-
}
|
|
1928
|
-
return c.json({
|
|
1929
|
-
subjectId: subject.id,
|
|
1930
|
-
consentId: result.consent.id,
|
|
1931
|
-
domainId: domainRecord.id,
|
|
1932
|
-
domain: domainRecord.name,
|
|
1933
|
-
type,
|
|
1934
|
-
metadata,
|
|
1935
|
-
appliedPreferences,
|
|
1936
|
-
uiSource: input.uiSource,
|
|
1937
|
-
givenAt: result.consent.givenAt
|
|
1938
|
-
});
|
|
1939
|
-
} catch (error) {
|
|
1940
|
-
logger.error('Error in POST /subjects handler', {
|
|
1941
|
-
error: extractErrorMessage(error),
|
|
1942
|
-
errorType: error instanceof Error ? error.constructor.name : typeof error
|
|
1943
|
-
});
|
|
1944
|
-
if (error instanceof HTTPException) throw error;
|
|
1945
|
-
throw new HTTPException(500, {
|
|
1946
|
-
message: 'Internal server error',
|
|
1947
|
-
cause: {
|
|
1948
|
-
code: 'INTERNAL_SERVER_ERROR'
|
|
1949
|
-
}
|
|
1950
|
-
});
|
|
1951
|
-
}
|
|
1952
|
-
};
|
|
1953
|
-
const createSubjectRoutes = ()=>{
|
|
1954
|
-
const app = new Hono();
|
|
1955
|
-
app.get('/:id', describeRoute({
|
|
1956
|
-
summary: 'Get subject consent status',
|
|
1957
|
-
description: `Returns the subject's consent status for this device. Use to check if the subject has valid consent for given policy types.
|
|
1958
|
-
|
|
1959
|
-
**Query:** \`type\` – Filter by consent type(s), comma-separated (e.g. \`privacy_policy,cookie_banner\`).
|
|
1960
|
-
|
|
1961
|
-
**Response:** \`subject\`, \`consents\` (matching filter), \`isValid\` (valid consent for requested type(s)).`,
|
|
1962
|
-
tags: [
|
|
1963
|
-
'Subject',
|
|
1964
|
-
'Consent'
|
|
1965
|
-
],
|
|
1966
|
-
responses: {
|
|
1967
|
-
200: {
|
|
1968
|
-
description: 'Subject and consent records for the requested type(s)',
|
|
1969
|
-
content: {
|
|
1970
|
-
'application/json': {
|
|
1971
|
-
schema: resolver(getSubjectOutputSchema)
|
|
1972
|
-
}
|
|
1973
|
-
}
|
|
1974
|
-
},
|
|
1975
|
-
404: {
|
|
1976
|
-
description: 'Subject not found for the given ID'
|
|
1977
|
-
}
|
|
1978
|
-
}
|
|
1979
|
-
}), validator('param', getSubjectInputSchema), getSubjectHandler);
|
|
1980
|
-
app.post('/', describeRoute({
|
|
1981
|
-
summary: 'Record consent for a subject',
|
|
1982
|
-
description: `Creates a new consent record (append-only). Creates the subject if it does not exist.
|
|
1983
|
-
|
|
1984
|
-
**Request body by \`type\`:**
|
|
1985
|
-
- \`cookie_banner\` – Requires \`preferences\` object
|
|
1986
|
-
- \`privacy_policy\`, \`dpa\`, \`terms_and_conditions\` – Optional \`policyId\`
|
|
1987
|
-
- \`marketing_communications\`, \`age_verification\`, \`other\` – Optional \`preferences\``,
|
|
1988
|
-
tags: [
|
|
1989
|
-
'Subject',
|
|
1990
|
-
'Consent'
|
|
1991
|
-
],
|
|
1992
|
-
responses: {
|
|
1993
|
-
200: {
|
|
1994
|
-
description: 'Consent recorded; subject and consent in response',
|
|
1995
|
-
content: {
|
|
1996
|
-
'application/json': {
|
|
1997
|
-
schema: resolver(postSubjectOutputSchema)
|
|
1998
|
-
}
|
|
1999
|
-
}
|
|
2000
|
-
},
|
|
2001
|
-
422: {
|
|
2002
|
-
description: 'Invalid request body (schema or validation failed)'
|
|
2003
|
-
}
|
|
2004
|
-
}
|
|
2005
|
-
}), validator('json', postSubjectInputSchema), postSubjectHandler);
|
|
2006
|
-
app.patch('/:id', describeRoute({
|
|
2007
|
-
summary: 'Link external ID to subject',
|
|
2008
|
-
description: 'Associates an external user ID with an existing subject (e.g. after login). Enables cross-device consent sync.',
|
|
2009
|
-
tags: [
|
|
2010
|
-
'Subject'
|
|
2011
|
-
],
|
|
2012
|
-
responses: {
|
|
2013
|
-
200: {
|
|
2014
|
-
description: 'Subject updated with external ID',
|
|
2015
|
-
content: {
|
|
2016
|
-
'application/json': {
|
|
2017
|
-
schema: resolver(patchSubjectOutputSchema)
|
|
2018
|
-
}
|
|
2019
|
-
}
|
|
2020
|
-
},
|
|
2021
|
-
404: {
|
|
2022
|
-
description: 'Subject not found for the given ID'
|
|
2023
|
-
}
|
|
2024
|
-
}
|
|
2025
|
-
}), validator('param', object({
|
|
2026
|
-
id: subjectIdSchema
|
|
2027
|
-
})), validator('json', object({
|
|
2028
|
-
externalId: string(),
|
|
2029
|
-
identityProvider: optional(string())
|
|
2030
|
-
})), patchSubjectHandler);
|
|
2031
|
-
app.get('/', describeRoute({
|
|
2032
|
-
summary: 'List subjects by external ID (API key required)',
|
|
2033
|
-
description: 'Returns all subjects linked to the given external ID. Requires Bearer token (API key). Use for server-side consent lookups.',
|
|
2034
|
-
tags: [
|
|
2035
|
-
'Subject'
|
|
2036
|
-
],
|
|
2037
|
-
security: [
|
|
2038
|
-
{
|
|
2039
|
-
bearerAuth: []
|
|
2040
|
-
}
|
|
2041
|
-
],
|
|
2042
|
-
responses: {
|
|
2043
|
-
200: {
|
|
2044
|
-
description: 'List of subjects for the external ID',
|
|
2045
|
-
content: {
|
|
2046
|
-
'application/json': {
|
|
2047
|
-
schema: resolver(listSubjectsOutputSchema)
|
|
2048
|
-
}
|
|
2049
|
-
}
|
|
2050
|
-
},
|
|
2051
|
-
401: {
|
|
2052
|
-
description: 'Missing or invalid API key'
|
|
2053
|
-
}
|
|
2054
|
-
}
|
|
2055
|
-
}), validator('query', listSubjectsQuerySchema), listSubjectsHandler);
|
|
2056
|
-
return app;
|
|
2057
|
-
};
|
|
2058
|
-
export { createConsentRoutes, createInitRoute, createStatusRoute, createSubjectRoutes };
|
|
1
|
+
export { createConsentRoutes, createInitRoute, createStatusRoute, createSubjectRoutes } from "./364.js";
|