@ultimat3/core 31.46.0 → 31.47.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/README.md CHANGED
@@ -132,6 +132,8 @@ Each of the five, and `fingerprint`, `storeMode` and render's `contentHash`, has
132
132
  ## Errors are instructions
133
133
 
134
134
  ```ts
135
+ import { UltimateError } from '@ultimat3/core';
136
+
135
137
  throw new UltimateError({
136
138
  code: 'X_DB_DRIFT',
137
139
  cause: 'table "posts" has column "publish_at" not present in any migration',
@@ -155,6 +157,8 @@ config faults, during the incident they were already causing. Classify the codes
155
157
  app throws once, beside the module that declares them:
156
158
 
157
159
  ```ts
160
+ import { registerErrorRetry } from '@ultimat3/core';
161
+
158
162
  registerErrorRetry({ X_OAUTH_EXCHANGE_FAILED: 'retryable', X_RATE_LIMITED: 'retry-after' });
159
163
  ```
160
164
 
@@ -265,6 +269,10 @@ build: `error instanceof Error` runs a `Proxy`'s `getPrototypeOf` trap, and
265
269
  throws one line *before* the total renderer that was meant to make the path safe.
266
270
 
267
271
  ```ts
272
+ import { renderThrowable, stringField } from '@ultimat3/core';
273
+
274
+ declare const error: unknown;
275
+
268
276
  const code = stringField(error, 'code') ?? 'X_TRANSPORT_UNAVAILABLE';
269
277
  const cause = stringField(error, 'cause') ?? renderThrowable(error);
270
278
  ```
@@ -320,6 +328,10 @@ a job boundary the class is gone and the `code` is what survives — match on th
320
328
  ## Context
321
329
 
322
330
  ```ts
331
+ import { agentActor, ctxOf, runWithContext, useContext, withChildContext } from '@ultimat3/core';
332
+
333
+ declare function render(): Promise<void>;
334
+
323
335
  const ctx = ctxOf({ actor: agentActor({ id: 'mcp-1', scopes: ['post:publish'] }) });
