geo-engine-node 2.0.0 → 3.0.0-rc.1

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.
@@ -0,0 +1,473 @@
1
+ /**
2
+ * Source used to capture the device location signal.
3
+ */
4
+ type LocationSource = 'device' | 'ip' | 'wifi' | 'cell' | 'manual' | (string & {});
5
+ /**
6
+ * Geographic location signal sent in the evaluation context.
7
+ */
8
+ interface IdentityLocation {
9
+ lat: number;
10
+ lng: number;
11
+ accuracy_m?: number;
12
+ source?: LocationSource;
13
+ captured_at?: string;
14
+ }
15
+ /**
16
+ * Request context signals evaluated against the scope rules.
17
+ */
18
+ interface IdentityContext {
19
+ ip?: string;
20
+ location?: IdentityLocation;
21
+ }
22
+ /**
23
+ * Subject attempting access. All identifiers are opaque client-defined strings.
24
+ * At least one of `user_id` or `device_id` is required.
25
+ */
26
+ type IdentitySubject = {
27
+ user_id: string;
28
+ device_id?: string;
29
+ roles?: string[];
30
+ } | {
31
+ user_id?: string;
32
+ device_id: string;
33
+ roles?: string[];
34
+ };
35
+ /**
36
+ * Request body for POST /v1/evaluate.
37
+ */
38
+ interface EvaluateRequest {
39
+ scope: string;
40
+ subject: IdentitySubject;
41
+ context?: IdentityContext;
42
+ }
43
+ /**
44
+ * Per-call options for `client.identity.evaluate`.
45
+ */
46
+ interface EvaluateOptions {
47
+ /** Total deadline in milliseconds for this evaluation, including any retry. Default: 500ms. */
48
+ timeoutMs?: number;
49
+ /** Optional correlation ID sent as X-Request-Id (max 128 chars, no control chars). */
50
+ requestId?: string;
51
+ /** Optional external AbortSignal to cancel the evaluation. */
52
+ signal?: AbortSignal;
53
+ }
54
+ type KnownDecision = 'ALLOW' | 'BLOCK' | 'CHALLENGE';
55
+ type Decision = KnownDecision | (string & {});
56
+ type EvaluateReason = 'RULE_MATCH' | 'DEFAULT_ACTION' | (string & {});
57
+ type KnownSignal = 'outside_geo_limit' | 'location_missing' | 'ip_blocklist' | 'ip_not_allowlist' | 'datacenter_ip' | 'tor_exit';
58
+ /**
59
+ * Open set of signals returned by /v1/evaluate.
60
+ */
61
+ type EvaluateSignal = KnownSignal | (string & {});
62
+ interface RuleRef {
63
+ id: string;
64
+ name: string;
65
+ priority: number;
66
+ }
67
+ interface ShadowMatch {
68
+ rule: RuleRef;
69
+ would_decide: Decision;
70
+ signals?: EvaluateSignal[];
71
+ }
72
+ interface Challenge {
73
+ hint?: 'step_up' | (string & {});
74
+ }
75
+ type MetaSource = 'postgres' | 'redis' | 'memory' | 'snapshot' | 'fallback' | 'sdk_fallback' | (string & {});
76
+ type ReputationStatus = 'not_needed' | 'ok' | 'unavailable' | (string & {});
77
+ interface EvaluateMeta {
78
+ config_version: number;
79
+ stale: boolean;
80
+ config_age_s: number;
81
+ source: MetaSource;
82
+ evaluated_at: string;
83
+ request_id?: string;
84
+ reputation?: ReputationStatus;
85
+ }
86
+ /**
87
+ * Response from POST /v1/evaluate.
88
+ */
89
+ interface EvaluateResponse {
90
+ decision: Decision;
91
+ matched_rule: RuleRef | null;
92
+ default_applied: boolean;
93
+ reason: EvaluateReason;
94
+ signals: EvaluateSignal[];
95
+ shadow_matches: ShadowMatch[];
96
+ challenge?: Challenge;
97
+ meta: EvaluateMeta;
98
+ }
99
+ type IdentityTransientReason = 'timeout' | 'network' | 'server_error' | 'rate_limited';
100
+ type FallbackReason = IdentityTransientReason | 'unknown_decision';
101
+ type IdentityIntegrationReason = 'invalid_request' | 'malformed_request' | 'unauthorized' | 'edge_forbidden' | 'forbidden' | 'not_found' | 'scope_not_found' | 'client_error' | 'unexpected_response' | 'configuration_error';
102
+ /**
103
+ * Synthetic decision produced locally by `identityGuard` when a transient failure
104
+ * or unknown decision triggers the `failOpen` fallback policy.
105
+ */
106
+ interface FallbackDecision {
107
+ decision: 'ALLOW' | 'BLOCK';
108
+ matched_rule: null;
109
+ default_applied: false;
110
+ reason: 'SDK_FALLBACK';
111
+ signals: EvaluateSignal[];
112
+ shadow_matches: ShadowMatch[];
113
+ fallback: true;
114
+ fallback_reason: FallbackReason;
115
+ meta: EvaluateMeta & {
116
+ source: 'sdk_fallback';
117
+ };
118
+ }
119
+ type IdentityDecision = EvaluateResponse | FallbackDecision;
120
+ interface GuardRequest {
121
+ headers?: Record<string, string | string[] | undefined>;
122
+ ip?: string;
123
+ socket?: {
124
+ remoteAddress?: string;
125
+ };
126
+ [key: string]: unknown;
127
+ }
128
+ interface GuardResponse {
129
+ headersSent?: boolean;
130
+ writableEnded?: boolean;
131
+ statusCode: number;
132
+ status?: (code: number) => {
133
+ json?: (body: unknown) => unknown;
134
+ end?: (chunk?: string) => unknown;
135
+ };
136
+ json?: (body: unknown) => unknown;
137
+ setHeader?: (name: string, value: string) => unknown;
138
+ end?: (chunk?: string) => unknown;
139
+ [key: string]: unknown;
140
+ }
141
+ type NextFunction = (err?: unknown) => void;
142
+ type IdentityGuardClient = {
143
+ identity: {
144
+ evaluate(request: EvaluateRequest, options?: EvaluateOptions): Promise<EvaluateResponse>;
145
+ };
146
+ } | {
147
+ evaluate(request: EvaluateRequest, options?: EvaluateOptions): Promise<EvaluateResponse>;
148
+ };
149
+ /**
150
+ * Configuration options for `identityGuard`.
151
+ * `failOpen` is mandatory and has no default value.
152
+ */
153
+ interface IdentityGuardOptions<Req extends GuardRequest = GuardRequest, Res extends GuardResponse = GuardResponse> {
154
+ client: IdentityGuardClient;
155
+ scope: string;
156
+ getSubject: (req: Req) => IdentitySubject | Promise<IdentitySubject>;
157
+ /**
158
+ * Provides request context (`ip`, `location`). If the scope has geographic rules and
159
+ * `location` is omitted, the engine returns HTTP 200 with signal `location_missing`
160
+ * (which may result in BLOCK depending on the rule).
161
+ */
162
+ getContext?: (req: Req) => IdentityContext | undefined | Promise<IdentityContext | undefined>;
163
+ /**
164
+ * Mandatory local fallback policy on transient errors or unknown decisions.
165
+ * `true` allows access on transient failure; `false` blocks (HTTP 403).
166
+ * Integration errors NEVER apply `failOpen`.
167
+ */
168
+ failOpen: boolean;
169
+ timeoutMs?: number;
170
+ onChallenge?: (decision: EvaluateResponse, req: Req, res: Res, next: NextFunction) => void | Promise<void>;
171
+ onBlock?: (decision: IdentityDecision, req: Req, res: Res, next: NextFunction) => void | Promise<void>;
172
+ onDecision?: (decision: IdentityDecision, req: Req) => void | Promise<void>;
173
+ onIntegrationError?: (error: unknown, req: Req, res: Res, next: NextFunction) => void | Promise<void>;
174
+ }
175
+
176
+ interface IdentityServiceConfig {
177
+ getBaseUrl: () => string;
178
+ getApiKey: () => string;
179
+ getTimeoutMs: () => number;
180
+ getFetch: () => (...args: any[]) => Promise<any>;
181
+ isClosed: () => boolean;
182
+ }
183
+ /**
184
+ * Evaluates contextual access policies via `POST /v1/evaluate` (server-only).
185
+ */
186
+ declare class IdentityService {
187
+ #private;
188
+ constructor(config: IdentityServiceConfig);
189
+ toJSON(): Record<string, unknown>;
190
+ /**
191
+ * Calls `POST /v1/evaluate` with Bearer authentication, X-Request-Id tracking,
192
+ * a total deadline (default 500ms), and at most one retry for transient failures.
193
+ * Never applies `failOpen` directly; throws typed transient or integration errors.
194
+ */
195
+ evaluate(request: EvaluateRequest, options?: EvaluateOptions): Promise<EvaluateResponse>;
196
+ }
197
+
198
+ /**
199
+ * Detailed error metadata returned by GeoEngine api-service.
200
+ */
201
+ interface SpatialErrorDetail {
202
+ '@type'?: string;
203
+ reason?: string;
204
+ domain?: string;
205
+ metadata?: Record<string, string>;
206
+ }
207
+ /**
208
+ * Base error class for all GeoEngine SDK exceptions.
209
+ */
210
+ declare class GeoEngineError extends Error {
211
+ constructor(message: string);
212
+ }
213
+ /**
214
+ * Error thrown when an operation is attempted on a closed client instance.
215
+ * Equivalent to Go's ErrClientClosed.
216
+ */
217
+ declare class ClientClosedError extends GeoEngineError {
218
+ constructor(message?: string);
219
+ }
220
+ /**
221
+ * Error thrown when a client-side parameter validation fails.
222
+ */
223
+ declare class ValidationError extends GeoEngineError {
224
+ constructor(message: string);
225
+ }
226
+ /**
227
+ * Error thrown when device_id is missing or empty.
228
+ * Equivalent to Go's ErrDeviceIDRequired.
229
+ */
230
+ declare class DeviceIDRequiredError extends ValidationError {
231
+ constructor(message?: string);
232
+ }
233
+ /**
234
+ * Error thrown when a geofence_id is missing or empty.
235
+ * Equivalent to Go's ErrGeofenceIDRequired.
236
+ */
237
+ declare class GeofenceIDRequiredError extends ValidationError {
238
+ constructor(message?: string);
239
+ }
240
+ /**
241
+ * Error thrown when latitude falls outside the valid range [-90, 90].
242
+ * Equivalent to Go's ErrInvalidLatitude.
243
+ */
244
+ declare class InvalidLatitudeError extends ValidationError {
245
+ constructor(message?: string);
246
+ }
247
+ /**
248
+ * Error thrown when longitude falls outside the valid range [-180, 180].
249
+ * Equivalent to Go's ErrInvalidLongitude.
250
+ */
251
+ declare class InvalidLongitudeError extends ValidationError {
252
+ constructor(message?: string);
253
+ }
254
+ /**
255
+ * Error thrown when coordinate polygon validation fails.
256
+ * Equivalent to Go's ErrInvalidCoordinates.
257
+ */
258
+ declare class InvalidCoordinatesError extends ValidationError {
259
+ constructor(message?: string);
260
+ }
261
+ /**
262
+ * Represents an HTTP error returned by the GeoEngine REST or Management API.
263
+ * Equivalent to Go's APIError.
264
+ */
265
+ declare class APIError extends GeoEngineError {
266
+ readonly statusCode: number;
267
+ constructor(statusCode: number, message: string);
268
+ }
269
+ /**
270
+ * Represents a structured error returned by GeoEngine api-service.
271
+ * Equivalent to Go's SpatialAPIError.
272
+ */
273
+ declare class SpatialAPIError extends APIError {
274
+ readonly code: string;
275
+ readonly statusText?: string;
276
+ readonly details: SpatialErrorDetail[];
277
+ constructor(statusCode: number, code: string, message: string, statusText?: string, details?: SpatialErrorDetail[]);
278
+ /**
279
+ * Returns true if the error indicates the geofence or resource was not found.
280
+ */
281
+ isNotFound(): boolean;
282
+ /**
283
+ * Returns true if the error indicates quota limit was hit.
284
+ */
285
+ isQuotaExceeded(): boolean;
286
+ /**
287
+ * Returns true if authentication failed.
288
+ */
289
+ isUnauthorized(): boolean;
290
+ /**
291
+ * Returns true if access to the requested resource is forbidden.
292
+ */
293
+ isForbidden(): boolean;
294
+ }
295
+ /**
296
+ * Specific error thrown when a geofence is not found (204 or 404).
297
+ * Equivalent to Go's ErrGeofenceNotFound.
298
+ */
299
+ declare class GeofenceNotFoundError extends SpatialAPIError {
300
+ constructor(message?: string, statusCode?: number, details?: SpatialErrorDetail[]);
301
+ }
302
+ /**
303
+ * Specific error thrown when request quota limit is exceeded (HTTP 402 or 429).
304
+ * Equivalent to Go's ErrQuotaExceeded.
305
+ */
306
+ declare class QuotaExceededError extends SpatialAPIError {
307
+ constructor(message?: string, statusCode?: number, details?: SpatialErrorDetail[]);
308
+ }
309
+ /**
310
+ * Specific error thrown when API authentication fails (HTTP 401).
311
+ * Equivalent to Go's ErrUnauthorized.
312
+ */
313
+ declare class AuthenticationError extends SpatialAPIError {
314
+ constructor(message?: string, statusCode?: number, details?: SpatialErrorDetail[]);
315
+ }
316
+ /**
317
+ * Specific error thrown when access is forbidden (HTTP 403).
318
+ * Equivalent to Go's ErrForbidden.
319
+ */
320
+ declare class ForbiddenError extends SpatialAPIError {
321
+ constructor(message?: string, statusCode?: number, details?: SpatialErrorDetail[]);
322
+ }
323
+ /**
324
+ * Error thrown when a network request exceeds its deadline or timeout limit.
325
+ */
326
+ declare class TimeoutError extends GeoEngineError {
327
+ constructor(timeoutMs: number);
328
+ }
329
+ /**
330
+ * Error thrown when a user ID is missing or empty.
331
+ * Equivalent to Go's ErrUserIDRequired.
332
+ */
333
+ declare class UserIDRequiredError extends ValidationError {
334
+ constructor(message?: string);
335
+ }
336
+ /**
337
+ * Error thrown when a GeoIdentity rule ID is missing or empty.
338
+ * Equivalent to Go's ErrRuleIDRequired.
339
+ */
340
+ declare class RuleIDRequiredError extends ValidationError {
341
+ constructor(message?: string);
342
+ }
343
+ /**
344
+ * Error thrown when a GeoIdentity rule name is missing or empty.
345
+ * Equivalent to Go's ErrRuleNameRequired.
346
+ */
347
+ declare class RuleNameRequiredError extends ValidationError {
348
+ constructor(message?: string);
349
+ }
350
+ /**
351
+ * Error thrown when an invitation email is missing or empty.
352
+ * Equivalent to Go's ErrEmailRequired.
353
+ */
354
+ declare class EmailRequiredError extends ValidationError {
355
+ constructor(message?: string);
356
+ }
357
+ /**
358
+ * Error thrown when a role is missing or empty.
359
+ * Equivalent to Go's ErrRoleRequired.
360
+ */
361
+ declare class RoleRequiredError extends ValidationError {
362
+ constructor(message?: string);
363
+ }
364
+ /**
365
+ * Structured error returned by the api-service Users and GeoIdentity endpoints.
366
+ * Equivalent to Go's APIServiceError. Branch on the subclasses (for example
367
+ * UserNotFoundError) or on `code`.
368
+ */
369
+ declare class APIServiceError extends APIError {
370
+ /** Machine-readable reason, e.g. "USER_NOT_FOUND". Empty when the API sent none. */
371
+ readonly code: string;
372
+ /** Message returned by the API, without the SDK prefix. */
373
+ readonly apiMessage: string;
374
+ readonly details: SpatialErrorDetail[];
375
+ constructor(statusCode: number, code: string, message: string, details?: SpatialErrorDetail[]);
376
+ }
377
+ /**
378
+ * The user does not exist in the organization (or its access was revoked).
379
+ * Equivalent to Go's ErrUserNotFound.
380
+ */
381
+ declare class UserNotFoundError extends APIServiceError {
382
+ constructor(message?: string, statusCode?: number, code?: string, details?: SpatialErrorDetail[]);
383
+ }
384
+ /**
385
+ * The GeoIdentity rule does not exist.
386
+ * Equivalent to Go's ErrRuleNotFound.
387
+ */
388
+ declare class RuleNotFoundError extends APIServiceError {
389
+ constructor(message?: string, statusCode?: number, code?: string, details?: SpatialErrorDetail[]);
390
+ }
391
+ /**
392
+ * The invited email already belongs to the organization.
393
+ * Equivalent to Go's ErrUserAlreadyExists.
394
+ */
395
+ declare class UserAlreadyExistsError extends APIServiceError {
396
+ constructor(message?: string, statusCode?: number, code?: string, details?: SpatialErrorDetail[]);
397
+ }
398
+ /**
399
+ * A pending invitation already exists for the email.
400
+ * Equivalent to Go's ErrInvitationPending.
401
+ */
402
+ declare class InvitationPendingError extends APIServiceError {
403
+ constructor(message?: string, statusCode?: number, code?: string, details?: SpatialErrorDetail[]);
404
+ }
405
+ /**
406
+ * The operation would leave the organization without an admin.
407
+ * Equivalent to Go's ErrLastAdmin.
408
+ */
409
+ declare class LastAdminError extends APIServiceError {
410
+ constructor(message?: string, statusCode?: number, code?: string, details?: SpatialErrorDetail[]);
411
+ }
412
+ /**
413
+ * The operation would leave a rule without assigned subjects.
414
+ * Equivalent to Go's ErrLastSubject.
415
+ */
416
+ declare class LastSubjectError extends APIServiceError {
417
+ constructor(message?: string, statusCode?: number, code?: string, details?: SpatialErrorDetail[]);
418
+ }
419
+
420
+ declare const TRANSIENT_BRAND: unique symbol;
421
+ declare const INTEGRATION_BRAND: unique symbol;
422
+ interface IdentityErrorFields<R extends string> {
423
+ message: string;
424
+ status?: number;
425
+ type?: string;
426
+ title?: string;
427
+ detail?: string;
428
+ requestId?: string;
429
+ reason: R;
430
+ apiKeyToRedact?: string;
431
+ }
432
+ /**
433
+ * Transient evaluation error (network, timeout, 5xx, 429, or non-JSON 5xx).
434
+ * `identityGuard` applies the configured `failOpen` policy for this error class.
435
+ */
436
+ declare class IdentityTransientError extends GeoEngineError {
437
+ readonly status?: number;
438
+ readonly type?: string;
439
+ readonly title?: string;
440
+ readonly detail?: string;
441
+ readonly requestId?: string;
442
+ readonly reason: IdentityTransientReason;
443
+ /** Stable machine-readable code; the contract between ESM and CJS builds. */
444
+ readonly code: "IDENTITY_TRANSIENT";
445
+ readonly [TRANSIENT_BRAND] = true;
446
+ static [Symbol.hasInstance](instance: unknown): boolean;
447
+ constructor(fields: IdentityErrorFields<IdentityTransientReason>);
448
+ toJSON(): Record<string, unknown>;
449
+ }
450
+ /**
451
+ * Integration or client configuration error (400, 401, 403, 404, 422, edge 403,
452
+ * unexpected 200 payload, or invalid input). `identityGuard` NEVER applies `failOpen`.
453
+ */
454
+ declare class IdentityIntegrationError extends GeoEngineError {
455
+ readonly status?: number;
456
+ readonly type?: string;
457
+ readonly title?: string;
458
+ readonly detail?: string;
459
+ readonly requestId?: string;
460
+ readonly reason: IdentityIntegrationReason;
461
+ /** Stable machine-readable code; the contract between ESM and CJS builds. */
462
+ readonly code: "IDENTITY_INTEGRATION";
463
+ readonly [INTEGRATION_BRAND] = true;
464
+ static [Symbol.hasInstance](instance: unknown): boolean;
465
+ constructor(fields: IdentityErrorFields<IdentityIntegrationReason>);
466
+ toJSON(): Record<string, unknown>;
467
+ }
468
+ /**
469
+ * Type guard that identifies transient GeoIdentity errors across ESM/CJS entrypoints.
470
+ */
471
+ declare function isTransient(err: unknown): err is IdentityTransientError;
472
+
473
+ export { RuleNameRequiredError as $, APIError as A, EmailRequiredError as B, type Challenge as C, type Decision as D, type EvaluateMeta as E, type FallbackDecision as F, type GuardRequest as G, ForbiddenError as H, type IdentityGuardOptions as I, GeoEngineError as J, type KnownDecision as K, type LocationSource as L, type MetaSource as M, type NextFunction as N, GeofenceIDRequiredError as O, GeofenceNotFoundError as P, InvalidCoordinatesError as Q, type ReputationStatus as R, type ShadowMatch as S, InvalidLatitudeError as T, InvalidLongitudeError as U, InvitationPendingError as V, LastAdminError as W, LastSubjectError as X, QuotaExceededError as Y, RoleRequiredError as Z, RuleIDRequiredError as _, type GuardResponse as a, RuleNotFoundError as a0, SpatialAPIError as a1, type SpatialErrorDetail as a2, TimeoutError as a3, UserAlreadyExistsError as a4, UserIDRequiredError as a5, UserNotFoundError as a6, ValidationError as a7, type EvaluateOptions as b, type EvaluateReason as c, type EvaluateRequest as d, type EvaluateResponse as e, type EvaluateSignal as f, type FallbackReason as g, type IdentityContext as h, type IdentityDecision as i, type IdentityErrorFields as j, type IdentityGuardClient as k, IdentityIntegrationError as l, type IdentityIntegrationReason as m, type IdentityLocation as n, IdentityService as o, type IdentityServiceConfig as p, type IdentitySubject as q, IdentityTransientError as r, type IdentityTransientReason as s, type KnownSignal as t, type RuleRef as u, isTransient as v, APIServiceError as w, AuthenticationError as x, ClientClosedError as y, DeviceIDRequiredError as z };
@@ -0,0 +1,196 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+
4
+
5
+
6
+
7
+ var _chunkA6RGK4MAcjs = require('./chunk-A6RGK4MA.cjs');
8
+
9
+ // src/identity/guard.ts
10
+ function resolveEvaluateFn(client) {
11
+ if (client && typeof client === "object" && "identity" in client && client.identity && typeof client.identity.evaluate === "function") {
12
+ return client.identity.evaluate.bind(client.identity);
13
+ }
14
+ if (client && typeof client === "object" && "evaluate" in client && typeof client.evaluate === "function") {
15
+ return client.evaluate.bind(client);
16
+ }
17
+ throw new (0, _chunkA6RGK4MAcjs.IdentityIntegrationError)({
18
+ message: "identityGuard: client debe exponer identity.evaluate() o evaluate()",
19
+ reason: "configuration_error"
20
+ });
21
+ }
22
+ function isResponseSent(res) {
23
+ return Boolean(res.headersSent || res.writableEnded);
24
+ }
25
+ function sendJson(res, statusCode, body) {
26
+ if (isResponseSent(res)) {
27
+ return;
28
+ }
29
+ if (typeof res.status === "function") {
30
+ const result = res.status(statusCode);
31
+ if (result && typeof result.json === "function") {
32
+ result.json(body);
33
+ return;
34
+ }
35
+ }
36
+ res.statusCode = statusCode;
37
+ if (typeof res.setHeader === "function") {
38
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
39
+ }
40
+ if (typeof res.json === "function") {
41
+ res.json(body);
42
+ return;
43
+ }
44
+ if (typeof res.end === "function") {
45
+ res.end(JSON.stringify(body));
46
+ }
47
+ }
48
+ function buildFallbackDecision(failOpen, fallbackReason, requestId) {
49
+ return {
50
+ decision: failOpen ? "ALLOW" : "BLOCK",
51
+ matched_rule: null,
52
+ default_applied: false,
53
+ reason: "SDK_FALLBACK",
54
+ signals: [],
55
+ shadow_matches: [],
56
+ fallback: true,
57
+ fallback_reason: fallbackReason,
58
+ meta: {
59
+ config_version: 0,
60
+ stale: true,
61
+ config_age_s: 0,
62
+ source: "sdk_fallback",
63
+ evaluated_at: (/* @__PURE__ */ new Date()).toISOString(),
64
+ ...requestId ? { request_id: requestId } : {}
65
+ }
66
+ };
67
+ }
68
+ function identityGuard(options) {
69
+ _chunkA6RGK4MAcjs.assertServerEnvironment.call(void 0, );
70
+ if (!options || typeof options !== "object") {
71
+ throw new (0, _chunkA6RGK4MAcjs.IdentityIntegrationError)({
72
+ message: "identityGuard: las opciones son obligatorias",
73
+ reason: "configuration_error"
74
+ });
75
+ }
76
+ if (typeof options.failOpen !== "boolean") {
77
+ throw new (0, _chunkA6RGK4MAcjs.IdentityIntegrationError)({
78
+ message: "identityGuard: la opci\xF3n failOpen (boolean) es obligatoria y no tiene valor por defecto",
79
+ reason: "configuration_error"
80
+ });
81
+ }
82
+ if (typeof options.scope !== "string" || options.scope.trim().length === 0) {
83
+ throw new (0, _chunkA6RGK4MAcjs.IdentityIntegrationError)({
84
+ message: "identityGuard: scope es obligatorio y debe ser una cadena no vac\xEDa",
85
+ reason: "configuration_error"
86
+ });
87
+ }
88
+ if (typeof options.getSubject !== "function") {
89
+ throw new (0, _chunkA6RGK4MAcjs.IdentityIntegrationError)({
90
+ message: "identityGuard: getSubject es obligatorio y debe ser una funci\xF3n",
91
+ reason: "configuration_error"
92
+ });
93
+ }
94
+ const evaluate = resolveEvaluateFn(options.client);
95
+ const {
96
+ scope,
97
+ getSubject,
98
+ getContext,
99
+ failOpen,
100
+ timeoutMs,
101
+ onChallenge,
102
+ onBlock,
103
+ onDecision,
104
+ onIntegrationError
105
+ } = options;
106
+ return (req, res, next) => {
107
+ const handleIntegrationFailure = async (err) => {
108
+ if (onIntegrationError) {
109
+ try {
110
+ await onIntegrationError(err, req, res, next);
111
+ } catch (e) {
112
+ }
113
+ }
114
+ sendJson(res, 500, { error: "internal_error" });
115
+ };
116
+ const handleBlock = async (decision) => {
117
+ if (onBlock) {
118
+ await onBlock(decision, req, res, next);
119
+ return;
120
+ }
121
+ sendJson(res, 403, { error: "access_denied" });
122
+ };
123
+ const handleFallback = async (fallbackReason, requestId) => {
124
+ const synthetic = buildFallbackDecision(failOpen, fallbackReason, requestId);
125
+ if (onDecision) {
126
+ await onDecision(synthetic, req);
127
+ }
128
+ if (failOpen) {
129
+ next();
130
+ return;
131
+ }
132
+ await handleBlock(synthetic);
133
+ };
134
+ void (async () => {
135
+ try {
136
+ _chunkA6RGK4MAcjs.assertServerEnvironment.call(void 0, );
137
+ const subject = await getSubject(req);
138
+ const context = getContext ? await getContext(req) : void 0;
139
+ const evaluateOptions = timeoutMs !== void 0 ? { timeoutMs } : void 0;
140
+ let response;
141
+ try {
142
+ response = await evaluate({ scope, subject, context }, evaluateOptions);
143
+ } catch (err) {
144
+ if (_chunkA6RGK4MAcjs.isTransient.call(void 0, err)) {
145
+ await handleFallback(err.reason, err.requestId);
146
+ return;
147
+ }
148
+ await handleIntegrationFailure(err);
149
+ return;
150
+ }
151
+ if (response.decision === "ALLOW") {
152
+ if (onDecision) {
153
+ await onDecision(response, req);
154
+ }
155
+ next();
156
+ return;
157
+ }
158
+ if (response.decision === "BLOCK") {
159
+ if (onDecision) {
160
+ await onDecision(response, req);
161
+ }
162
+ await handleBlock(response);
163
+ return;
164
+ }
165
+ if (response.decision === "CHALLENGE") {
166
+ if (onDecision) {
167
+ await onDecision(response, req);
168
+ }
169
+ if (onChallenge) {
170
+ await onChallenge(response, req, res, next);
171
+ return;
172
+ }
173
+ sendJson(res, 403, {
174
+ error: "challenge_required",
175
+ hint: _optionalChain([response, 'access', _ => _.challenge, 'optionalAccess', _2 => _2.hint]) || "step_up"
176
+ });
177
+ return;
178
+ }
179
+ await handleFallback("unknown_decision", _optionalChain([response, 'access', _3 => _3.meta, 'optionalAccess', _4 => _4.request_id]));
180
+ } catch (err) {
181
+ await handleIntegrationFailure(err);
182
+ }
183
+ })();
184
+ };
185
+ }
186
+
187
+ // src/identity/index.ts
188
+ _chunkA6RGK4MAcjs.assertServerEnvironment.call(void 0, );
189
+
190
+
191
+
192
+
193
+
194
+
195
+ exports.IdentityIntegrationError = _chunkA6RGK4MAcjs.IdentityIntegrationError; exports.IdentityService = _chunkA6RGK4MAcjs.IdentityService; exports.IdentityTransientError = _chunkA6RGK4MAcjs.IdentityTransientError; exports.identityGuard = identityGuard; exports.isTransient = _chunkA6RGK4MAcjs.isTransient;
196
+ //# sourceMappingURL=identity.cjs.map