@amedia/user 1.2.3 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @amedia/user
2
2
 
3
+ ## 1.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#1230](https://github.com/amedia/amedia-user-js/pull/1230) [`c9819f4`](https://github.com/amedia/amedia-user-js/commit/c9819f480437f63fd1508f4d9d6deafcf56475e1) Thanks [@csandven](https://github.com/csandven)! - Add Node.js support. `@amedia/user` now publishes a node-specific bundle via `exports` conditions. Node consumers (`npm install @amedia/user`) get `createAidClient`, `createShamoClient`, `validateToken`, and shared types/exceptions. Browser consumers using the importmap/CDN flow are unaffected.
8
+
3
9
  ## 1.2.3
4
10
 
5
11
  ### Patch Changes
package/README.md CHANGED
@@ -22,6 +22,48 @@ parts of the webpage are handled efficiently.
22
22
 
23
23
  Please be advised that you are required to use ESM to use this module.
24
24
 
25
+ ## Node.js usage
26
+
27
+ `@amedia/user` ships a Node bundle in addition to the browser one. Install via npm and import as usual:
28
+
29
+ ```bash
30
+ npm install @amedia/user
31
+ ```
32
+
33
+ ```ts
34
+ import { validateToken, createAidClient, ValidationError } from '@amedia/user';
35
+
36
+ // Verify a JWT issued by aID
37
+ try {
38
+ const { payload } = await validateToken(jwt, {
39
+ jwksUrl: 'https://...',
40
+ issuer: 'https://aid.example.no',
41
+ audience: 'api://your-service',
42
+ algorithms: ['RS256'],
43
+ });
44
+ // `payload.sub`, `payload.iat`, etc. are trusted
45
+ } catch (err) {
46
+ if (err instanceof ValidationError) {
47
+ // err.code is one of: token_expired, signature_invalid, claim_invalid:*, ...
48
+ }
49
+ }
50
+
51
+ // Call aID from the server
52
+ const aid = createAidClient({
53
+ baseUrl: 'https://aid.example.no',
54
+ token: '<bearer token>',
55
+ });
56
+ const user = await aid.getSelf();
57
+ ```
58
+
59
+ Available node exports:
60
+
61
+ - `validateToken` — JWT verification with JWKS caching.
62
+ - `createAidClient({ baseUrl, token })` — server-side aID HTTP client.
63
+ - `createShamoClient({ baseUrl, token })` — server-side shamo HTTP client.
64
+ - Shared types: `UserAttributes`, `ServiceUser`, `LoginStatus`, `PrimarySite`, etc.
65
+ - Shared exceptions: `ProblemJsonError`, `ResponseError`, `ValidationError`, ...
66
+
25
67
  ## Importing the module
26
68
 
27
69
  Add this module to your project by running `npm install -d @amedia/user`. This will allow for type-hinting. @amedia/user
package/index.d.ts CHANGED
@@ -1,39 +1,5 @@
1
- import * as v from 'valibot';
2
-
3
- type AccessFeatures = string[];
4
- interface UserAttributes {
5
- uuid: string | null;
6
- name: string | null;
7
- trackingKey: string | null;
8
- avatar: string | null;
9
- /** @deprecated Always returns empty. Use data from [@amedia/user-datapoints](https://github.com/amedia/amedia-user-datapoints) instead. */
10
- extraData: {
11
- [index: string]: unknown;
12
- };
13
- access: AccessFeatures;
14
- /** @deprecated Returns false for all keys. CMP data is now used. */
15
- privacyPreferences: PrivacyPreferences | null;
16
- sessionTrackingKey: string | null;
17
- }
18
- interface State {
19
- isLoggedIn: boolean;
20
- isCircuitBreakerTripped?: boolean;
21
- emergencyMode?: string[];
22
- }
23
- /**
24
- * @deprecated This is set to false as default. CMP data is now used.
25
- */
26
- declare class PrivacyPreferences {
27
- readonly allowResearchUsage: boolean;
28
- readonly personalizedContent: boolean;
29
- constructor(data: {
30
- allowResearchUsage: boolean;
31
- personalizedContent: boolean;
32
- });
33
- static default(): PrivacyPreferences;
34
- }
35
-
36
- type ClientId = string;
1
+ import { UserAttributes, ClientId, State, PrimarySite } from '@amedia/user-core';
2
+ export { FetchTimeoutError, PaywallError, PrivacyPreferences, State, UserAttributes, ValidationError } from '@amedia/user-core';
37
3
 
38
4
  type NamespaceList = Array<string>;
39
5
 
