@smartcrab/tenant-context 0.1.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.
@@ -0,0 +1,71 @@
1
+ import { ENVIRONMENT_ID_PATTERN } from "./ids.js";
2
+ /**
3
+ * Domain and issuer helpers (design.md §8).
4
+ *
5
+ * These are pure string functions. They never read request headers: callers
6
+ * must pass `new URL(request.url).hostname`. `X-Forwarded-Host` and request
7
+ * bodies are explicitly not trusted for host resolution (§8.2).
8
+ */
9
+ /**
10
+ * Canonical issuer for an Environment: `https://id.<root>/e/<envId>`.
11
+ * The issuer never changes after Environment creation, even when a custom
12
+ * interaction domain is configured (§8.1).
13
+ */
14
+ export const buildCanonicalIssuer = (platformRootDomain, environmentId) => `https://id.${platformRootDomain}/e/${environmentId}`;
15
+ /**
16
+ * Default interaction (Hosted Login) domain for an Environment (§8, §8.3
17
+ * default RP ID mode): `<label>.login.<root>` where `<label>` is the
18
+ * Environment id with its `env_` prefix written as `env-`.
19
+ *
20
+ * Documented deviation from §8's literal `env_xxx.login.<root>` (IMPL_NOTES
21
+ * rule 1): an underscore is not valid in a hostname label (RFC 1123), so
22
+ * Cloudflare refuses to attach such a name as a Workers Custom Domain or to
23
+ * issue a certificate for it, and WebAuthn requires the RP ID to be a valid
24
+ * domain. `env-<body>` is unambiguous (ids have exactly one underscore) and
25
+ * keeps the label parseable back to the id. `parseEnvironmentIdFromLoginHost`
26
+ * accepts both spellings so rows written before this change keep resolving.
27
+ */
28
+ export const buildDefaultInteractionDomain = (environmentId, rootDomain) => `${loginHostLabel(environmentId)}.login.${rootDomain}`;
29
+ /** `env_<body>` -> `env-<body>`: the DNS-safe label for an Environment id. */
30
+ export const loginHostLabel = (environmentId) => environmentId.replace(/^env_/, "env-");
31
+ /**
32
+ * Inverse of `loginHostLabel`. Accepts the DNS-safe `env-<body>` label and
33
+ * the legacy literal `env_<body>`; anything else is null.
34
+ */
35
+ export const environmentIdFromLoginHostLabel = (label) => {
36
+ const candidate = label.replace(/^env-/, "env_");
37
+ return ENVIRONMENT_ID_PATTERN.test(candidate) ? candidate : null;
38
+ };
39
+ /**
40
+ * Management API origin for this deployment: `https://api.<root>` (§8's
41
+ * domain table). Response bodies that hand a caller a Management API URL
42
+ * (user import/export artifacts) must build it from the deployment's own
43
+ * root domain rather than embedding a literal host.
44
+ */
45
+ export const buildManagementApiOrigin = (platformRootDomain) => `https://api.${platformRootDomain}`;
46
+ /** DNS names are case-insensitive; a single trailing root dot is ignored. */
47
+ const normalizeHost = (value) => {
48
+ const lower = value.trim().toLowerCase();
49
+ return lower.endsWith(".") ? lower.slice(0, -1) : lower;
50
+ };
51
+ /**
52
+ * Extracts the Environment ID from a default login host
53
+ * (`<envId>.login.<root>`), step 1 of host resolution in §8.2.
54
+ *
55
+ * Returns null for anything else: unknown suffixes, multi-label prefixes,
56
+ * malformed IDs, ports, and near-miss hosts such as
57
+ * `evil-login.example-auth.com` (the `.login.` label boundary is required).
58
+ */
59
+ export const parseEnvironmentIdFromLoginHost = (hostname, rootDomain) => {
60
+ const host = normalizeHost(hostname);
61
+ // A colon means a port or a non-DNS value (e.g. an IP literal) — never a
62
+ // valid login host.
63
+ if (host.includes(":")) {
64
+ return null;
65
+ }
66
+ const suffix = `.login.${normalizeHost(rootDomain)}`;
67
+ if (!host.endsWith(suffix)) {
68
+ return null;
69
+ }
70
+ return environmentIdFromLoginHostLabel(host.slice(0, host.length - suffix.length));
71
+ };
package/dist/ids.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ import { z } from "zod";
2
+ export declare const CELL_ID_PATTERN: RegExp;
3
+ export declare const WORKSPACE_ID_PATTERN: RegExp;
4
+ export declare const PROJECT_ID_PATTERN: RegExp;
5
+ export declare const ENVIRONMENT_ID_PATTERN: RegExp;
6
+ export declare const USER_ID_PATTERN: RegExp;
7
+ /** Auth partition IDs (`prt_...`) identify EnvironmentAuthPartition rows (design.md §10.5). */
8
+ export declare const AUTH_PARTITION_ID_PATTERN: RegExp;
9
+ /** Branded cell ID: a `cel_`-prefixed resource ID for a deployment cell. */
10
+ export declare const cellIdSchema: z.core.$ZodBranded<z.ZodString, "CellId", "out">;
11
+ export type CellId = z.infer<typeof cellIdSchema>;
12
+ export declare const workspaceIdSchema: z.ZodString;
13
+ export declare const projectIdSchema: z.ZodString;
14
+ export declare const environmentIdSchema: z.ZodString;
15
+ export declare const userIdSchema: z.ZodString;
16
+ export declare const authPartitionIdSchema: z.ZodString;
17
+ export declare const isCellId: (value: unknown) => value is CellId;
package/dist/ids.js ADDED
@@ -0,0 +1,26 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * Resource identifier shapes (design.md §7.5): a meaningful prefix plus 32
4
+ * base32url characters (160 bits of cryptographic randomness). Values are
5
+ * generated by `@smartcrab/identifiers`; the patterns here validate them
6
+ * at trust boundaries without depending on the generator package.
7
+ *
8
+ * Sequential, email-derived, or timestamp-only predictable IDs are forbidden.
9
+ */
10
+ /** 160-bit base32url body shared by all prefixed resource IDs. */
11
+ const ID_BODY = "[a-z2-7]{32}";
12
+ export const CELL_ID_PATTERN = new RegExp(`^cel_${ID_BODY}$`);
13
+ export const WORKSPACE_ID_PATTERN = new RegExp(`^wsp_${ID_BODY}$`);
14
+ export const PROJECT_ID_PATTERN = new RegExp(`^prj_${ID_BODY}$`);
15
+ export const ENVIRONMENT_ID_PATTERN = new RegExp(`^env_${ID_BODY}$`);
16
+ export const USER_ID_PATTERN = new RegExp(`^usr_${ID_BODY}$`);
17
+ /** Auth partition IDs (`prt_...`) identify EnvironmentAuthPartition rows (design.md §10.5). */
18
+ export const AUTH_PARTITION_ID_PATTERN = new RegExp(`^prt_${ID_BODY}$`);
19
+ /** Branded cell ID: a `cel_`-prefixed resource ID for a deployment cell. */
20
+ export const cellIdSchema = z.string().regex(CELL_ID_PATTERN).brand();
21
+ export const workspaceIdSchema = z.string().regex(WORKSPACE_ID_PATTERN);
22
+ export const projectIdSchema = z.string().regex(PROJECT_ID_PATTERN);
23
+ export const environmentIdSchema = z.string().regex(ENVIRONMENT_ID_PATTERN);
24
+ export const userIdSchema = z.string().regex(USER_ID_PATTERN);
25
+ export const authPartitionIdSchema = z.string().regex(AUTH_PARTITION_ID_PATTERN);
26
+ export const isCellId = (value) => typeof value === "string" && CELL_ID_PATTERN.test(value);
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @smartcrab/tenant-context — tenant resolution primitives.
3
+ *
4
+ * - `TenantContext` / `AuthLocation` contracts (design.md §9) with zod schemas
5
+ * and never-throwing typed parsers.
6
+ * - Branded physical database keys (`control_nn` / `auth_nnn` / `platform`)
7
+ * with round-trippable wrangler binding names (design.md §10.2, §10.3).
8
+ * - Resource ID validation patterns matching `@smartcrab/identifiers`
9
+ * (design.md §7.5).
10
+ * - Issuer / interaction-domain helpers (design.md §8).
11
+ */
12
+ export * from "./context.js";
13
+ export * from "./database-keys.js";
14
+ export * from "./domains.js";
15
+ export * from "./ids.js";
16
+ export * from "./validation.js";
package/dist/index.js ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @smartcrab/tenant-context — tenant resolution primitives.
3
+ *
4
+ * - `TenantContext` / `AuthLocation` contracts (design.md §9) with zod schemas
5
+ * and never-throwing typed parsers.
6
+ * - Branded physical database keys (`control_nn` / `auth_nnn` / `platform`)
7
+ * with round-trippable wrangler binding names (design.md §10.2, §10.3).
8
+ * - Resource ID validation patterns matching `@smartcrab/identifiers`
9
+ * (design.md §7.5).
10
+ * - Issuer / interaction-domain helpers (design.md §8).
11
+ */
12
+ export * from "./context.js";
13
+ export * from "./database-keys.js";
14
+ export * from "./domains.js";
15
+ export * from "./ids.js";
16
+ export * from "./validation.js";
@@ -0,0 +1,33 @@
1
+ import type { z } from "zod";
2
+ /**
3
+ * Outcome of a never-throwing parse helper.
4
+ *
5
+ * This package is runtime-agnostic (tsconfig `types: []`), so it deliberately
6
+ * does not depend on `@smartcrab/result` (whose source needs DOM/workers
7
+ * ambient types). The shape mirrors the byethrow `Result` convention:
8
+ * discriminate on `ok`.
9
+ */
10
+ export type ParseOutcome<T, E> = {
11
+ readonly ok: true;
12
+ readonly value: T;
13
+ } | {
14
+ readonly ok: false;
15
+ readonly error: E;
16
+ };
17
+ export declare const parseOk: <T, E>(value: T) => ParseOutcome<T, E>;
18
+ export declare const parseErr: <T, E>(error: E) => ParseOutcome<T, E>;
19
+ /**
20
+ * Serializable description of a single schema violation.
21
+ *
22
+ * Deliberately contains no zod internals (`z.core.$ZodIssue` carries regexes,
23
+ * schema references and input values that must not leak across trust
24
+ * boundaries or into logs verbatim).
25
+ */
26
+ export interface ValidationIssue {
27
+ /** Dot-joined path to the offending value, e.g. `appearance.primaryColor`. */
28
+ readonly path: string;
29
+ /** zod issue code, e.g. `invalid_format`, `too_small`, `invalid_value`. */
30
+ readonly code: string;
31
+ readonly message: string;
32
+ }
33
+ export declare const toValidationIssues: (error: z.ZodError) => readonly ValidationIssue[];
@@ -0,0 +1,7 @@
1
+ export const parseOk = (value) => ({ ok: true, value });
2
+ export const parseErr = (error) => ({ ok: false, error });
3
+ export const toValidationIssues = (error) => error.issues.map((issue) => ({
4
+ path: issue.path.map((segment) => String(segment)).join("."),
5
+ code: issue.code,
6
+ message: issue.message,
7
+ }));
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@smartcrab/tenant-context",
3
+ "version": "0.1.0",
4
+ "license": "Apache-2.0",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./src/index.ts",
11
+ "development": "./src/index.ts",
12
+ "import": "./dist/index.js",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "./*": {
16
+ "types": "./src/*.ts",
17
+ "development": "./src/*.ts",
18
+ "import": "./dist/*.js",
19
+ "default": "./dist/*.js"
20
+ }
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "src"
25
+ ],
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "dependencies": {
30
+ "zod": "4.4.3",
31
+ "@smartcrab/result": "0.1.0"
32
+ },
33
+ "devDependencies": {
34
+ "typescript": "5.9.3",
35
+ "vitest": "4.1.11"
36
+ },
37
+ "scripts": {
38
+ "typecheck": "tsc --noEmit",
39
+ "test": "vitest run --passWithNoTests",
40
+ "build": "tsc -p tsconfig.build.json"
41
+ }
42
+ }
@@ -0,0 +1,181 @@
1
+ import { describe, expect, test } from "vitest";
2
+ import {
3
+ AUTH_METHODS,
4
+ CLIENT_TYPES,
5
+ ENVIRONMENT_TYPES,
6
+ authLocationSchema,
7
+ authMethodSchema,
8
+ clientTypeSchema,
9
+ environmentTypeSchema,
10
+ parseAuthLocation,
11
+ parseTenantContext,
12
+ tenantContextSchema,
13
+ } from "./context.js";
14
+ import { isCellId } from "./ids.js";
15
+
16
+ const ENV_ID = `env_${"d".repeat(32)}`;
17
+
18
+ const validTenantContext = {
19
+ cellId: `cel_${"a".repeat(32)}`,
20
+ workspaceId: `wsp_${"b".repeat(32)}`,
21
+ projectId: `prj_${"c".repeat(32)}`,
22
+ applicationName: "Example App",
23
+ environmentId: ENV_ID,
24
+ environmentType: "test",
25
+ controlDatabaseKey: "control_02",
26
+ authRoutingVersion: 1,
27
+ issuer: `https://id.example-auth.com/e/${ENV_ID}`,
28
+ interactionOrigin: `https://${ENV_ID}.login.example-auth.com`,
29
+ defaultInteractionOrigin: `https://${ENV_ID}.login.example-auth.com`,
30
+ rpId: `${ENV_ID}.login.example-auth.com`,
31
+ allowedOrigins: ["https://app.customer.example", "https://admin.customer.example"],
32
+ enabledMethods: ["passkey", "email_otp", "google"],
33
+ configVersion: 3,
34
+ themeVersion: 2,
35
+ } as const;
36
+
37
+ const validAuthLocation = {
38
+ cellId: `cel_${"a".repeat(32)}`,
39
+ authDatabaseKey: "auth_007",
40
+ authPartitionId: `prt_${"e".repeat(32)}`,
41
+ environmentId: ENV_ID,
42
+ userId: `usr_${"f".repeat(32)}`,
43
+ routingVersion: 1,
44
+ } as const;
45
+
46
+ describe("authMethodSchema", () => {
47
+ test("accepts every platform auth method (design §20.1)", () => {
48
+ expect(AUTH_METHODS).toEqual([
49
+ "passkey",
50
+ "email_otp",
51
+ "google",
52
+ "apple",
53
+ "github",
54
+ "microsoft",
55
+ "generic_oidc",
56
+ ]);
57
+ for (const method of AUTH_METHODS) {
58
+ expect(authMethodSchema.safeParse(method).success).toBe(true);
59
+ }
60
+ });
61
+
62
+ test("rejects legacy or unknown methods", () => {
63
+ for (const method of ["password", "sms", "magic_link", "oidc", ""]) {
64
+ expect(authMethodSchema.safeParse(method).success).toBe(false);
65
+ }
66
+ });
67
+ });
68
+
69
+ describe("environmentTypeSchema / clientTypeSchema", () => {
70
+ test("environment types are exactly test and production", () => {
71
+ expect(ENVIRONMENT_TYPES).toEqual(["test", "production"]);
72
+ expect(environmentTypeSchema.safeParse("test").success).toBe(true);
73
+ expect(environmentTypeSchema.safeParse("production").success).toBe(true);
74
+ expect(environmentTypeSchema.safeParse("staging").success).toBe(false);
75
+ });
76
+
77
+ test("client types match design §7.4", () => {
78
+ expect(CLIENT_TYPES).toEqual(["web_bff", "web_spa", "react_native"]);
79
+ for (const clientType of CLIENT_TYPES) {
80
+ expect(clientTypeSchema.safeParse(clientType).success).toBe(true);
81
+ }
82
+ expect(clientTypeSchema.safeParse("web").success).toBe(false);
83
+ expect(clientTypeSchema.safeParse("ios").success).toBe(false);
84
+ });
85
+ });
86
+
87
+ describe("tenantContextSchema", () => {
88
+ test("accepts a fully valid context", () => {
89
+ const parsed = tenantContextSchema.safeParse(validTenantContext);
90
+ expect(parsed.success).toBe(true);
91
+ if (parsed.success) {
92
+ expect(parsed.data.controlDatabaseKey).toBe("control_02");
93
+ expect(isCellId(parsed.data.cellId)).toBe(true);
94
+ }
95
+ });
96
+
97
+ test("rejects invalid variants", () => {
98
+ const cases: Record<string, unknown>[] = [
99
+ { ...validTenantContext, environmentType: "staging" },
100
+ { ...validTenantContext, controlDatabaseKey: "control_99" },
101
+ { ...validTenantContext, controlDatabaseKey: "auth_000" },
102
+ { ...validTenantContext, issuer: "http://id.example-auth.com/e/x" },
103
+ { ...validTenantContext, issuer: "not-a-url" },
104
+ { ...validTenantContext, interactionOrigin: "http://login.example-auth.com" },
105
+ { ...validTenantContext, allowedOrigins: ["https://ok.example", "http://insecure.example"] },
106
+ { ...validTenantContext, rpId: "https://env.example.com" },
107
+ { ...validTenantContext, enabledMethods: [] },
108
+ { ...validTenantContext, enabledMethods: ["passkey", "password"] },
109
+ { ...validTenantContext, authRoutingVersion: 0 },
110
+ { ...validTenantContext, configVersion: 1.5 },
111
+ { ...validTenantContext, themeVersion: -1 },
112
+ { ...validTenantContext, environmentId: "env_short" },
113
+ { ...validTenantContext, cellId: "wsp_" + "a".repeat(32) },
114
+ ];
115
+ for (const input of cases) {
116
+ expect(tenantContextSchema.safeParse(input).success).toBe(false);
117
+ }
118
+ });
119
+ });
120
+
121
+ describe("authLocationSchema", () => {
122
+ test("accepts a fully valid location", () => {
123
+ expect(authLocationSchema.safeParse(validAuthLocation).success).toBe(true);
124
+ });
125
+
126
+ test("rejects invalid variants", () => {
127
+ const cases: Record<string, unknown>[] = [
128
+ { ...validAuthLocation, authDatabaseKey: "auth_128" },
129
+ { ...validAuthLocation, authDatabaseKey: "control_00" },
130
+ { ...validAuthLocation, authPartitionId: "prt_short" },
131
+ { ...validAuthLocation, userId: "usr_bad body" },
132
+ { ...validAuthLocation, routingVersion: 0 },
133
+ ];
134
+ for (const input of cases) {
135
+ expect(authLocationSchema.safeParse(input).success).toBe(false);
136
+ }
137
+ });
138
+ });
139
+
140
+ describe("parseTenantContext / parseAuthLocation", () => {
141
+ test("parseTenantContext succeeds on valid input", () => {
142
+ const result = parseTenantContext(validTenantContext);
143
+ expect(result.ok).toBe(true);
144
+ if (result.ok) {
145
+ expect(result.value.environmentId).toBe(ENV_ID);
146
+ expect(result.value.enabledMethods).toEqual(["passkey", "email_otp", "google"]);
147
+ }
148
+ });
149
+
150
+ test("parseTenantContext fails with typed issues and never throws", () => {
151
+ for (const garbage of [null, undefined, 42, "x", {}, { ...validTenantContext, issuer: 7 }]) {
152
+ const result = parseTenantContext(garbage);
153
+ expect(result.ok).toBe(false);
154
+ if (!result.ok) {
155
+ expect(result.error.type).toBe("invalid_tenant_context");
156
+ expect(result.error.issues.length).toBeGreaterThan(0);
157
+ const first = result.error.issues[0];
158
+ expect(typeof first?.path).toBe("string");
159
+ expect(typeof first?.code).toBe("string");
160
+ expect(typeof first?.message).toBe("string");
161
+ }
162
+ }
163
+ });
164
+
165
+ test("parseAuthLocation succeeds on valid input", () => {
166
+ const result = parseAuthLocation(validAuthLocation);
167
+ expect(result.ok).toBe(true);
168
+ if (result.ok) {
169
+ expect(result.value.authDatabaseKey).toBe("auth_007");
170
+ }
171
+ });
172
+
173
+ test("parseAuthLocation fails with typed error on invalid input", () => {
174
+ const result = parseAuthLocation({ ...validAuthLocation, authDatabaseKey: "auth_200" });
175
+ expect(result.ok).toBe(false);
176
+ if (!result.ok) {
177
+ expect(result.error.type).toBe("invalid_auth_location");
178
+ expect(result.error.issues.length).toBeGreaterThan(0);
179
+ }
180
+ });
181
+ });
package/src/context.ts ADDED
@@ -0,0 +1,190 @@
1
+ import { z } from "zod";
2
+ import { authDatabaseKeySchema, controlDatabaseKeySchema } from "./database-keys.js";
3
+ import type { AuthDatabaseKey, ControlDatabaseKey } from "./database-keys.js";
4
+ import {
5
+ authPartitionIdSchema,
6
+ cellIdSchema,
7
+ environmentIdSchema,
8
+ projectIdSchema,
9
+ userIdSchema,
10
+ workspaceIdSchema,
11
+ } from "./ids.js";
12
+ import { parseErr, parseOk, toValidationIssues } from "./validation.js";
13
+ import type { ParseOutcome, ValidationIssue } from "./validation.js";
14
+
15
+ // ---------------------------------------------------------------------------
16
+ // Enums
17
+ // ---------------------------------------------------------------------------
18
+
19
+ /**
20
+ * Authentication methods an Environment can enable (design.md §20.1, §23.2).
21
+ * Social providers double as methods; `generic_oidc` is a customer-configured
22
+ * OIDC connection.
23
+ */
24
+ export const AUTH_METHODS = [
25
+ "passkey",
26
+ "email_otp",
27
+ "google",
28
+ "apple",
29
+ "github",
30
+ "microsoft",
31
+ "generic_oidc",
32
+ ] as const;
33
+
34
+ export type AuthMethod = (typeof AUTH_METHODS)[number];
35
+ export const authMethodSchema = z.enum(AUTH_METHODS);
36
+
37
+ /** Builds enabled methods from active, already-authorized provider names. */
38
+ export const deriveEnabledAuthMethods = (providers: readonly string[]): readonly AuthMethod[] => {
39
+ const candidates = ["passkey", "email_otp", ...providers];
40
+ const validated = candidates.flatMap((candidate) => {
41
+ const parsed = authMethodSchema.safeParse(candidate);
42
+ return parsed.success ? [parsed.data] : [];
43
+ });
44
+ return [...new Set(validated)];
45
+ };
46
+
47
+ export const ENVIRONMENT_TYPES = ["test", "production"] as const;
48
+ export const environmentTypeSchema = z.enum(ENVIRONMENT_TYPES);
49
+ export type EnvironmentType = (typeof ENVIRONMENT_TYPES)[number];
50
+
51
+ /** Client kinds from design.md §7.4. */
52
+ export const CLIENT_TYPES = ["web_bff", "web_spa", "react_native"] as const;
53
+ export const clientTypeSchema = z.enum(CLIENT_TYPES);
54
+ export type ClientType = (typeof CLIENT_TYPES)[number];
55
+
56
+ // ---------------------------------------------------------------------------
57
+ // TenantContext / AuthLocation (design.md §9, verbatim contract)
58
+ // ---------------------------------------------------------------------------
59
+
60
+ /**
61
+ * Resolved once at the start of every authentication request. Route handlers
62
+ * must not call repositories with a bare `environmentId`; Control
63
+ * repositories are created via `forTenant(TenantContext)` and Auth
64
+ * repositories via `forLocation(TenantContext, AuthLocation)` only.
65
+ */
66
+ export interface TenantContext {
67
+ readonly cellId: string;
68
+ readonly workspaceId: string;
69
+ readonly projectId: string;
70
+ /** Human-readable project name used in end-user mail and hosted UI. */
71
+ readonly applicationName: string;
72
+ readonly environmentId: string;
73
+ readonly environmentType: "test" | "production";
74
+ readonly controlDatabaseKey: ControlDatabaseKey;
75
+ readonly authRoutingVersion: number;
76
+ readonly issuer: string;
77
+ readonly interactionOrigin: string;
78
+ /**
79
+ * The Environment's default Interaction Domain origin
80
+ * (`https://${environments.interaction_domain}`), independent of the request
81
+ * host or custom domain mode. Used where a stable, custom-domain-independent
82
+ * origin is required (e.g. BYO social callback URIs, design.md §20).
83
+ */
84
+ readonly defaultInteractionOrigin: string;
85
+ readonly rpId: string;
86
+ readonly allowedOrigins: readonly string[];
87
+ readonly enabledMethods: readonly AuthMethod[];
88
+ readonly configVersion: number;
89
+ readonly themeVersion: number;
90
+ }
91
+
92
+ export interface AuthLocation {
93
+ readonly cellId: string;
94
+ readonly authDatabaseKey: AuthDatabaseKey;
95
+ readonly authPartitionId: string;
96
+ readonly environmentId: string;
97
+ readonly userId: string;
98
+ readonly routingVersion: number;
99
+ }
100
+
101
+ // ---------------------------------------------------------------------------
102
+ // Schemas
103
+ // ---------------------------------------------------------------------------
104
+
105
+ /** Monotonic version counters (`routing_version`, `config_version`, ...) start at 1. */
106
+ const versionSchema = z.number().int().positive();
107
+
108
+ /** Issuer / origins are always https URLs (design.md §8). */
109
+ const httpsUrlSchema = z.url({ protocol: /^https$/ });
110
+
111
+ /**
112
+ * RP IDs and interaction domains are DNS names whose labels may contain
113
+ * underscores: default interaction domains embed `env_...` IDs
114
+ * (design.md §8.3), so strict LDH hostname validation is intentionally not
115
+ * applied.
116
+ */
117
+ const DOMAIN_PATTERN =
118
+ /^(?=.{1,253}$)[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9_])?(?:\.[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9_])?)*$/;
119
+
120
+ const domainSchema = z.string().regex(DOMAIN_PATTERN);
121
+
122
+ export const tenantContextSchema = z.object({
123
+ cellId: cellIdSchema,
124
+ workspaceId: workspaceIdSchema,
125
+ projectId: projectIdSchema,
126
+ applicationName: z.string(),
127
+ environmentId: environmentIdSchema,
128
+ environmentType: environmentTypeSchema,
129
+ controlDatabaseKey: controlDatabaseKeySchema,
130
+ authRoutingVersion: versionSchema,
131
+ issuer: httpsUrlSchema,
132
+ interactionOrigin: httpsUrlSchema,
133
+ defaultInteractionOrigin: httpsUrlSchema,
134
+ rpId: domainSchema,
135
+ allowedOrigins: z.array(httpsUrlSchema),
136
+ enabledMethods: z.array(authMethodSchema).min(1),
137
+ configVersion: versionSchema,
138
+ themeVersion: versionSchema,
139
+ });
140
+
141
+ export const authLocationSchema = z.object({
142
+ cellId: cellIdSchema,
143
+ authDatabaseKey: authDatabaseKeySchema,
144
+ authPartitionId: authPartitionIdSchema,
145
+ environmentId: environmentIdSchema,
146
+ userId: userIdSchema,
147
+ routingVersion: versionSchema,
148
+ });
149
+
150
+ // ---------------------------------------------------------------------------
151
+ // Typed parse (trust boundaries: directory DO state, control D1 rows)
152
+ // ---------------------------------------------------------------------------
153
+
154
+ export interface InvalidTenantContextError {
155
+ readonly type: "invalid_tenant_context";
156
+ readonly issues: readonly ValidationIssue[];
157
+ }
158
+
159
+ /** Validates untrusted input as a TenantContext. Never throws. */
160
+ export const parseTenantContext = (
161
+ input: unknown,
162
+ ): ParseOutcome<TenantContext, InvalidTenantContextError> => {
163
+ const parsed = tenantContextSchema.safeParse(input);
164
+ if (parsed.success) {
165
+ return parseOk(parsed.data);
166
+ }
167
+ return parseErr({
168
+ type: "invalid_tenant_context",
169
+ issues: toValidationIssues(parsed.error),
170
+ });
171
+ };
172
+
173
+ export interface InvalidAuthLocationError {
174
+ readonly type: "invalid_auth_location";
175
+ readonly issues: readonly ValidationIssue[];
176
+ }
177
+
178
+ /** Validates untrusted input as an AuthLocation. Never throws. */
179
+ export const parseAuthLocation = (
180
+ input: unknown,
181
+ ): ParseOutcome<AuthLocation, InvalidAuthLocationError> => {
182
+ const parsed = authLocationSchema.safeParse(input);
183
+ if (parsed.success) {
184
+ return parseOk(parsed.data);
185
+ }
186
+ return parseErr({
187
+ type: "invalid_auth_location",
188
+ issues: toValidationIssues(parsed.error),
189
+ });
190
+ };