@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.
- package/LICENSE +202 -0
- package/dist/context.d.ts +123 -0
- package/dist/context.js +99 -0
- package/dist/database-keys.d.ts +55 -0
- package/dist/database-keys.js +92 -0
- package/dist/domains.d.ts +50 -0
- package/dist/domains.js +71 -0
- package/dist/ids.d.ts +17 -0
- package/dist/ids.js +26 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +16 -0
- package/dist/validation.d.ts +33 -0
- package/dist/validation.js +7 -0
- package/package.json +42 -0
- package/src/context.test.ts +181 -0
- package/src/context.ts +190 -0
- package/src/database-keys.test.ts +222 -0
- package/src/database-keys.ts +140 -0
- package/src/domains.test.ts +120 -0
- package/src/domains.ts +86 -0
- package/src/ids.ts +34 -0
- package/src/index.ts +16 -0
- package/src/validation.ts +39 -0
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
import { describe, expect, test } from "vitest";
|
|
2
|
+
import {
|
|
3
|
+
authDatabaseKeySchema,
|
|
4
|
+
bindingNameToKey,
|
|
5
|
+
controlDatabaseKeySchema,
|
|
6
|
+
databaseKeySchema,
|
|
7
|
+
isAuthDatabaseKey,
|
|
8
|
+
isControlDatabaseKey,
|
|
9
|
+
isDatabaseKey,
|
|
10
|
+
isPlatformDatabaseKey,
|
|
11
|
+
keyToBindingName,
|
|
12
|
+
parseDatabaseKey,
|
|
13
|
+
platformDatabaseKeySchema,
|
|
14
|
+
} from "./database-keys.js";
|
|
15
|
+
import type { DatabaseKey } from "./database-keys.js";
|
|
16
|
+
|
|
17
|
+
describe("database key schemas", () => {
|
|
18
|
+
test("accepts control keys within the provisioned range 00-31", () => {
|
|
19
|
+
for (const key of [
|
|
20
|
+
"control_00",
|
|
21
|
+
"control_01",
|
|
22
|
+
"control_09",
|
|
23
|
+
"control_29",
|
|
24
|
+
"control_30",
|
|
25
|
+
"control_31",
|
|
26
|
+
]) {
|
|
27
|
+
expect(controlDatabaseKeySchema.safeParse(key).success).toBe(true);
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
test("rejects control keys outside the range or malformed", () => {
|
|
32
|
+
for (const key of [
|
|
33
|
+
"control_32",
|
|
34
|
+
"control_99",
|
|
35
|
+
"control_1",
|
|
36
|
+
"control_001",
|
|
37
|
+
"control_0a",
|
|
38
|
+
"CONTROL_00",
|
|
39
|
+
"control00",
|
|
40
|
+
"control_",
|
|
41
|
+
"",
|
|
42
|
+
]) {
|
|
43
|
+
expect(controlDatabaseKeySchema.safeParse(key).success).toBe(false);
|
|
44
|
+
}
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
test("accepts auth keys within the provisioned range 000-127", () => {
|
|
48
|
+
for (const key of [
|
|
49
|
+
"auth_000",
|
|
50
|
+
"auth_007",
|
|
51
|
+
"auth_042",
|
|
52
|
+
"auth_099",
|
|
53
|
+
"auth_100",
|
|
54
|
+
"auth_119",
|
|
55
|
+
"auth_120",
|
|
56
|
+
"auth_127",
|
|
57
|
+
]) {
|
|
58
|
+
expect(authDatabaseKeySchema.safeParse(key).success).toBe(true);
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
test("rejects auth keys outside the range or malformed", () => {
|
|
63
|
+
for (const key of [
|
|
64
|
+
"auth_128",
|
|
65
|
+
"auth_129",
|
|
66
|
+
"auth_130",
|
|
67
|
+
"auth_999",
|
|
68
|
+
"auth_00",
|
|
69
|
+
"auth_0000",
|
|
70
|
+
"AUTH_000",
|
|
71
|
+
"auth-000",
|
|
72
|
+
"",
|
|
73
|
+
]) {
|
|
74
|
+
expect(authDatabaseKeySchema.safeParse(key).success).toBe(false);
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
test("platform key is exactly the literal 'platform'", () => {
|
|
79
|
+
expect(platformDatabaseKeySchema.safeParse("platform").success).toBe(true);
|
|
80
|
+
expect(platformDatabaseKeySchema.safeParse("PLATFORM").success).toBe(false);
|
|
81
|
+
expect(platformDatabaseKeySchema.safeParse("platform_db").success).toBe(false);
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
test("databaseKeySchema accepts every tier", () => {
|
|
85
|
+
expect(databaseKeySchema.safeParse("control_00").success).toBe(true);
|
|
86
|
+
expect(databaseKeySchema.safeParse("auth_127").success).toBe(true);
|
|
87
|
+
expect(databaseKeySchema.safeParse("platform").success).toBe(true);
|
|
88
|
+
expect(databaseKeySchema.safeParse("control_32").success).toBe(false);
|
|
89
|
+
});
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
describe("database key guards", () => {
|
|
93
|
+
test("type guards classify values", () => {
|
|
94
|
+
expect(isControlDatabaseKey("control_00")).toBe(true);
|
|
95
|
+
expect(isControlDatabaseKey("auth_000")).toBe(false);
|
|
96
|
+
expect(isAuthDatabaseKey("auth_000")).toBe(true);
|
|
97
|
+
expect(isAuthDatabaseKey("auth_128")).toBe(false);
|
|
98
|
+
expect(isPlatformDatabaseKey("platform")).toBe(true);
|
|
99
|
+
expect(isPlatformDatabaseKey("control_00")).toBe(false);
|
|
100
|
+
expect(isDatabaseKey("platform")).toBe(true);
|
|
101
|
+
expect(isDatabaseKey(42)).toBe(false);
|
|
102
|
+
expect(isDatabaseKey(null)).toBe(false);
|
|
103
|
+
expect(isDatabaseKey(undefined)).toBe(false);
|
|
104
|
+
});
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
describe("keyToBindingName", () => {
|
|
108
|
+
test("maps keys to wrangler binding names", () => {
|
|
109
|
+
const control = controlDatabaseKeySchema.parse("control_00");
|
|
110
|
+
const controlMax = controlDatabaseKeySchema.parse("control_31");
|
|
111
|
+
const auth = authDatabaseKeySchema.parse("auth_000");
|
|
112
|
+
const authMax = authDatabaseKeySchema.parse("auth_127");
|
|
113
|
+
const platform = platformDatabaseKeySchema.parse("platform");
|
|
114
|
+
|
|
115
|
+
expect(keyToBindingName(control)).toBe("CONTROL_DB_00");
|
|
116
|
+
expect(keyToBindingName(controlMax)).toBe("CONTROL_DB_31");
|
|
117
|
+
expect(keyToBindingName(auth)).toBe("AUTH_DB_000");
|
|
118
|
+
expect(keyToBindingName(authMax)).toBe("AUTH_DB_127");
|
|
119
|
+
expect(keyToBindingName(platform)).toBe("PLATFORM_DB");
|
|
120
|
+
});
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
describe("bindingNameToKey", () => {
|
|
124
|
+
test("parses provisioned binding names", () => {
|
|
125
|
+
expect(bindingNameToKey("CONTROL_DB_00")).toBe("control_00");
|
|
126
|
+
expect(bindingNameToKey("CONTROL_DB_31")).toBe("control_31");
|
|
127
|
+
expect(bindingNameToKey("AUTH_DB_000")).toBe("auth_000");
|
|
128
|
+
expect(bindingNameToKey("AUTH_DB_127")).toBe("auth_127");
|
|
129
|
+
expect(bindingNameToKey("PLATFORM_DB")).toBe("platform");
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
test("rejects out-of-range, malformed, or wrongly-cased names", () => {
|
|
133
|
+
for (const name of [
|
|
134
|
+
"CONTROL_DB_32",
|
|
135
|
+
"CONTROL_DB_99",
|
|
136
|
+
"CONTROL_DB_0",
|
|
137
|
+
"CONTROL_DB_000",
|
|
138
|
+
"AUTH_DB_128",
|
|
139
|
+
"AUTH_DB_999",
|
|
140
|
+
"AUTH_DB_00",
|
|
141
|
+
"AUTH_DB_0000",
|
|
142
|
+
"platform_db",
|
|
143
|
+
"control_db_00",
|
|
144
|
+
"PLATFORM_DB ",
|
|
145
|
+
" PLATFORM_DB",
|
|
146
|
+
"control_00",
|
|
147
|
+
"platform",
|
|
148
|
+
"",
|
|
149
|
+
]) {
|
|
150
|
+
expect(bindingNameToKey(name)).toBeNull();
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
describe("key/binding round trips", () => {
|
|
156
|
+
test("key -> binding -> key is the identity for representative keys", () => {
|
|
157
|
+
const keys: DatabaseKey[] = [
|
|
158
|
+
controlDatabaseKeySchema.parse("control_00"),
|
|
159
|
+
controlDatabaseKeySchema.parse("control_09"),
|
|
160
|
+
controlDatabaseKeySchema.parse("control_31"),
|
|
161
|
+
authDatabaseKeySchema.parse("auth_000"),
|
|
162
|
+
authDatabaseKeySchema.parse("auth_042"),
|
|
163
|
+
authDatabaseKeySchema.parse("auth_127"),
|
|
164
|
+
platformDatabaseKeySchema.parse("platform"),
|
|
165
|
+
];
|
|
166
|
+
for (const key of keys) {
|
|
167
|
+
expect(bindingNameToKey(keyToBindingName(key))).toBe(key);
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
test("binding -> key -> binding is the identity for representative bindings", () => {
|
|
172
|
+
for (const name of [
|
|
173
|
+
"CONTROL_DB_00",
|
|
174
|
+
"CONTROL_DB_03",
|
|
175
|
+
"CONTROL_DB_31",
|
|
176
|
+
"AUTH_DB_000",
|
|
177
|
+
"AUTH_DB_007",
|
|
178
|
+
"AUTH_DB_127",
|
|
179
|
+
"PLATFORM_DB",
|
|
180
|
+
]) {
|
|
181
|
+
const key = bindingNameToKey(name);
|
|
182
|
+
expect(key).not.toBeNull();
|
|
183
|
+
if (key !== null) {
|
|
184
|
+
expect(keyToBindingName(key)).toBe(name);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
test("exhaustive round trip over the whole provisioned shard space", () => {
|
|
190
|
+
for (let i = 0; i <= 31; i += 1) {
|
|
191
|
+
const suffix = i.toString().padStart(2, "0");
|
|
192
|
+
const key = controlDatabaseKeySchema.parse(`control_${suffix}`);
|
|
193
|
+
expect(keyToBindingName(key)).toBe(`CONTROL_DB_${suffix}`);
|
|
194
|
+
expect(bindingNameToKey(`CONTROL_DB_${suffix}`)).toBe(`control_${suffix}`);
|
|
195
|
+
}
|
|
196
|
+
for (let i = 0; i <= 127; i += 1) {
|
|
197
|
+
const suffix = i.toString().padStart(3, "0");
|
|
198
|
+
const key = authDatabaseKeySchema.parse(`auth_${suffix}`);
|
|
199
|
+
expect(keyToBindingName(key)).toBe(`AUTH_DB_${suffix}`);
|
|
200
|
+
expect(bindingNameToKey(`AUTH_DB_${suffix}`)).toBe(`auth_${suffix}`);
|
|
201
|
+
}
|
|
202
|
+
});
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
describe("parseDatabaseKey", () => {
|
|
206
|
+
test("succeeds for valid keys", () => {
|
|
207
|
+
const result = parseDatabaseKey("control_02");
|
|
208
|
+
expect(result.ok).toBe(true);
|
|
209
|
+
if (result.ok) {
|
|
210
|
+
expect(result.value).toBe("control_02");
|
|
211
|
+
}
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
test("fails with a typed error for invalid input", () => {
|
|
215
|
+
const result = parseDatabaseKey("control_99");
|
|
216
|
+
expect(result.ok).toBe(false);
|
|
217
|
+
if (!result.ok) {
|
|
218
|
+
expect(result.error.type).toBe("invalid_database_key");
|
|
219
|
+
expect(result.error.issues.length).toBeGreaterThan(0);
|
|
220
|
+
}
|
|
221
|
+
});
|
|
222
|
+
});
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { parseErr, parseOk, toValidationIssues } from "./validation.js";
|
|
3
|
+
import type { ParseOutcome, ValidationIssue } from "./validation.js";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Physical D1 database keys and their wrangler binding names (design.md
|
|
7
|
+
* §10.2). The platform is a three-tier layout:
|
|
8
|
+
*
|
|
9
|
+
* - `platform` -> PLATFORM_DB (registry, workspace routing)
|
|
10
|
+
* - `control_nn` -> CONTROL_DB_00 .. 31 (workspace/project/environment)
|
|
11
|
+
* - `auth_nnn` -> AUTH_DB_000 .. 127 (users, sessions, passkeys)
|
|
12
|
+
*
|
|
13
|
+
* The schemas enforce the documented shard bounds so a parsed key can never
|
|
14
|
+
* resolve to a binding the platform does not provision (§10.3: bindings are
|
|
15
|
+
* statically fixed at deploy time).
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
export const CONTROL_DATABASE_KEY_PATTERN = /^control_(?:[0-2]\d|3[01])$/;
|
|
19
|
+
export const AUTH_DATABASE_KEY_PATTERN = /^auth_(?:0\d\d|1[01]\d|12[0-7])$/;
|
|
20
|
+
export const PLATFORM_DATABASE_KEY_PATTERN = /^platform$/;
|
|
21
|
+
|
|
22
|
+
/** Branded key of a Control D1 shard, e.g. `control_00` (range 00-31). */
|
|
23
|
+
export const controlDatabaseKeySchema = z
|
|
24
|
+
.string()
|
|
25
|
+
.regex(CONTROL_DATABASE_KEY_PATTERN)
|
|
26
|
+
.brand<"ControlDatabaseKey">();
|
|
27
|
+
export type ControlDatabaseKey = z.infer<typeof controlDatabaseKeySchema>;
|
|
28
|
+
|
|
29
|
+
/** Branded key of an Auth D1 shard, e.g. `auth_000` (range 000-127, 3 digits). */
|
|
30
|
+
export const authDatabaseKeySchema = z
|
|
31
|
+
.string()
|
|
32
|
+
.regex(AUTH_DATABASE_KEY_PATTERN)
|
|
33
|
+
.brand<"AuthDatabaseKey">();
|
|
34
|
+
export type AuthDatabaseKey = z.infer<typeof authDatabaseKeySchema>;
|
|
35
|
+
|
|
36
|
+
/** Branded key of the singleton Platform D1 database: the literal `platform`. */
|
|
37
|
+
export const platformDatabaseKeySchema = z.literal("platform").brand<"PlatformDatabaseKey">();
|
|
38
|
+
export type PlatformDatabaseKey = z.infer<typeof platformDatabaseKeySchema>;
|
|
39
|
+
|
|
40
|
+
export const databaseKeySchema = z.union([
|
|
41
|
+
controlDatabaseKeySchema,
|
|
42
|
+
authDatabaseKeySchema,
|
|
43
|
+
platformDatabaseKeySchema,
|
|
44
|
+
]);
|
|
45
|
+
export type DatabaseKey = z.infer<typeof databaseKeySchema>;
|
|
46
|
+
|
|
47
|
+
export const isControlDatabaseKey = (value: unknown): value is ControlDatabaseKey =>
|
|
48
|
+
typeof value === "string" && CONTROL_DATABASE_KEY_PATTERN.test(value);
|
|
49
|
+
|
|
50
|
+
export const isAuthDatabaseKey = (value: unknown): value is AuthDatabaseKey =>
|
|
51
|
+
typeof value === "string" && AUTH_DATABASE_KEY_PATTERN.test(value);
|
|
52
|
+
|
|
53
|
+
export const isPlatformDatabaseKey = (value: unknown): value is PlatformDatabaseKey =>
|
|
54
|
+
value === "platform";
|
|
55
|
+
|
|
56
|
+
export const isDatabaseKey = (value: unknown): value is DatabaseKey =>
|
|
57
|
+
isControlDatabaseKey(value) || isAuthDatabaseKey(value) || isPlatformDatabaseKey(value);
|
|
58
|
+
|
|
59
|
+
// ---------------------------------------------------------------------------
|
|
60
|
+
// Key <-> wrangler binding name mapping (design.md §10.3, §36)
|
|
61
|
+
// ---------------------------------------------------------------------------
|
|
62
|
+
|
|
63
|
+
export type ControlDatabaseBindingName = `CONTROL_DB_${string}`;
|
|
64
|
+
export type AuthDatabaseBindingName = `AUTH_DB_${string}`;
|
|
65
|
+
export type PlatformDatabaseBindingName = "PLATFORM_DB";
|
|
66
|
+
export type DatabaseBindingName =
|
|
67
|
+
| ControlDatabaseBindingName
|
|
68
|
+
| AuthDatabaseBindingName
|
|
69
|
+
| PlatformDatabaseBindingName;
|
|
70
|
+
|
|
71
|
+
export const PLATFORM_DATABASE_BINDING: PlatformDatabaseBindingName = "PLATFORM_DB";
|
|
72
|
+
|
|
73
|
+
const CONTROL_KEY_PREFIX = "control_";
|
|
74
|
+
const AUTH_KEY_PREFIX = "auth_";
|
|
75
|
+
const CONTROL_BINDING_PREFIX = "CONTROL_DB_";
|
|
76
|
+
const AUTH_BINDING_PREFIX = "AUTH_DB_";
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Maps a validated database key to its wrangler D1 binding name:
|
|
80
|
+
* `control_00` -> `CONTROL_DB_00`, `auth_000` -> `AUTH_DB_000`,
|
|
81
|
+
* `platform` -> `PLATFORM_DB`.
|
|
82
|
+
*/
|
|
83
|
+
export const keyToBindingName = (key: DatabaseKey): DatabaseBindingName => {
|
|
84
|
+
if (isControlDatabaseKey(key)) {
|
|
85
|
+
return `${CONTROL_BINDING_PREFIX}${key.slice(CONTROL_KEY_PREFIX.length)}`;
|
|
86
|
+
}
|
|
87
|
+
if (isAuthDatabaseKey(key)) {
|
|
88
|
+
return `${AUTH_BINDING_PREFIX}${key.slice(AUTH_KEY_PREFIX.length)}`;
|
|
89
|
+
}
|
|
90
|
+
return PLATFORM_DATABASE_BINDING;
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
const CONTROL_BINDING_PATTERN = /^CONTROL_DB_(\d{2})$/;
|
|
94
|
+
const AUTH_BINDING_PATTERN = /^AUTH_DB_(\d{3})$/;
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Inverse of `keyToBindingName`. Returns null for anything that is not a
|
|
98
|
+
* provisioned binding name: wrong shape, wrong case, or an out-of-range shard
|
|
99
|
+
* number (e.g. `CONTROL_DB_32`, `AUTH_DB_128`).
|
|
100
|
+
*/
|
|
101
|
+
export const bindingNameToKey = (name: string): DatabaseKey | null => {
|
|
102
|
+
if (name === PLATFORM_DATABASE_BINDING) {
|
|
103
|
+
const parsed = platformDatabaseKeySchema.safeParse("platform");
|
|
104
|
+
return parsed.success ? parsed.data : null;
|
|
105
|
+
}
|
|
106
|
+
const controlDigits = CONTROL_BINDING_PATTERN.exec(name)?.[1];
|
|
107
|
+
if (controlDigits !== undefined) {
|
|
108
|
+
const parsed = controlDatabaseKeySchema.safeParse(`${CONTROL_KEY_PREFIX}${controlDigits}`);
|
|
109
|
+
return parsed.success ? parsed.data : null;
|
|
110
|
+
}
|
|
111
|
+
const authDigits = AUTH_BINDING_PATTERN.exec(name)?.[1];
|
|
112
|
+
if (authDigits !== undefined) {
|
|
113
|
+
const parsed = authDatabaseKeySchema.safeParse(`${AUTH_KEY_PREFIX}${authDigits}`);
|
|
114
|
+
return parsed.success ? parsed.data : null;
|
|
115
|
+
}
|
|
116
|
+
return null;
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
// ---------------------------------------------------------------------------
|
|
120
|
+
// Typed parse
|
|
121
|
+
// ---------------------------------------------------------------------------
|
|
122
|
+
|
|
123
|
+
export interface InvalidDatabaseKeyError {
|
|
124
|
+
readonly type: "invalid_database_key";
|
|
125
|
+
readonly issues: readonly ValidationIssue[];
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Validates untrusted input as a database key. Never throws. */
|
|
129
|
+
export const parseDatabaseKey = (
|
|
130
|
+
input: unknown,
|
|
131
|
+
): ParseOutcome<DatabaseKey, InvalidDatabaseKeyError> => {
|
|
132
|
+
const parsed = databaseKeySchema.safeParse(input);
|
|
133
|
+
if (parsed.success) {
|
|
134
|
+
return parseOk(parsed.data);
|
|
135
|
+
}
|
|
136
|
+
return parseErr({
|
|
137
|
+
type: "invalid_database_key",
|
|
138
|
+
issues: toValidationIssues(parsed.error),
|
|
139
|
+
});
|
|
140
|
+
};
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { describe, expect, test } from "vitest";
|
|
2
|
+
import {
|
|
3
|
+
buildCanonicalIssuer,
|
|
4
|
+
buildDefaultInteractionDomain,
|
|
5
|
+
buildManagementApiOrigin,
|
|
6
|
+
environmentIdFromLoginHostLabel,
|
|
7
|
+
loginHostLabel,
|
|
8
|
+
parseEnvironmentIdFromLoginHost,
|
|
9
|
+
} from "./domains.js";
|
|
10
|
+
|
|
11
|
+
const ROOT = "example-auth.com";
|
|
12
|
+
const ENV_ID = `env_${"d".repeat(32)}`;
|
|
13
|
+
const LOGIN_HOST = `${ENV_ID}.login.${ROOT}`;
|
|
14
|
+
|
|
15
|
+
describe("buildCanonicalIssuer", () => {
|
|
16
|
+
test("builds https://id.<root>/e/<envId> (design §8)", () => {
|
|
17
|
+
expect(buildCanonicalIssuer(ROOT, ENV_ID)).toBe(`https://id.${ROOT}/e/${ENV_ID}`);
|
|
18
|
+
});
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
describe("buildManagementApiOrigin", () => {
|
|
22
|
+
test("builds https://api.<root> (design §8)", () => {
|
|
23
|
+
expect(buildManagementApiOrigin(ROOT)).toBe(`https://api.${ROOT}`);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
test("follows the deployment's root domain rather than a fixed host", () => {
|
|
27
|
+
expect(buildManagementApiOrigin("zeroword.smartcrab.ai")).toBe(
|
|
28
|
+
"https://api.zeroword.smartcrab.ai",
|
|
29
|
+
);
|
|
30
|
+
});
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
describe("buildDefaultInteractionDomain", () => {
|
|
34
|
+
test("builds env-<body>.login.<root>: a DNS-compliant label, never an underscore", () => {
|
|
35
|
+
const host = buildDefaultInteractionDomain(ENV_ID, ROOT);
|
|
36
|
+
expect(host).toBe(`env-${"d".repeat(32)}.login.${ROOT}`);
|
|
37
|
+
expect(host).not.toContain("_");
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test("round-trips through parseEnvironmentIdFromLoginHost", () => {
|
|
41
|
+
expect(parseEnvironmentIdFromLoginHost(buildDefaultInteractionDomain(ENV_ID, ROOT), ROOT)).toBe(
|
|
42
|
+
ENV_ID,
|
|
43
|
+
);
|
|
44
|
+
});
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
describe("loginHostLabel / environmentIdFromLoginHostLabel", () => {
|
|
48
|
+
test("encodes the env_ prefix as env- and decodes it back", () => {
|
|
49
|
+
expect(loginHostLabel(ENV_ID)).toBe(`env-${"d".repeat(32)}`);
|
|
50
|
+
expect(environmentIdFromLoginHostLabel(`env-${"d".repeat(32)}`)).toBe(ENV_ID);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
test("still decodes the legacy literal env_ label (rows written before the encoding)", () => {
|
|
54
|
+
expect(environmentIdFromLoginHostLabel(ENV_ID)).toBe(ENV_ID);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test("rejects anything that is not exactly one environment id", () => {
|
|
58
|
+
expect(environmentIdFromLoginHostLabel(`env-${"d".repeat(31)}`)).toBeNull();
|
|
59
|
+
expect(environmentIdFromLoginHostLabel(`env--${"d".repeat(32)}`)).toBeNull();
|
|
60
|
+
expect(environmentIdFromLoginHostLabel(`usr-${"d".repeat(32)}`)).toBeNull();
|
|
61
|
+
expect(environmentIdFromLoginHostLabel(`env-env_${"d".repeat(32)}`)).toBeNull();
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
describe("parseEnvironmentIdFromLoginHost", () => {
|
|
66
|
+
test("parses the legacy literal env_ login host", () => {
|
|
67
|
+
expect(parseEnvironmentIdFromLoginHost(LOGIN_HOST, ROOT)).toBe(ENV_ID);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
test("parses the DNS-safe env- login host", () => {
|
|
71
|
+
expect(parseEnvironmentIdFromLoginHost(`env-${"d".repeat(32)}.login.${ROOT}`, ROOT)).toBe(
|
|
72
|
+
ENV_ID,
|
|
73
|
+
);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test("DNS names are case-insensitive", () => {
|
|
77
|
+
expect(parseEnvironmentIdFromLoginHost(LOGIN_HOST.toUpperCase(), ROOT)).toBe(ENV_ID);
|
|
78
|
+
expect(parseEnvironmentIdFromLoginHost(LOGIN_HOST, ROOT.toUpperCase())).toBe(ENV_ID);
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
test("a single trailing root dot is ignored", () => {
|
|
82
|
+
expect(parseEnvironmentIdFromLoginHost(`${LOGIN_HOST}.`, ROOT)).toBe(ENV_ID);
|
|
83
|
+
expect(parseEnvironmentIdFromLoginHost(LOGIN_HOST, `${ROOT}.`)).toBe(ENV_ID);
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
test("rejects hosts carrying a port", () => {
|
|
87
|
+
expect(parseEnvironmentIdFromLoginHost(`${LOGIN_HOST}:443`, ROOT)).toBeNull();
|
|
88
|
+
expect(parseEnvironmentIdFromLoginHost(`${LOGIN_HOST}:8443`, ROOT)).toBeNull();
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
test("rejects suffix confusion: evil-login.example-auth.com", () => {
|
|
92
|
+
expect(parseEnvironmentIdFromLoginHost(`evil-login.${ROOT}`, ROOT)).toBeNull();
|
|
93
|
+
expect(parseEnvironmentIdFromLoginHost(`${ENV_ID}.evil-login.${ROOT}`, ROOT)).toBeNull();
|
|
94
|
+
expect(parseEnvironmentIdFromLoginHost(`${ENV_ID}.login.${ROOT}.evil.com`, ROOT)).toBeNull();
|
|
95
|
+
expect(parseEnvironmentIdFromLoginHost(`login.${ROOT}`, ROOT)).toBeNull();
|
|
96
|
+
expect(parseEnvironmentIdFromLoginHost(`.login.${ROOT}`, ROOT)).toBeNull();
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
test("rejects multi-label prefixes and malformed environment IDs", () => {
|
|
100
|
+
expect(parseEnvironmentIdFromLoginHost(`${ENV_ID}.extra.login.${ROOT}`, ROOT)).toBeNull();
|
|
101
|
+
expect(parseEnvironmentIdFromLoginHost(`usr_${"d".repeat(32)}.login.${ROOT}`, ROOT)).toBeNull();
|
|
102
|
+
expect(parseEnvironmentIdFromLoginHost(`env_short.login.${ROOT}`, ROOT)).toBeNull();
|
|
103
|
+
expect(parseEnvironmentIdFromLoginHost(`env_${"D".repeat(32)}.login.${ROOT}`, ROOT)).toBe(
|
|
104
|
+
ENV_ID,
|
|
105
|
+
); // case-normalized, still valid
|
|
106
|
+
expect(parseEnvironmentIdFromLoginHost(`env_${"0".repeat(32)}.login.${ROOT}`, ROOT)).toBeNull();
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
test("rejects a different root domain", () => {
|
|
110
|
+
expect(parseEnvironmentIdFromLoginHost(LOGIN_HOST, "other.com")).toBeNull();
|
|
111
|
+
expect(parseEnvironmentIdFromLoginHost(`${ENV_ID}.login.other.com`, ROOT)).toBeNull();
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
test("rejects empty and non-host input", () => {
|
|
115
|
+
expect(parseEnvironmentIdFromLoginHost("", ROOT)).toBeNull();
|
|
116
|
+
expect(parseEnvironmentIdFromLoginHost(" ", ROOT)).toBeNull();
|
|
117
|
+
expect(parseEnvironmentIdFromLoginHost("[::1]", ROOT)).toBeNull();
|
|
118
|
+
expect(parseEnvironmentIdFromLoginHost(`https://${LOGIN_HOST}/`, ROOT)).toBeNull();
|
|
119
|
+
});
|
|
120
|
+
});
|
package/src/domains.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { ENVIRONMENT_ID_PATTERN } from "./ids.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Domain and issuer helpers (design.md §8).
|
|
5
|
+
*
|
|
6
|
+
* These are pure string functions. They never read request headers: callers
|
|
7
|
+
* must pass `new URL(request.url).hostname`. `X-Forwarded-Host` and request
|
|
8
|
+
* bodies are explicitly not trusted for host resolution (§8.2).
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Canonical issuer for an Environment: `https://id.<root>/e/<envId>`.
|
|
13
|
+
* The issuer never changes after Environment creation, even when a custom
|
|
14
|
+
* interaction domain is configured (§8.1).
|
|
15
|
+
*/
|
|
16
|
+
export const buildCanonicalIssuer = (platformRootDomain: string, environmentId: string): string =>
|
|
17
|
+
`https://id.${platformRootDomain}/e/${environmentId}`;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Default interaction (Hosted Login) domain for an Environment (§8, §8.3
|
|
21
|
+
* default RP ID mode): `<label>.login.<root>` where `<label>` is the
|
|
22
|
+
* Environment id with its `env_` prefix written as `env-`.
|
|
23
|
+
*
|
|
24
|
+
* Documented deviation from §8's literal `env_xxx.login.<root>` (IMPL_NOTES
|
|
25
|
+
* rule 1): an underscore is not valid in a hostname label (RFC 1123), so
|
|
26
|
+
* Cloudflare refuses to attach such a name as a Workers Custom Domain or to
|
|
27
|
+
* issue a certificate for it, and WebAuthn requires the RP ID to be a valid
|
|
28
|
+
* domain. `env-<body>` is unambiguous (ids have exactly one underscore) and
|
|
29
|
+
* keeps the label parseable back to the id. `parseEnvironmentIdFromLoginHost`
|
|
30
|
+
* accepts both spellings so rows written before this change keep resolving.
|
|
31
|
+
*/
|
|
32
|
+
export const buildDefaultInteractionDomain = (environmentId: string, rootDomain: string): string =>
|
|
33
|
+
`${loginHostLabel(environmentId)}.login.${rootDomain}`;
|
|
34
|
+
|
|
35
|
+
/** `env_<body>` -> `env-<body>`: the DNS-safe label for an Environment id. */
|
|
36
|
+
export const loginHostLabel = (environmentId: string): string =>
|
|
37
|
+
environmentId.replace(/^env_/, "env-");
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Inverse of `loginHostLabel`. Accepts the DNS-safe `env-<body>` label and
|
|
41
|
+
* the legacy literal `env_<body>`; anything else is null.
|
|
42
|
+
*/
|
|
43
|
+
export const environmentIdFromLoginHostLabel = (label: string): string | null => {
|
|
44
|
+
const candidate = label.replace(/^env-/, "env_");
|
|
45
|
+
return ENVIRONMENT_ID_PATTERN.test(candidate) ? candidate : null;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Management API origin for this deployment: `https://api.<root>` (§8's
|
|
50
|
+
* domain table). Response bodies that hand a caller a Management API URL
|
|
51
|
+
* (user import/export artifacts) must build it from the deployment's own
|
|
52
|
+
* root domain rather than embedding a literal host.
|
|
53
|
+
*/
|
|
54
|
+
export const buildManagementApiOrigin = (platformRootDomain: string): string =>
|
|
55
|
+
`https://api.${platformRootDomain}`;
|
|
56
|
+
|
|
57
|
+
/** DNS names are case-insensitive; a single trailing root dot is ignored. */
|
|
58
|
+
const normalizeHost = (value: string): string => {
|
|
59
|
+
const lower = value.trim().toLowerCase();
|
|
60
|
+
return lower.endsWith(".") ? lower.slice(0, -1) : lower;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Extracts the Environment ID from a default login host
|
|
65
|
+
* (`<envId>.login.<root>`), step 1 of host resolution in §8.2.
|
|
66
|
+
*
|
|
67
|
+
* Returns null for anything else: unknown suffixes, multi-label prefixes,
|
|
68
|
+
* malformed IDs, ports, and near-miss hosts such as
|
|
69
|
+
* `evil-login.example-auth.com` (the `.login.` label boundary is required).
|
|
70
|
+
*/
|
|
71
|
+
export const parseEnvironmentIdFromLoginHost = (
|
|
72
|
+
hostname: string,
|
|
73
|
+
rootDomain: string,
|
|
74
|
+
): string | null => {
|
|
75
|
+
const host = normalizeHost(hostname);
|
|
76
|
+
// A colon means a port or a non-DNS value (e.g. an IP literal) — never a
|
|
77
|
+
// valid login host.
|
|
78
|
+
if (host.includes(":")) {
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
const suffix = `.login.${normalizeHost(rootDomain)}`;
|
|
82
|
+
if (!host.endsWith(suffix)) {
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
return environmentIdFromLoginHostLabel(host.slice(0, host.length - suffix.length));
|
|
86
|
+
};
|
package/src/ids.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Resource identifier shapes (design.md §7.5): a meaningful prefix plus 32
|
|
5
|
+
* base32url characters (160 bits of cryptographic randomness). Values are
|
|
6
|
+
* generated by `@smartcrab/identifiers`; the patterns here validate them
|
|
7
|
+
* at trust boundaries without depending on the generator package.
|
|
8
|
+
*
|
|
9
|
+
* Sequential, email-derived, or timestamp-only predictable IDs are forbidden.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** 160-bit base32url body shared by all prefixed resource IDs. */
|
|
13
|
+
const ID_BODY = "[a-z2-7]{32}";
|
|
14
|
+
|
|
15
|
+
export const CELL_ID_PATTERN = new RegExp(`^cel_${ID_BODY}$`);
|
|
16
|
+
export const WORKSPACE_ID_PATTERN = new RegExp(`^wsp_${ID_BODY}$`);
|
|
17
|
+
export const PROJECT_ID_PATTERN = new RegExp(`^prj_${ID_BODY}$`);
|
|
18
|
+
export const ENVIRONMENT_ID_PATTERN = new RegExp(`^env_${ID_BODY}$`);
|
|
19
|
+
export const USER_ID_PATTERN = new RegExp(`^usr_${ID_BODY}$`);
|
|
20
|
+
/** Auth partition IDs (`prt_...`) identify EnvironmentAuthPartition rows (design.md §10.5). */
|
|
21
|
+
export const AUTH_PARTITION_ID_PATTERN = new RegExp(`^prt_${ID_BODY}$`);
|
|
22
|
+
|
|
23
|
+
/** Branded cell ID: a `cel_`-prefixed resource ID for a deployment cell. */
|
|
24
|
+
export const cellIdSchema = z.string().regex(CELL_ID_PATTERN).brand<"CellId">();
|
|
25
|
+
export type CellId = z.infer<typeof cellIdSchema>;
|
|
26
|
+
|
|
27
|
+
export const workspaceIdSchema = z.string().regex(WORKSPACE_ID_PATTERN);
|
|
28
|
+
export const projectIdSchema = z.string().regex(PROJECT_ID_PATTERN);
|
|
29
|
+
export const environmentIdSchema = z.string().regex(ENVIRONMENT_ID_PATTERN);
|
|
30
|
+
export const userIdSchema = z.string().regex(USER_ID_PATTERN);
|
|
31
|
+
export const authPartitionIdSchema = z.string().regex(AUTH_PARTITION_ID_PATTERN);
|
|
32
|
+
|
|
33
|
+
export const isCellId = (value: unknown): value is CellId =>
|
|
34
|
+
typeof value === "string" && CELL_ID_PATTERN.test(value);
|
package/src/index.ts
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,39 @@
|
|
|
1
|
+
import type { z } from "zod";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Outcome of a never-throwing parse helper.
|
|
5
|
+
*
|
|
6
|
+
* This package is runtime-agnostic (tsconfig `types: []`), so it deliberately
|
|
7
|
+
* does not depend on `@smartcrab/result` (whose source needs DOM/workers
|
|
8
|
+
* ambient types). The shape mirrors the byethrow `Result` convention:
|
|
9
|
+
* discriminate on `ok`.
|
|
10
|
+
*/
|
|
11
|
+
export type ParseOutcome<T, E> =
|
|
12
|
+
| { readonly ok: true; readonly value: T }
|
|
13
|
+
| { readonly ok: false; readonly error: E };
|
|
14
|
+
|
|
15
|
+
export const parseOk = <T, E>(value: T): ParseOutcome<T, E> => ({ ok: true, value });
|
|
16
|
+
|
|
17
|
+
export const parseErr = <T, E>(error: E): ParseOutcome<T, E> => ({ ok: false, error });
|
|
18
|
+
|
|
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
|
+
|
|
34
|
+
export const toValidationIssues = (error: z.ZodError): readonly ValidationIssue[] =>
|
|
35
|
+
error.issues.map((issue) => ({
|
|
36
|
+
path: issue.path.map((segment) => String(segment)).join("."),
|
|
37
|
+
code: issue.code,
|
|
38
|
+
message: issue.message,
|
|
39
|
+
}));
|