@@ -81,19 +47,6 @@ declare class UserDataRequest<TUserAttributes extends UserAttributes, TStorage e
81
47
  private debugLogFetchCompleted;
82
48
  }
83
49
 
84
- declare enum AffiliationType {
85
- ACCESS = "access",
86
- FAMILY = "family",
87
- SUBSCRIPTION = "subscription"
88
- }
89
- declare const PrimarySiteSchema: v.ObjectSchema<{
90
- readonly domain: v.StringSchema<undefined>;
91
- readonly name: v.StringSchema<undefined>;
92
- readonly affiliation: v.LiteralSchema<AffiliationType.ACCESS, undefined>;
93
- readonly affiliations: v.ArraySchema<v.UnionSchema<[v.LiteralSchema<AffiliationType.ACCESS, undefined>, v.LiteralSchema<AffiliationType.FAMILY, undefined>, v.LiteralSchema<AffiliationType.SUBSCRIPTION, undefined>], undefined>, undefined>;
94
- }, undefined>;
95
- type PrimarySite = v.InferOutput<typeof PrimarySiteSchema>;
96
-
97
50
  declare class SiteAccessResponse {
98
51
  readonly isLoggedIn: boolean;
99
52
  readonly hasAccess: boolean;
@@ -136,29 +89,11 @@ declare class PaywallUnlockRequest {
136
89
  tryUnlock(): Promise<PaywallUnlockResponse>;
137
90
  }
138
91
 
139
- declare class FetchTimeoutError extends Error {
140
- partialData: Record<string, unknown>;
141
- constructor(message: string, partialData: Record<string, unknown>);
142
- }
143
-
144
- declare class PaywallError extends Error {
145
- code: string;
146
- static ERROR_RELOADED_NO_ACCESS: string;
147
- static ERROR_ENABLING_ACCESS_FAILED: string;
148
- static ERROR_NO_ACCESS_AFTER_SUCCESSFUL_ACTIVATION_WITH_REQUESTED_ACCESS_FEATURES: string;
149
- constructor(message: string, code: string);
150
- }
151
-
152
92
  declare class EmergencyModeError extends Error {
153
93
  activeEmergencyModes: string[];
154
94
  constructor(message?: string);
155
95
  }
156
96
 
157
- declare class ValidationError extends Error {
158
- readonly code: string;
159
- constructor(code: string, message: string);
160
- }
161
-
162
97
  declare class TimeoutError extends Error {
163
98
  }
164
99
  /**
@@ -171,7 +106,7 @@ declare class TimeoutError extends Error {
171
106
  * @throws Error if unknown error
172
107
  * @returns true
173
108
  */
174
- declare function pollForAccess(requiredAccessFeatures?: string[], timeout_millis?: number): Promise<true>;
109
+ declare const pollForAccess: (requiredAccessFeatures?: string[], timeout_millis?: number) => Promise<true>;
175
110
 
176
111
  type LoginPageParams = {
177
112
  requestedUrl?: string;
@@ -196,5 +131,5 @@ declare const aidUrls: {
196
131
  sites: URL;
197
132
  };
198
133
 
199
- export { EmergencyModeError, FetchTimeoutError, PaywallError, PaywallUnlockRequest, PrivacyPreferences, SiteAccessRequest, SiteAccessResponse, TimeoutError, UserDataRequest, ValidationError, aidUrls, getLoginUrl, goToLoginPage, logout, pollForAccess, requestDataRefresh };
200
- export type { PaywallUnlockResponse, State, UserAttributes };
134
+ export { EmergencyModeError, PaywallUnlockRequest, SiteAccessRequest, SiteAccessResponse, TimeoutError, UserDataRequest, aidUrls, getLoginUrl, goToLoginPage, logout, pollForAccess, requestDataRefresh };
135
+ export type { PaywallUnlockResponse };
package/package.json CHANGED
@@ -6,25 +6,43 @@
6
6
  "url": "git+https://github.com/amedia/amedia-user-js.git"
7
7
  },
8
8
  "author": "Amedia Produkt og Teknologi AS (https://amedia.no)",
9
- "version": "1.2.3",
9
+ "version": "1.3.0",
10
10
  "type": "module",
11
- "types": "./index.d.ts",
12
- "publishConfig": {
13
- "access": "public"
14
- },
15
11
  "exports": {
16
12
  ".": {
17
- "types": "./index.d.ts",
18
- "import": "./index.js",
19
- "default": "./index.js"
13
+ "browser": {
14
+ "types": "./index.d.ts",
15
+ "import": "./index.js"
16
+ },
17
+ "node": {
18
+ "types": "./user.node.d.ts",
19
+ "import": "./user.node.js"
20
+ },
21
+ "default": {
22
+ "types": "./index.d.ts",
23
+ "import": "./index.js"
24
+ }
25
+ },
26
+ "./node": {
27
+ "types": "./user.node.d.ts",
28
+ "import": "./user.node.js"
20
29
  }
21
30
  },
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
22
34
  "files": [
23
35
  "index.js",
24
36
  "index.d.ts",
37
+ "user.node.js",
38
+ "user.node.d.ts",
25
39
  "README.md",
26
40
  "CHANGELOG.md"
27
41
  ],
42
+ "dependencies": {
43
+ "jose": "5.9.6",
44
+ "valibot": "1.3.1"
45
+ },
28
46
  "eik": {
29
47
  "server": "https://assets.acdn.no",
30
48
  "files": {
@@ -34,7 +52,8 @@
34
52
  }
35
53
  },
36
54
  "scripts": {
37
- "prepublishOnly": "(cd ../../ && npm run build) && cp ../../dist/user.d.ts index.d.ts",
38
- "postpublish": "npx @eik/cli publish && rm index.d.ts"
55
+ "prepublishOnly": "cd ../../ && npm run build",
56
+ "prepack": "cp ../../dist/user.d.ts index.d.ts && cp ../../dist/user.node.js user.node.js && cp ../../dist/user.node.d.ts user.node.d.ts",
57
+ "postpublish": "npx @eik/cli publish && rm index.d.ts user.node.js user.node.d.ts"
39
58
  }
40
59
  }
