@env-ctrl/angular 0.1.0 → 0.1.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.
package/README.md CHANGED
@@ -49,7 +49,7 @@ provideEnvCtrl({
49
49
  });
50
50
  ```
51
51
 
52
- Matching: exact `host:port`, then exact host, then the longest `*.` wildcard, then a `'*'` entry. An address with no
52
+ Matching: exact `host:port`, then exact host, then the longest `*.` wildcard (with a port it matches that port only), then a `'*'` entry. An address with no
53
53
  match uses `fallback`, or fails with an error naming the host. In the browser the host is `location.host`; with SSR
54
54
  it is the request's `Host` header, which Angular checks against `allowedHosts` (keep that list tight). Prerendered
55
55
  pages have no request, so the browser picks the token there.
@@ -85,7 +85,7 @@ token instead.
85
85
  | `cache` | `true` | Keep the last values in `localStorage` and use them when env-ctrl can't be reached (network error, timeout, 5xx, 429). Never after 401/403: a revoked token stops working. |
86
86
  | `maxCacheAgeMs` | 7 days | Ignore older cached values. |
87
87
  | `fallback` | none | Values to use when nothing else is available. |
88
- | `onError` | `'throw'` | When nothing can be loaded: `'throw'` fails the bootstrap, `'warn'` starts with empty values. |
88
+ | `onError` | `'throw'` | When nothing can be loaded: `'throw'` fails the bootstrap, `'warn'` logs and starts with `fallback` (empty if none). A 401/403 (revoked token, origin or IP not allowed) never uses the cache or the fallback, so it always ends up here. |
89
89
  | `transferState` | `true` | SSR: pass the server's values to the browser so it doesn't fetch them again. |
90
90
  | `serverOrigin` | the page's origin | SSR: the `Origin` header the server sends, for tokens limited to origins. Set it only if the server sees another address than users (a proxy rewriting `Host`). |
91
91
 
@@ -98,6 +98,11 @@ With `@angular/ssr` the server fetches the configs once per request and hands th
98
98
  origin-restricted tokens work. It never writes the cache. If the server's fetch fails, it renders with the fallback
99
99
  and the browser loads the values itself, so the page may change once they arrive.
100
100
 
101
+ The server keeps each answer in memory for 60 seconds (the API's own cache time) and concurrent renders share one
102
+ request: public tokens are rate limited per client IP, and all your SSR traffic comes from the server's IP. If the
103
+ token has an IP allow-list, add the server's outgoing address. Behind a proxy the host and origin come from the
104
+ forwarded request URL (`X-Forwarded-Host` / `-Proto`), not the internal `Host` header.
105
+
101
106
  Prerendered pages (`RenderMode.Prerender`) are built without a request: the server does not fetch (values would be
102
107
  frozen at build time) and renders with `fallback`; the browser loads current values on start.
103
108
 
package/dist/core.d.ts CHANGED
@@ -79,5 +79,7 @@ interface Env {
79
79
  /** Host the app is served on (browser: location.host; SSR: the request's Host), to pick from a TokenByHost. */
80
80
  host: string | undefined;
81
81
  }
82
+ /** Test hook: forget the server-side cache. */
83
+ export declare function clearServerCache(): void;
82
84
  export declare function loadPublicConfig(opts: PublicConfigOptions, env?: Partial<Env>): Promise<LoadedConfig>;
83
85
  export {};
package/dist/core.js CHANGED
@@ -41,7 +41,7 @@ export function tokenForHost(token, host) {
41
41
  if (!token || typeof token === 'string')
42
42
  return token ? token.trim() : undefined;
43
43
  if (!host)
44
- return token['*'];
44
+ return token['*']?.trim();
45
45
  const map = new Map(Object.entries(token).map(([k, v]) => [k.trim().toLowerCase(), v.trim()]));
46
46
  const withPort = host.trim().toLowerCase();
47
47
  const name = withPort.replace(/:\d+$/, '').replace(/^\[|\]$/g, '');
@@ -50,7 +50,11 @@ export function tokenForHost(token, host) {
50
50
  return exact;
51
51
  let best;
52
52
  for (const [k, v] of map) {
53
- if (k.startsWith('*.') && name.endsWith(k.slice(1)) && (!best || k.length > best[0]))
53
+ if (!k.startsWith('*.'))
54
+ continue;
55
+ // '*.example.com:8080' matches that port only; '*.example.com' any port.
56
+ const target = /:\d+$/.test(k) ? withPort : name;
57
+ if (target.endsWith(k.slice(1)) && (!best || k.length > best[0]))
54
58
  best = [k.length, v];
55
59
  }
56
60
  return best?.[1] ?? map.get('*');
@@ -79,6 +83,19 @@ function cacheKey(apiUrl, token) {
79
83
  function isOutage(status) {
80
84
  return status === undefined || status === 429 || status >= 500;
81
85
  }
86
+ /**
87
+ * SSR: every render needs the configs, and the API limits public requests per client IP (one server = one IP).
88
+ * Answers are shared per API URL + token for SERVER_TTL_MS (the API's own max-age), and concurrent renders share one
89
+ * request.
90
+ */
91
+ const SERVER_TTL_MS = 60_000;
92
+ const serverCache = new Map();
93
+ const inFlight = new Map();
94
+ /** Test hook: forget the server-side cache. */
95
+ export function clearServerCache() {
96
+ serverCache.clear();
97
+ inFlight.clear();
98
+ }
82
99
  export async function loadPublicConfig(opts, env = {}) {
83
100
  const e = {
84
101
  fetch: env.fetch ?? globalThis.fetch.bind(globalThis),
@@ -104,9 +121,28 @@ export async function loadPublicConfig(opts, env = {}) {
104
121
  const apiUrl = (opts.apiUrl ?? DEFAULT_API_URL).replace(/\/+$/, '');
105
122
  const useCache = opts.cache !== false && !e.server;
106
123
  const key = cacheKey(apiUrl, token);
124
+ const skey = `${apiUrl}|${token}`; // server memory only: the whole token is fine as a key
125
+ if (e.server) {
126
+ const hit = serverCache.get(skey);
127
+ if (hit && e.now() - hit.at < SERVER_TTL_MS)
128
+ return { values: { ...hit.values }, source: 'network', fetchedAt: hit.fetchedAt };
129
+ }
107
130
  try {
108
- const values = await fetchValues(apiUrl, token, opts, e);
131
+ let values;
132
+ if (e.server) {
133
+ let p = inFlight.get(skey);
134
+ if (!p) {
135
+ p = fetchValues(apiUrl, token, opts, e).finally(() => inFlight.delete(skey));
136
+ inFlight.set(skey, p);
137
+ }
138
+ values = { ...(await p) };
139
+ }
140
+ else {
141
+ values = await fetchValues(apiUrl, token, opts, e);
142
+ }
109
143
  const fetchedAt = new Date(e.now()).toISOString();
144
+ if (e.server)
145
+ serverCache.set(skey, { at: e.now(), values, fetchedAt });
110
146
  if (useCache) {
111
147
  try {
112
148
  e.storage?.setItem(key, JSON.stringify({ values, fetchedAt }));
package/dist/index.d.ts CHANGED
@@ -1,11 +1,13 @@
1
1
  import { EnvironmentProviders, InjectionToken } from '@angular/core';
2
2
  import { ConfigSource, PublicConfigOptions } from './core.js';
3
- export { DEFAULT_API_URL, EnvCtrlError, assertPublicToken, loadPublicConfig, tokenForHost } from './core.js';
3
+ export { DEFAULT_API_URL, EnvCtrlError, assertPublicToken, clearServerCache, loadPublicConfig, tokenForHost } from './core.js';
4
4
  export type { ConfigSource, LoadedConfig, PublicConfigOptions, PublicToken, TokenByHost } from './core.js';
5
5
  export interface EnvCtrlOptions extends PublicConfigOptions {
6
6
  /**
7
- * What to do when the configs can't be loaded and there is neither a cached copy nor a fallback:
8
- * 'throw' (default) fails the bootstrap, 'warn' logs and starts with empty values.
7
+ * What to do when the configs can't be loaded: always after 401/403 (revoked token, origin or IP not allowed:
8
+ * cache and fallback are ignored, so a misconfiguration is not hidden), and on outages when there is neither a
9
+ * cached copy nor a fallback. 'throw' (default) fails the bootstrap; 'warn' logs and starts with the fallback
10
+ * values (empty if none).
9
11
  */
10
12
  onError?: 'throw' | 'warn';
11
13
  /**
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { InjectionToken, PLATFORM_ID, REQUEST, TransferState, inject, makeEnvironmentProviders, makeStateKey, provideAppInitializer, } from '@angular/core';
2
2
  import { EnvCtrlError, assertPublicToken, loadPublicConfig, tokensOf } from './core.js';
3
- export { DEFAULT_API_URL, EnvCtrlError, assertPublicToken, loadPublicConfig, tokenForHost } from './core.js';
3
+ export { DEFAULT_API_URL, EnvCtrlError, assertPublicToken, clearServerCache, loadPublicConfig, tokenForHost } from './core.js';
4
4
  /**
5
5
  * The loaded public configs. Available once the app has started (it is filled by an app initializer), so read it in
6
6
  * components, services and guards, not in other app initializers registered before provideEnvCtrl().
@@ -91,13 +91,17 @@ export function provideEnvCtrl(options) {
91
91
  config.set({ values: { ...(opts.fallback ?? {}) }, source: 'fallback', error: 'prerendering: the browser loads the values' });
92
92
  return;
93
93
  }
94
- const host = request?.headers.get('host') ?? undefined;
94
+ // Host and origin from request.url, which Angular builds from X-Forwarded-Host/Proto behind a proxy: the raw
95
+ // Host header there can be an internal name.
96
+ let host;
95
97
  let origin;
96
98
  try {
97
- origin = request ? new URL(request.url).origin : undefined;
99
+ const u = new URL(request.url);
100
+ host = u.host;
101
+ origin = u.origin;
98
102
  }
99
103
  catch {
100
- origin = undefined;
104
+ host = request?.headers.get('host') ?? undefined;
101
105
  }
102
106
  try {
103
107
  const loaded = await loadPublicConfig(opts, server ? { server, host, origin } : {});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@env-ctrl/angular",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Public runtime config for Angular apps from env-ctrl (envctrl.com): API URLs, feature flags and keys safe for the browser, loaded before the app renders, SSR-aware.",
5
5
  "homepage": "https://envctrl.com",
6
6
  "keywords": [