324
336
  await runWithContext(ctx, async () => {
325
337
  const { actor, locale, tz, logger } = useContext(); // throws X_NO_CONTEXT outside
@@ -371,6 +383,14 @@ fetch one. Resolve the graph ONCE per request and hand it to the actor every sur
371
383
  carries:
372
384
 
373
385
  ```ts
386
+ import { actorFact, userActor, withFacts } from '@ultimat3/core';
387
+ import { can } from '@ultimat3/policy';
388
+
389
+ type Viewer = { readonly staff: boolean };
390
+ declare const viewer: Viewer;
391
+ declare const user: { readonly id: string; readonly role: string };
392
+ declare function canSee(viewer: Viewer | undefined, row: unknown): boolean;
393
+
374
394
  declare module '@ultimat3/core' {
375
395
  interface ActorFacts { readonly viewer: Viewer } // declared once, app-wide
376
396
  }
@@ -433,6 +453,8 @@ Loading `.env` is **Bun's**, not ours. `envFileCandidates()` states what it does
433
453
  ## One environment, one key
434
454
 
435
455
  ```ts
456
+ import { isLocal, isProduction, resolveEnvironment, tryResolveEnvironment } from '@ultimat3/core';
457
+
436
458
  resolveEnvironment(); // 'development' | 'test' | 'staging' | 'production'
437
459
  tryResolveEnvironment(); // the same, `undefined` instead of a throw for an unrecognised value
438
460
  isProduction(); // exact; nothing else counts
@@ -467,7 +489,13 @@ embedded PGlite included. Never a `DATABASE_URL` truthiness check: `x dev` sets
467
489
  ## A secret is redacted by value, not by name
468
490
 
469
491
  ```ts
470
- const dsn = secret(process.env.DATABASE_URL ?? '', 'DATABASE_URL');
492
+ import { type Logger, revealSecret, secret } from '@ultimat3/core';
493
+
494
+ declare function connect(dsn: string): void;
495
+
496
+ declare const logger: Logger;
497
+
498
+ const dsn = secret(process.env['DATABASE_URL'] ?? '', 'DATABASE_URL');
471
499
  logger.info('boot', { dsn }); // {"dsn":"[redacted]"}
472
500
  connect(revealSecret(dsn)); // the one greppable way out
473
501
  ```
@@ -506,6 +534,8 @@ out. There is no vault integration and there will not be one — that is a platf
506
534
 
507
535
  ```ts
508
536
  // app.config.ts
537
+ import { defineEnv, type EnvSchema, installSecrets } from '@ultimat3/core';
538
+
509
539
  await installSecrets(); // secrets.enc.json → process.env, real env wins
510
540
  export const envSchema = {
511
541
  SESSION_SECRET: { type: 'string', secret: true },
@@ -663,6 +693,12 @@ match with `sealAll()`; uniqueness cannot be held across keys.
663
693
  ## Metrics: same seam as tracing, one signal over
664
694
 
665
695
  ```ts
696
+ import { collectMetrics, counter, gauge, histogram, metricsText } from '@ultimat3/core';
697
+
698
+ declare function pending(): number;
699
+
700
+ declare const ms: number;
701
+
666
702
  const published = counter('posts_published_total', { description: 'posts published' });
667
703
  published.add(1, { plan: 'pro' });
668
704
 
@@ -757,6 +793,12 @@ raised at `parseSentryDsn`, at configuration, never at a report.
757
793
  ## One cursor, everywhere
758
794
 
759
795
  ```ts
796
+ import { decodeCursor, encodeCursor } from '@ultimat3/core';
797
+
798
+ declare const scope: string;
799
+
800
+ declare const cursor: string;
801
+
760
802
  encodeCursor({ scope, key: ['2026-01-01T00:00:00.000Z'], id: 'p_9' }); // base64url(body).hmac
761
803
  decodeCursor(cursor, scope); // or X_CURSOR_INVALID
762
804
  ```
@@ -970,6 +1012,10 @@ answers what an element carries.
970
1012
  ## One image pipeline, everywhere
971
1013
 
972
1014
  ```ts
1015
+ import { blurDataUrl, probeImage, transformImageBytes } from '@ultimat3/core';
1016
+
1017
+ declare const bytes: Uint8Array;
1018
+
973
1019
  probeImage(bytes); // { format, width, height, mimeType }
974
1020
  await transformImageBytes(bytes, { width: 640, format: 'webp', quality: 80 });
975
1021
  await blurDataUrl(bytes); // ThumbHash PNG data: URI, the LQIP
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/core",
3
- "version": "31.46.0",
3
+ "version": "31.47.0",
4
4
  "description": "Ultimate's foundation: errors, context, env, config, clock, ids, logging, telemetry, lifecycle",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -54,6 +54,6 @@
54
54
  "test": "bun test"
55
55
  },
56
56
  "dependencies": {
57
- "@ultimat3/schema": "31.46.0"
57
+ "@ultimat3/schema": "31.47.0"
58
58
  }
59
59
  }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * The opaque id of the principal a page acts for: keyed SHA-256 over who is acting, never the id,
3
+ * because the HTML carrying it is readable by every script on the page. Here, below both, so the
4
+ * document's writer (`@ultimat3/auth`) and a replay's judge (`@ultimat3/action`) derive one value
5
+ * under one key: the per-process fallback key is module state, and two copies would disagree.
6
+ */
7
+
8
+ import type { Actor } from './actor';
9
+ import { hmac } from './hmac';
10
+ import { logger } from './logger';
11
+
12
+ /** 128 bits: a scope only has to differ between principals, never to authenticate anyone. */
13
+ const SCOPE_HEX_CHARS = 32;
14
+
15
+ /** `wiki/Configuration.md`'s floor for `SESSION_SECRET`. */
16
+ const MIN_SECRET_LENGTH = 32;
17
+
18
+ export interface ClientScopeIdOptions {
19
+ /** Defaults to `SESSION_SECRET`. */
20
+ readonly secret?: string | undefined;
21
+ readonly env?: Readonly<Record<string, string | undefined>> | undefined;
22
+ }
23
+
24
+ /** Minted on first need when no `SESSION_SECRET` exists: stable per process, never per request. */
25
+ let processKey: string | undefined;
26
+
27
+ /** `''` for the anonymous actor; otherwise the principal AND who is really acting. */
28
+ export function clientScopeId(actor: Actor, options: ClientScopeIdOptions = {}): string {
29
+ if (actor.kind === 'anonymous') return '';
30
+ const material = JSON.stringify([
31
+ actor.kind,
32
+ actor.id,
33
+ actor.onBehalfOf?.actorKind ?? null,
34
+ actor.onBehalfOf?.actorId ?? null,
35
+ ]);
36
+ return hmac('sha256', scopeKey(options), material, 'hex').slice(0, SCOPE_HEX_CHARS);
37
+ }
38
+
39
+ function scopeKey(options: ClientScopeIdOptions): string {
40
+ if (options.secret !== undefined) return options.secret;
41
+ const configured = (options.env ?? Bun.env)['SESSION_SECRET']?.trim() ?? '';
42
+ if (configured.length >= MIN_SECRET_LENGTH) return configured;
43
+ if (processKey === undefined) {
44
+ // `SESSION_SECRET` is optional in the env schema, so its absence cannot refuse a render. A
45
+ // random per-process key keeps the id opaque; what it costs is stability across replicas and
46
+ // restarts — a principal's page then rescopes, which clears its store, never leaks it, and a
47
+ // replay rendered by another process is refused and stays queued.
48
+ processKey = Array.from(crypto.getRandomValues(new Uint8Array(32)), (byte) =>
49
+ byte.toString(16).padStart(2, '0'),
50
+ ).join('');
51
+ logger.warn('auth.client_scope.process_key', {
52
+ reason: 'SESSION_SECRET unset or shorter than 32 chars',
53
+ fix: 'export SESSION_SECRET="$(openssl rand -hex 32)"',
54
+ });
55
+ }
56
+ return processKey;
57
+ }
package/src/index.ts CHANGED
@@ -160,6 +160,8 @@ export { MAX_RETRY_AFTER_SECONDS, retryAfterSecondsOf } from './client-retry-aft
160
160
  */
161
161
  export type { ClientScope } from './client-scope';
162
162
  export { onRescope, rescope } from './client-scope';
163
+ export type { ClientScopeIdOptions } from './client-scope-id';
164
+ export { clientScopeId } from './client-scope-id';
163
165
  export type { StreamRequest } from './client-stream';
164
166
  export { clientStream } from './client-stream';
165
167
  export { clientTransport } from './client-transport';
@@ -891,10 +893,12 @@ export {
891
893
  CLIENT_PATH_STYLE_META,
892
894
  CLIENT_PERSIST_META,
893
895
  CLIENT_PINS_META,
896
+ CLIENT_REPLAY_SCOPE_HEADER,
894
897
  CLIENT_SCOPE_HEADER,
895
898
  CLIENT_SCOPE_META,
896
899
  CLIENT_SYNC_META,
897
900
  CLIENT_SYNC_WORKER_META,
901
+ principalScopeName,
898
902
  } from './page-meta';
899
903
  /** The structural Postgres seam http, auth, action and jobs share without a `@ultimat3/db` edge. */
900
904
  export type { PgExecutor } from './pg-executor';
package/src/page-meta.ts CHANGED
@@ -14,6 +14,23 @@ export const CLIENT_SCOPE_META = 'ultimate-scope';
14
14
  */
15
15
  export const CLIENT_SCOPE_HEADER = 'x-ultimate-scope';
16
16
 
17
+ /**
18
+ * On a REPLAY of a queued offline write, the principal whose queue holds it, as
19
+ * `principalScopeName` spells it. `@ultimat3/realtime`'s outbox sends it and `@ultimat3/action`'s
20
+ * route refuses a session that is someone else (`X_REPLAY_PRINCIPAL_MISMATCH`): two tier-3 packages
21
+ * that cannot import each other, agreeing here. Absent on every write that is not a replay.
22
+ */
23
+ export const CLIENT_REPLAY_SCOPE_HEADER = 'x-ultimate-replay-scope';
24
+
25
+ /**
26
+ * A principal as one non-empty token: the page's outbox partition and the replay header's value.
27
+ * Never blank for the anonymous visitor, because a proxy may drop an empty header and a dropped one
28
+ * claims nobody. Prefixed so a principal spelled `anon` is not the anonymous visitor.
29
+ */
30
+ export function principalScopeName(principal: string | null): string {
31
+ return principal === null ? 'anon' : `p:${principal}`;
32
+ }
33
+
17
34
  /**
18
35
  * The build id the document was rendered by. `x-ultimate-build` — the same spelling as the header,
19
36
  * and the one `@ultimat3/pwa` shipped as `BUILD_ID_META`, so no shipped reader changes.
package/src/page.ts CHANGED
@@ -78,10 +78,12 @@ export {
78
78
  CLIENT_PATH_STYLE_META,
79
79
  CLIENT_PERSIST_META,
80
80
  CLIENT_PINS_META,
81
+ CLIENT_REPLAY_SCOPE_HEADER,
81
82
  CLIENT_SCOPE_HEADER,
82
83
  CLIENT_SCOPE_META,
83
84
  CLIENT_SYNC_META,
84
85
  CLIENT_SYNC_WORKER_META,
86
+ principalScopeName,
85
87
  } from './page-meta';
86
88
  export type { RecordEnvelope, RecordRows } from './record-envelope';
87
89
  export { decodeRecordEnvelope, RECORDS_HEADER } from './record-envelope';
@@ -89,6 +91,7 @@ export type { PageClient, RecordSink } from './record-sink';
89
91
  export { pageClient } from './record-sink';
90
92
  export { fillTemplate, templateParams } from './route-path-template';
91
93
  export { onSessionLost, sessionIsLost } from './session-lost';
94
+ export { isSessionRefusalCode } from './session-refusal';
92
95
  // The key the theme boot script reads and the toggle island writes.
93
96
  export { THEME_STORAGE_KEY } from './theme-storage';
94
97
  export { trimTrailingSlashes } from './trailing-slashes';