package/user.node.d.ts ADDED
@@ -0,0 +1,114 @@
1
+ import { ServiceUser, LoginStatus, PrimarySite } from '@amedia/user-core';
2
+ export { AccessFeatures, AffiliationType, DEFAULT_CLIENT_ID, FetchTimeoutError, IgnoredNetworkError, LoginStatus, PrimarySite, ProblemJsonError, ResponseError, ServerError, ServiceUser, State, UserAttributes, ValidationError } from '@amedia/user-core';
3
+ import { JWTPayload } from 'jose';
4
+
5
+ interface AidClientOptions {
6
+ /** Absolute base URL for aID (e.g. "https://aid.example.no"). Required. */
7
+ baseUrl: string;
8
+ /** Optional additional headers to merge into every request. */
9
+ headers?: Record<string, string>;
10
+ }
11
+ interface AidClient {
12
+ /**
13
+ * Fetch the authenticated user's own profile.
14
+ *
15
+ * @param sessionId - Value of the user's `aid.session` cookie.
16
+ * @param filter - Fields to include in the response. Defaults to `["uuid", "name", "tracking_key", "access", "session_tracking_key"]`.
17
+ * @returns Partial `ServiceUser` object containing only the requested fields.
18
+ */
19
+ getSelf: (sessionId: string, filter?: string[]) => Promise<ServiceUser>;
20
+ /**
21
+ * Fetch the access features granted to the authenticated user for a given site.
22
+ *
23
+ * @param sessionId - Value of the user's `aid.session` cookie.
24
+ * @param siteDomain - Full domain of the site to check access for (e.g. `"www.ba.no"`).
25
+ * @returns Array of access feature strings (e.g. `["plus", "sport"]`). Empty array means no access.
26
+ */
27
+ getAccessFeatures: (sessionId: string, siteDomain: string) => Promise<string[]>;
28
+ /**
29
+ * Fetch the current login flow status for the user's session.
30
+ *
31
+ * @param sessionId - Value of the user's `aid.session` cookie.
32
+ * @returns `LoginStatus.INITIATED` | `LoginStatus.COMPLETED` | `LoginStatus.ERROR`.
33
+ */
34
+ getLoginStatus: (sessionId: string) => Promise<LoginStatus>;
35
+ }
36
+ /**
37
+ * Create a server-side aID client bound to a given baseUrl.
38
+ *
39
+ * The returned client reuses the pure HTTP functions from @amedia/user-core —
40
+ * same URL paths, same schema validation — so the server surface mirrors
41
+ * what the browser does, forwarding the user's `aid.session` cookie value
42
+ * so aID identifies the request as coming from that user.
43
+ */
44
+ declare const createAidClient: (options: AidClientOptions) => AidClient;
45
+
46
+ interface ShamoClientOptions {
47
+ baseUrl: string;
48
+ token: string;
49
+ headers?: Record<string, string>;
50
+ }
51
+ interface ShamoClient {
52
+ getPrimarySite: (accessFeatures: string[]) => Promise<PrimarySite | null>;
53
+ }
54
+ declare const createShamoClient: (options: ShamoClientOptions) => ShamoClient;
55
+
56
+ interface JwksOptions {
57
+ /** Maximum age of the JWKS cache in milliseconds. Default 10 minutes. */
58
+ cacheMaxAge?: number;
59
+ /** Timeout for the JWKS HTTP fetch in milliseconds. Default 5 seconds. */
60
+ timeoutDuration?: number;
61
+ /** Cooldown before re-fetching after a cache miss, in milliseconds. Default 30 seconds. */
62
+ cooldownDuration?: number;
63
+ }
64
+ /**
65
+ * Clears the JWKS resolver cache. Primarily for tests.
66
+ */
67
+ declare const clearJwksCache: () => void;
68
+
69
+ interface ValidateTokenOptions {
70
+ /** JWKS endpoint URL. Required. */
71
+ jwksUrl: string;
72
+ /** Expected `iss` claim value (or array of acceptable values). */
73
+ issuer: string | string[];
74
+ /** Expected `aud` claim value (or array). */
75
+ audience: string | string[];
76
+ /**
77
+ * Allowed signing algorithms (explicit allow-list). Required — leaving
78
+ * this unset would let a forged JWT be verified under any algorithm the
79
+ * JWKS key happens to support, including unintended ones. Typical aID
80
+ * tokens use `["RS256"]`.
81
+ */
82
+ algorithms: string[];
83
+ /** Clock skew tolerance in seconds. Default 5s. */
84
+ clockTolerance?: number;
85
+ /** JWKS cache/timeout overrides. */
86
+ jwks?: JwksOptions;
87
+ }
88
+ interface ValidatedToken {
89
+ /** Fully parsed and verified JWT payload. */
90
+ payload: JWTPayload;
91
+ /** Header fields from the JWT (algorithm used, kid, etc.). */
92
+ header: {
93
+ alg: string;
94
+ kid?: string;
95
+ typ?: string;
96
+ };
97
+ }
98
+ /**
99
+ * Verifies a JWT issued by aID:
100
+ * - signature (via JWKS)
101
+ * - expiry (`exp`)
102
+ * - not-before (`nbf`)
103
+ * - issuer (`iss`)
104
+ * - audience (`aud`)
105
+ * - algorithm allow-list
106
+ *
107
+ * On failure throws a {@link ValidationError} with a stable `code` describing
108
+ * the failure mode, plus a human-readable message. Consumers can catch and
109
+ * map to HTTP 401/403 as appropriate.
110
+ */
111
+ declare const validateToken: (jwt: string, options: ValidateTokenOptions) => Promise<ValidatedToken>;
112
+
113
+ export { clearJwksCache, createAidClient, createShamoClient, validateToken };
114
+ export type { AidClient, AidClientOptions, JwksOptions, ShamoClient, ShamoClientOptions, ValidateTokenOptions, ValidatedToken };
package/user.node.js ADDED
@@ -0,0 +1,433 @@
1
+ import * as v from 'valibot';
2
+ import { createRemoteJWKSet, jwtVerify, errors } from 'jose';
3
+
4
+ function tryParseJSON(value) {
5
+ try {
6
+ return JSON.parse(value);
7
+ }
8
+ catch {
9
+ return null;
10
+ }
11
+ }
12
+
13
+ class ResponseError extends Error {
14
+ constructor(body, response, nestedException) {
15
+ const message = `Request failed (${response.status}/${response.statusText}: ${response.url || '[missing url]'}) Body: ${body || '[empty body received]'}`;
16
+ super(message + (nestedException ? `. Reason: ${nestedException.message}` : ''));
17
+ this.body = body;
18
+ this.response = response;
19
+ this.nestedException = nestedException;
20
+ }
21
+ }
22
+
23
+ class ProblemJson {
24
+ constructor(data) {
25
+ this.type = data.type;
26
+ this.title = data.title;
27
+ this.detail = data.detail;
28
+ this.status = data.status;
29
+ }
30
+ static unknown(body, status) {
31
+ return new ProblemJson({
32
+ type: 'about:blank',
33
+ title: 'Unparseable problem response',
34
+ detail: body,
35
+ status,
36
+ });
37
+ }
38
+ }
39
+ class ProblemJsonError extends ResponseError {
40
+ constructor(body, response) {
41
+ super(body, response);
42
+ const parsed = tryParseJSON(body);
43
+ this.problem = parsed
44
+ ? new ProblemJson(parsed)
45
+ : ProblemJson.unknown(body, response.status);
46
+ }
47
+ }
48
+
49
+ class ValidationError extends Error {
50
+ constructor(code, message) {
51
+ super(message);
52
+ this.code = code;
53
+ }
54
+ }
55
+
56
+ class ServerError extends Error {
57
+ }
58
+
59
+ class FetchTimeoutError extends Error {
60
+ constructor(message, partialData) {
61
+ super(message);
62
+ this.partialData = partialData;
63
+ }
64
+ }
65
+
66
+ class PaywallError extends Error {
67
+ constructor(message, code) {
68
+ super(message);
69
+ this.code = code;
70
+ }
71
+ }
72
+ PaywallError.ERROR_RELOADED_NO_ACCESS = 'RELOADED_NO_ACCESS';
73
+ PaywallError.ERROR_ENABLING_ACCESS_FAILED = 'ENABLING_ACCESS_FAILED';
74
+ PaywallError.ERROR_NO_ACCESS_AFTER_SUCCESSFUL_ACTIVATION_WITH_REQUESTED_ACCESS_FEATURES = 'NO_ACCESS_AFTER_SUCCESSFUL_ACTIVATION_WITH_REQUESTED_ACCESS_FEATURES';
75
+
76
+ class IgnoredNetworkError extends Error {
77
+ constructor(originalError) {
78
+ super(originalError?.message);
79
+ this.originalError = originalError;
80
+ }
81
+ }
82
+
83
+ const AidNamespaceSchema = v.record(v.string(), v.string());
84
+ const AidStorageSchema = v.record(v.string(), AidNamespaceSchema);
85
+ v.record(v.string(), AidStorageSchema);
86
+ v.object({
87
+ errors: v.array(v.object({
88
+ code: v.string(),
89
+ detail: v.string(),
90
+ })),
91
+ });
92
+ const PrivacyPreferencesSchema = v.object({
93
+ allow_research_usage: v.boolean(),
94
+ personalized_content: v.boolean(),
95
+ });
96
+ const SiteAccessSchema = v.object({
97
+ site_domain: v.string(),
98
+ access_features: v.array(v.string()),
99
+ });
100
+ const ServiceUserSchema = v.partial(v.object({
101
+ uuid: v.string(),
102
+ name: v.string(),
103
+ tracking_key: v.string(),
104
+ avatar: v.string(),
105
+ access: v.array(SiteAccessSchema),
106
+ privacy_preferences: PrivacyPreferencesSchema,
107
+ session_tracking_key: v.string(),
108
+ }));
109
+ v.object({
110
+ type: v.string(),
111
+ title: v.string(),
112
+ detail: v.string(),
113
+ status: v.number(),
114
+ instance: v.optional(v.string()),
115
+ });
116
+ var LoginStatus;
117
+ (function (LoginStatus) {
118
+ LoginStatus["INITIATED"] = "INITIATED";
119
+ LoginStatus["COMPLETED"] = "COMPLETED";
120
+ LoginStatus["ERROR"] = "ERROR";
121
+ })(LoginStatus || (LoginStatus = {}));
122
+ const LoginStatusResponseSchema = v.object({
123
+ status: v.enum(LoginStatus),
124
+ });
125
+
126
+ var AffiliationType;
127
+ (function (AffiliationType) {
128
+ AffiliationType["ACCESS"] = "access";
129
+ AffiliationType["FAMILY"] = "family";
130
+ AffiliationType["SUBSCRIPTION"] = "subscription";
131
+ })(AffiliationType || (AffiliationType = {}));
132
+ const PrimarySiteSchema = v.object({
133
+ domain: v.string(),
134
+ name: v.string(),
135
+ affiliation: v.literal(AffiliationType.ACCESS),
136
+ affiliations: v.array(v.union([
137
+ v.literal(AffiliationType.ACCESS),
138
+ v.literal(AffiliationType.FAMILY),
139
+ v.literal(AffiliationType.SUBSCRIPTION),
140
+ ])),
141
+ });
142
+
143
+ const isProblemJsonContentType = (contentType) => /^application\/problem\+json/.test(contentType ?? '');
144
+ function handleNetworkError(error) {
145
+ throw new IgnoredNetworkError(error);
146
+ }
147
+ async function unmarshalResponse(response) {
148
+ const body = await response.text();
149
+ if (body.length === 0) {
150
+ return null;
151
+ }
152
+ try {
153
+ const data = JSON.parse(body);
154
+ if (typeof data === 'undefined') {
155
+ return null;
156
+ }
157
+ return data;
158
+ }
159
+ catch (e) {
160
+ if (e instanceof SyntaxError) {
161
+ throw new ResponseError(body, response, e);
162
+ }
163
+ throw e;
164
+ }
165
+ }
166
+ async function failOnNonSuccess(response) {
167
+ if (response.ok) {
168
+ return response;
169
+ }
170
+ const body = await response.text();
171
+ if (isProblemJsonContentType(response.headers.get('Content-Type'))) {
172
+ throw new ProblemJsonError(body, response);
173
+ }
174
+ try {
175
+ const json = JSON.parse(body);
176
+ if (['message'].every((k) => Object.keys(json).includes(k)) &&
177
+ /Failed to fetch|Load Failed/i.test(json.message)) {
178
+ throw new IgnoredNetworkError(new Error(json.message));
179
+ }
180
+ }
181
+ catch (parseOrRethrow) {
182
+ if (parseOrRethrow instanceof IgnoredNetworkError)
183
+ throw parseOrRethrow;
184
+ if (/Failed to fetch|Load Failed/i.test(body)) {
185
+ throw new IgnoredNetworkError(new Error(body));
186
+ }
187
+ }
188
+ throw new ResponseError(body, response);
189
+ }
190
+ /**
191
+ * Pure HTTP primitive. Issues a fetch, maps non-2xx/network/problem+json
192
+ * to typed exceptions, and returns the JSON body (or null for empty).
193
+ *
194
+ * No retries, no emergency-mode handling, no circuit breaker, no logging —
195
+ * consumers layer those concerns on top.
196
+ */
197
+ const coreFetcher = (url, options) => fetch(url, options)
198
+ .catch(handleNetworkError)
199
+ .then(failOnNonSuccess)
200
+ .then(unmarshalResponse);
201
+ /**
202
+ * Pure HTTP primitive + valibot validation. Throws ValiError from valibot
203
+ * on schema mismatch; callers are responsible for catching it if they want.
204
+ */
205
+ const coreSchemaVerifiedFetch = (schema, url, options) => coreFetcher(url, options).then((json) => v.parse(schema, json));
206
+
207
+ const DEFAULT_CLIENT_ID = 'default';
208
+ const buildUrl$1 = (path, baseUrl) => baseUrl ? `${baseUrl.replace(/\/$/, '')}${path}` : path;
209
+ const resolveSchemaVerifiedFetch = (opts) => opts.schemaVerifiedFetch ?? coreSchemaVerifiedFetch;
210
+ /**
211
+ * GET /aid/api/users/self — returns ServiceUser schema.
212
+ */
213
+ const FILTER_FIELD_RE = /^[a-zA-Z0-9_]+$/;
214
+ const fetchSelf = (filter = [
215
+ 'uuid',
216
+ 'name',
217
+ 'tracking_key',
218
+ 'access',
219
+ 'session_tracking_key',
220
+ ], opts = {}) => {
221
+ for (const field of filter) {
222
+ if (!FILTER_FIELD_RE.test(field)) {
223
+ throw new TypeError(`fetchSelf: filter field must match ${FILTER_FIELD_RE} (got "${field}")`);
224
+ }
225
+ }
226
+ const filterQuery = filter.length > 0 ? `?filter=(${filter.join(',')})` : '';
227
+ return resolveSchemaVerifiedFetch(opts)(ServiceUserSchema, buildUrl$1(`/aid/api/users/self${filterQuery}`, opts.baseUrl), { headers: opts.headers });
228
+ };
229
+ /**
230
+ * GET /aid/api/access — returns string[] of access features for a site.
231
+ */
232
+ const fetchAccessFeatures = (siteDomain, opts = {}) => resolveSchemaVerifiedFetch(opts)(v.array(v.string()), buildUrl$1(`/aid/api/access?${new URLSearchParams({ site_domain: siteDomain })}`, opts.baseUrl), { headers: opts.headers });
233
+ /**
234
+ * GET /aid/login/status — login flow status enum.
235
+ */
236
+ const fetchLoginStatus = (opts = {}) => resolveSchemaVerifiedFetch(opts)(LoginStatusResponseSchema, buildUrl$1(`/aid/login/status`, opts.baseUrl), { headers: opts.headers }).then((d) => d.status);
237
+
238
+ const buildUrl = (path, baseUrl) => baseUrl ? `${baseUrl.replace(/\/$/, '')}${path}` : path;
239
+ /**
240
+ * GET /api/shamo/v2/access/primary_site — returns primary site or null.
241
+ */
242
+ const fetchPrimarySite = (accessFeatures, opts = {}) => {
243
+ const schemaVerifiedFetch = opts.schemaVerifiedFetch ?? coreSchemaVerifiedFetch;
244
+ return schemaVerifiedFetch(v.union([v.null(), PrimarySiteSchema]), buildUrl(`/api/shamo/v2/access/primary_site?${new URLSearchParams({
245
+ access_features: accessFeatures.join(','),
246
+ })}`, opts.baseUrl), { method: 'GET', headers: opts.headers });
247
+ };
248
+
249
+ /**
250
+ * Reject URLs that are not absolute http(s) — protects against SSRF via
251
+ * `file:`, `gopher:`, missing scheme (empty → relative), or malformed input
252
+ * when a URL is built from configuration / env / request context.
253
+ */
254
+ const assertHttpUrl = (value, fieldName) => {
255
+ if (typeof value !== 'string' || value.length === 0) {
256
+ throw new TypeError(`${fieldName} must be a non-empty string`);
257
+ }
258
+ let parsed;
259
+ try {
260
+ parsed = new URL(value);
261
+ }
262
+ catch {
263
+ throw new TypeError(`${fieldName} must be an absolute URL: ${value}`);
264
+ }
265
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
266
+ throw new TypeError(`${fieldName} must use http or https (got ${parsed.protocol})`);
267
+ }
268
+ return value;
269
+ };
270
+
271
+ /**
272
+ * Reject header values containing CR, LF or NUL so a caller cannot inject
273
+ * extra HTTP headers / cookies by passing a crafted session id or token.
274
+ * Throws TypeError on bad input; returns the value unchanged otherwise.
275
+ */
276
+ const assertHeaderSafe = (value, fieldName) => {
277
+ if (typeof value !== 'string' || value.length === 0) {
278
+ throw new TypeError(`${fieldName} must be a non-empty string`);
279
+ }
280
+ if (/[\r\n\0]/.test(value)) {
281
+ throw new TypeError(`${fieldName} must not contain CR/LF/NUL characters`);
282
+ }
283
+ return value;
284
+ };
285
+
286
+ const optsWith$1 = (c, sessionId) => ({
287
+ baseUrl: c.baseUrl,
288
+ // Caller headers spread FIRST so they cannot override the session Cookie
289
+ // we append last.
290
+ headers: {
291
+ ...c.headers,
292
+ Cookie: `aid.session=${assertHeaderSafe(sessionId, 'sessionId')}`,
293
+ },
294
+ });
295
+ /**
296
+ * Create a server-side aID client bound to a given baseUrl.
297
+ *
298
+ * The returned client reuses the pure HTTP functions from @amedia/user-core —
299
+ * same URL paths, same schema validation — so the server surface mirrors
300
+ * what the browser does, forwarding the user's `aid.session` cookie value
301
+ * so aID identifies the request as coming from that user.
302
+ */
303
+ const createAidClient = (options) => {
304
+ assertHttpUrl(options.baseUrl, 'baseUrl');
305
+ return {
306
+ getSelf: (sessionId, filter) => fetchSelf(filter, optsWith$1(options, sessionId)),
307
+ getAccessFeatures: (sessionId, siteDomain) => fetchAccessFeatures(siteDomain, optsWith$1(options, sessionId)),
308
+ getLoginStatus: (sessionId) => fetchLoginStatus(optsWith$1(options, sessionId)),
309
+ };
310
+ };
311
+
312
+ const optsWith = (c) => ({
313
+ baseUrl: c.baseUrl,
314
+ // Caller headers spread FIRST so they cannot override the Authorization
315
+ // header we append last.
316
+ headers: {
317
+ ...c.headers,
318
+ Authorization: `Bearer ${assertHeaderSafe(c.token, 'token')}`,
319
+ },
320
+ });
321
+ const createShamoClient = (options) => {
322
+ assertHttpUrl(options.baseUrl, 'baseUrl');
323
+ return {
324
+ getPrimarySite: (accessFeatures) => fetchPrimarySite(accessFeatures, optsWith(options)),
325
+ };
326
+ };
327
+
328
+ /**
329
+ * Cache of JWKS resolvers keyed by URL. `createRemoteJWKSet` already caches
330
+ * the fetched JWKS in memory — we just avoid constructing multiple resolvers
331
+ * for the same URL, and allow TTL overrides.
332
+ */
333
+ const cache = new Map();
334
+ const getJwks = (jwksUrl, options = {}) => {
335
+ assertHttpUrl(jwksUrl, 'jwksUrl');
336
+ const existing = cache.get(jwksUrl);
337
+ if (existing)
338
+ return existing;
339
+ const resolver = createRemoteJWKSet(new URL(jwksUrl), {
340
+ cacheMaxAge: options.cacheMaxAge ?? 10 * 60 * 1000,
341
+ timeoutDuration: options.timeoutDuration ?? 5000,
342
+ cooldownDuration: options.cooldownDuration ?? 30000,
343
+ });
344
+ cache.set(jwksUrl, resolver);
345
+ return resolver;
346
+ };
347
+ /**
348
+ * Clears the JWKS resolver cache. Primarily for tests.
349
+ */
350
+ const clearJwksCache = () => {
351
+ cache.clear();
352
+ };
353
+
354
+ // TBD resolved with aID team on 2026-04-21:
355
+ // - JWKS URL: — resolve before production use; see ValidateTokenOptions.jwksUrl
356
+ // - Issuer: — resolve before production use; see ValidateTokenOptions.issuer
357
+ // - Audience: — resolve before production use; see ValidateTokenOptions.audience (may be per-consumer)
358
+ // - Algorithms: — resolve before production use; see ValidateTokenOptions.algorithms (e.g. ['RS256'])
359
+ // - JWKS TTL: — resolve before production use; see ValidateTokenOptions.jwks.cacheMaxAge
360
+ /**
361
+ * Verifies a JWT issued by aID:
362
+ * - signature (via JWKS)
363
+ * - expiry (`exp`)
364
+ * - not-before (`nbf`)
365
+ * - issuer (`iss`)
366
+ * - audience (`aud`)
367
+ * - algorithm allow-list
368
+ *
369
+ * On failure throws a {@link ValidationError} with a stable `code` describing
370
+ * the failure mode, plus a human-readable message. Consumers can catch and
371
+ * map to HTTP 401/403 as appropriate.
372
+ */
373
+ const validateToken = async (jwt, options) => {
374
+ const keySet = getJwks(options.jwksUrl, options.jwks);
375
+ return validateTokenWithKeySet(jwt, keySet, options);
376
+ };
377
+ /**
378
+ * Internal test seam. Accepts a pre-constructed JWKS resolver (either
379
+ * remote via `createRemoteJWKSet` or local via `createLocalJWKSet`) so tests
380
+ * can bypass HTTP. Exported from the module but NOT from the package index.
381
+ */
382
+ const validateTokenWithKeySet = async (jwt, keySet, options) => {
383
+ if (!Array.isArray(options.algorithms) || options.algorithms.length === 0) {
384
+ throw new ValidationError('config_invalid', 'algorithms must be a non-empty array of allowed signing algorithms');
385
+ }
386
+ try {
387
+ const { payload, protectedHeader } = await jwtVerify(jwt, keySet, {
388
+ issuer: options.issuer,
389
+ audience: options.audience,
390
+ algorithms: options.algorithms,
391
+ clockTolerance: options.clockTolerance ?? 5,
392
+ });
393
+ return {
394
+ payload,
395
+ header: {
396
+ alg: protectedHeader.alg,
397
+ kid: protectedHeader.kid,
398
+ typ: protectedHeader.typ,
399
+ },
400
+ };
401
+ }
402
+ catch (err) {
403
+ throw mapJoseError(err);
404
+ }
405
+ };
406
+ function mapJoseError(err) {
407
+ if (err instanceof errors.JWTExpired) {
408
+ return new ValidationError('token_expired', err.message);
409
+ }
410
+ if (err instanceof errors.JWTClaimValidationFailed) {
411
+ return new ValidationError(`claim_invalid:${err.claim ?? 'unknown'}`, err.message);
412
+ }
413
+ if (err instanceof errors.JWSSignatureVerificationFailed) {
414
+ return new ValidationError('signature_invalid', err.message);
415
+ }
416
+ if (err instanceof errors.JWTInvalid ||
417
+ err instanceof errors.JWSInvalid) {
418
+ return new ValidationError('token_malformed', err.message);
419
+ }
420
+ if (err instanceof errors.JWKSNoMatchingKey) {
421
+ return new ValidationError('unknown_kid', err.message);
422
+ }
423
+ if (err instanceof errors.JOSEError) {
424
+ return new ValidationError(`jose_${err.code ?? 'error'}`, err.message);
425
+ }
426
+ if (err instanceof Error) {
427
+ return new ValidationError('validation_failed', err.message);
428
+ }
429
+ return new ValidationError('validation_failed', String(err));
430
+ }
431
+
432
+ export { AffiliationType, DEFAULT_CLIENT_ID, FetchTimeoutError, IgnoredNetworkError, LoginStatus, ProblemJsonError, ResponseError, ServerError, ValidationError, clearJwksCache, createAidClient, createShamoClient, validateToken };
433
+ //# sourceMappingURL=user.node.js.map