@k9o/gate 0.0.0-stage → 1.0.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/src/jwt.ts ADDED
@@ -0,0 +1,229 @@
1
+ /**
2
+ * JWT verification primitives for external-app standalone consumption.
3
+ *
4
+ * Standalone-mode customers consume Gate-issued JWTs in their own
5
+ * application code without needing the full SDK shape — they just need
6
+ * to verify the signature, extract claims, and (optionally) check
7
+ * scopes. This module is the canonical entry for that surface.
8
+ *
9
+ * Backed by `jose` (already a peer dependency in the gateway via the
10
+ * same library; chose `jose` for consistency + JWK fetch support out
11
+ * of the box).
12
+ *
13
+ * Native-mode customers don't typically reach for this directly — the
14
+ * gateway verifies project-issued tokens on every request and rehydrates
15
+ * `subject.*` claims per ch06 §3.2. But the same primitives are
16
+ * portable: Native customers running their own services downstream of
17
+ * the gateway can verify Gate-issued JWTs identically.
18
+ */
19
+
20
+ import { createRemoteJWKSet, jwtVerify, errors as joseErrors } from "jose";
21
+ import type { GateJwtClaims, VerifyJwtFailure, VerifyJwtResult } from "./types.ts";
22
+ import { GateError } from "./errors.ts";
23
+
24
+ /**
25
+ * Configuration for `verifyJwt`. The verifier can resolve signing keys
26
+ * via either a remote JWKS URL (the typical Gate deployment shape) or
27
+ * an inline key set (for tests + air-gapped deployments).
28
+ */
29
+ export type VerifyJwtOptions = {
30
+ token: string;
31
+ /**
32
+ * JWKS endpoint URL — the gateway exposes `/@<projectSlug>/gate/.well-known/jwks.json`
33
+ * by convention. Either `jwksUrl` or `jwks` must be set; not both.
34
+ */
35
+ jwksUrl?: string;
36
+ /**
37
+ * Inline JWK set — used by tests + integration scenarios that want to
38
+ * avoid the network hop. The shape is the standard JWKS `{keys: [...]}`
39
+ * envelope; pass through unchanged to `jose`.
40
+ */
41
+ jwks?: { keys: ReadonlyArray<Record<string, unknown>> };
42
+ /** Expected issuer (`iss` claim). Strict comparison. */
43
+ expectedIssuer?: string;
44
+ /** Expected audience (`aud` claim). Accepts either string or array per RFC 7519. */
45
+ expectedAudience?: string;
46
+ /**
47
+ * Allowed signing algorithms. Defaults to `["RS256", "ES256"]` per the
48
+ * standard Gate issuer config. Reject anything outside this set
49
+ * (defense against alg-confusion attacks).
50
+ */
51
+ allowedAlgorithms?: ReadonlyArray<string>;
52
+ /**
53
+ * Clock-skew tolerance in seconds. Defaults to 30. Applies to both
54
+ * `exp` and `nbf` checks.
55
+ */
56
+ clockToleranceSeconds?: number;
57
+ };
58
+
59
+ const DEFAULT_ALLOWED_ALGORITHMS = ["RS256", "ES256"] as const;
60
+ const DEFAULT_CLOCK_TOLERANCE_SECONDS = 30;
61
+
62
+ /**
63
+ * Verify a Gate-issued JWT. Returns a typed result; does NOT throw on
64
+ * verification failure (a `valid: false` result carries the reason).
65
+ *
66
+ * Throws `GateError` only when:
67
+ * - `jwksUrl` and `jwks` are both unset or both set
68
+ * - the JWKS fetch fails for transport reasons (UPSTREAM_UNAVAILABLE)
69
+ */
70
+ export async function verifyJwt(opts: VerifyJwtOptions): Promise<VerifyJwtResult> {
71
+ if (opts.jwksUrl !== undefined && opts.jwks !== undefined) {
72
+ throw new GateError({
73
+ code: "INVALID_FIELD_VALUE",
74
+ message: "verifyJwt: pass either jwksUrl OR jwks, not both",
75
+ context: {},
76
+ recommendation: null,
77
+ });
78
+ }
79
+ if (opts.jwksUrl === undefined && opts.jwks === undefined) {
80
+ throw new GateError({
81
+ code: "INVALID_FIELD_VALUE",
82
+ message: "verifyJwt: must pass exactly one of {jwksUrl, jwks}",
83
+ context: {},
84
+ recommendation: null,
85
+ });
86
+ }
87
+
88
+ const allowedAlgorithms = opts.allowedAlgorithms ?? DEFAULT_ALLOWED_ALGORITHMS;
89
+ const clockTolerance = opts.clockToleranceSeconds ?? DEFAULT_CLOCK_TOLERANCE_SECONDS;
90
+
91
+ let keyResolver: Parameters<typeof jwtVerify>[1];
92
+ if (opts.jwksUrl !== undefined) {
93
+ keyResolver = createRemoteJWKSet(new URL(opts.jwksUrl));
94
+ } else {
95
+ // Inline JWKS — implement the resolver inline since `jose`'s
96
+ // `createLocalJWKSet` import path varies across versions.
97
+ keyResolver = makeLocalJwksResolver(opts.jwks!);
98
+ }
99
+
100
+ try {
101
+ const result = await jwtVerify(opts.token, keyResolver, {
102
+ ...(opts.expectedIssuer !== undefined ? { issuer: opts.expectedIssuer } : {}),
103
+ ...(opts.expectedAudience !== undefined ? { audience: opts.expectedAudience } : {}),
104
+ algorithms: allowedAlgorithms as string[],
105
+ clockTolerance,
106
+ });
107
+ return { valid: true, claims: result.payload as GateJwtClaims };
108
+ } catch (e) {
109
+ return { valid: false, reason: classifyJoseFailure(e) };
110
+ }
111
+ }
112
+
113
+ /**
114
+ * Extract claims from a JWT WITHOUT verifying the signature. Used by
115
+ * SDK consumers that want to read claim data in client code where
116
+ * signature verification has already happened at a trusted hop (e.g.,
117
+ * a reverse proxy). Caller is responsible for confirming the upstream
118
+ * trust path before consuming these claims for security decisions.
119
+ *
120
+ * Throws `GateError` on malformed input.
121
+ */
122
+ export function extractClaims(token: string): GateJwtClaims {
123
+ const parts = token.split(".");
124
+ if (parts.length !== 3) {
125
+ throw new GateError({
126
+ code: "INVALID_FIELD_VALUE",
127
+ message: `Malformed JWT: expected 3 dot-separated parts, got ${parts.length}`,
128
+ context: {},
129
+ recommendation: null,
130
+ });
131
+ }
132
+ try {
133
+ const payloadJson = base64UrlDecode(parts[1]!);
134
+ return JSON.parse(payloadJson) as GateJwtClaims;
135
+ } catch (e) {
136
+ throw new GateError({
137
+ code: "INVALID_FIELD_VALUE",
138
+ message: `Malformed JWT payload: ${e instanceof Error ? e.message : String(e)}`,
139
+ context: {},
140
+ recommendation: null,
141
+ });
142
+ }
143
+ }
144
+
145
+ /**
146
+ * Assert that the given claim set contains all of the required scopes.
147
+ * Throws `GateError` with `code: "RBAC_DENY"` if any scope is missing.
148
+ * Returns nothing on success — caller uses the throw-or-pass shape.
149
+ */
150
+ export function requireScope(
151
+ claims: GateJwtClaims,
152
+ requiredScopes: ReadonlyArray<string>,
153
+ ): void {
154
+ const present = new Set(claims.scopes ?? []);
155
+ const missing = requiredScopes.filter((s) => !present.has(s));
156
+ if (missing.length > 0) {
157
+ throw new GateError({
158
+ code: "RBAC_DENY",
159
+ message: `Required scopes missing: ${missing.join(", ")}`,
160
+ context: { missingScopes: missing, presentScopes: Array.from(present) },
161
+ recommendation: null,
162
+ });
163
+ }
164
+ }
165
+
166
+ // ----------------------------------------------------------------------
167
+ // Internals
168
+ // ----------------------------------------------------------------------
169
+
170
+ function classifyJoseFailure(e: unknown): VerifyJwtFailure {
171
+ // Map `jose`'s typed errors to our closed reason set per `VerifyJwtFailure`.
172
+ if (e instanceof joseErrors.JWSSignatureVerificationFailed) return "INVALID_SIGNATURE";
173
+ if (e instanceof joseErrors.JWTExpired) return "EXPIRED";
174
+ if (e instanceof joseErrors.JWTClaimValidationFailed) {
175
+ const claim = (e as { claim?: string }).claim;
176
+ if (claim === "aud") return "AUDIENCE_MISMATCH";
177
+ if (claim === "iss") return "ISSUER_MISMATCH";
178
+ if (claim === "nbf") return "NOT_YET_VALID";
179
+ return "MALFORMED";
180
+ }
181
+ if (e instanceof joseErrors.JOSEAlgNotAllowed) return "ALGORITHM_NOT_ALLOWED";
182
+ // Fallback — `jose` raises other errors (parse failures, KID mismatches,
183
+ // etc.) that we lump into `MALFORMED` rather than leaking the per-version
184
+ // taxonomy.
185
+ return "MALFORMED";
186
+ }
187
+
188
+ function base64UrlDecode(input: string): string {
189
+ // Pad to a multiple of 4 + swap urlsafe alphabet -> standard alphabet.
190
+ const padded = input + "=".repeat((4 - (input.length % 4)) % 4);
191
+ const standard = padded.replace(/-/g, "+").replace(/_/g, "/");
192
+ // Bun + Node 18+ + browsers all expose `atob`.
193
+ const binary = globalThis.atob(standard);
194
+ // Reassemble bytes back to UTF-8 text.
195
+ const bytes = new Uint8Array(binary.length);
196
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
197
+ return new TextDecoder("utf-8").decode(bytes);
198
+ }
199
+
200
+ /**
201
+ * Build a key resolver compatible with `jose.jwtVerify` from an inline
202
+ * JWKS object. `jose` exports `createLocalJWKSet` from its main module
203
+ * but the import path / type shape can shift across minors; reimplement
204
+ * the minimal resolver here for stability.
205
+ */
206
+ function makeLocalJwksResolver(
207
+ jwks: { keys: ReadonlyArray<Record<string, unknown>> },
208
+ ): Parameters<typeof jwtVerify>[1] {
209
+ // The `jose` resolver signature is `(header, token) => Promise<KeyLike>`
210
+ // — pull the kid from the header, match against the JWKS, and import.
211
+ return async (header) => {
212
+ const { importJWK } = await import("jose");
213
+ const kid = (header as { kid?: string }).kid;
214
+ let match: Record<string, unknown> | undefined;
215
+ if (kid !== undefined) {
216
+ match = jwks.keys.find((k) => k["kid"] === kid);
217
+ }
218
+ if (match === undefined && jwks.keys.length === 1) {
219
+ // Single-key JWKS — return the only key. Tests typically ship one
220
+ // key in the inline set and may not bother with `kid`.
221
+ match = jwks.keys[0];
222
+ }
223
+ if (match === undefined) {
224
+ throw new joseErrors.JWKSNoMatchingKey("No matching key in inline JWKS for kid");
225
+ }
226
+ const alg = (header as { alg?: string }).alg ?? (match["alg"] as string | undefined);
227
+ return importJWK(match as unknown as Parameters<typeof importJWK>[0], alg);
228
+ };
229
+ }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * `gate.magicLinkRedirects` sub-namespace — the per-project magic-link
3
+ * redirect-URL allowlist, PROJECT_ADMIN+ managed. Blessed shape (
4
+ * 2026-07-16): `list()`/`add()`/`remove()`, mirroring the
5
+ * `gate.idpProviders.*` sub-namespace convention (gate-admin surface,
6
+ * not the end-user-facing `passwordless.*` send/verify flow).
7
+ *
8
+ * Wraps the live gateway routes (`services/gateway/src/routes/
9
+ * gate-magic-link-redirects.ts`):
10
+ *
11
+ * GET /@<projectSlug>/gate/magic-link-redirects
12
+ * POST /@<projectSlug>/gate/magic-link-redirects { redirectUrl, isDefault? }
13
+ * DELETE /@<projectSlug>/gate/magic-link-redirects/:id
14
+ *
15
+ * One deliberate deviation from the shorthand in the original blessing
16
+ * relay ("remove(redirectUrl)"): the shipped route deletes by the
17
+ * redirect row's `id`, not by re-presenting its `redirectUrl` value —
18
+ * verified directly against the route, not assumed from the relay's
19
+ * informal shape sketch. `remove(id)` matches what the gateway actually
20
+ * does; a `redirectUrl`-keyed removal would need an extra `list()`
21
+ * round-trip to resolve the id first, which the SDK should not do
22
+ * silently on the caller's behalf.
23
+ *
24
+ * Auth: operator JWT with PROJECT_ADMIN+ (or ORG_ADMIN/ORG_OWNER) role —
25
+ * the gateway rejects end-user JWTs and lower-role operators alike
26
+ * (K9O_RBAC_DENY). The allowlist is a security control: registering a
27
+ * redirect target is an admin act, same posture as `idpProviders.*`.
28
+ */
29
+
30
+ import { getGateConfig, type GateConfig } from "./mode.ts";
31
+ import { requestWith } from "./client.ts";
32
+ import { resolveProjectPathRoot } from "./paths.ts";
33
+ import type { Envelope } from "./types.ts";
34
+
35
+ /** A single allowlisted magic-link redirect target. */
36
+ export type MagicLinkRedirect = {
37
+ id: string;
38
+ redirectUrl: string;
39
+ isDefault: boolean;
40
+ createdAt: string;
41
+ };
42
+
43
+ export type AddMagicLinkRedirectInput = {
44
+ redirectUrl: string;
45
+ /**
46
+ * When true, this target becomes the default the gateway falls back to
47
+ * when a `requestMagicLink` call doesn't specify one. The gateway
48
+ * atomically demotes any previously-default entry — never two
49
+ * simultaneous defaults.
50
+ */
51
+ isDefault?: boolean;
52
+ };
53
+
54
+ export type RemoveMagicLinkRedirectResult = { removed: true; id: string };
55
+
56
+ function magicLinkRedirectsPath(config: GateConfig, id?: string): string {
57
+ const root = `${resolveProjectPathRoot(config)}/gate/magic-link-redirects`;
58
+ return id !== undefined ? `${root}/${id}` : root;
59
+ }
60
+
61
+ /** Factory — produces a `magicLinkRedirects` namespace bound to the
62
+ * supplied config getter. Used by both the `gate` singleton +
63
+ * `createGateClient`. */
64
+ export function makeMagicLinkRedirects(getConfig: () => GateConfig) {
65
+ return {
66
+ /** List every allowlisted redirect target for the active project. */
67
+ async list(): Promise<Envelope<{ redirects: MagicLinkRedirect[] }>> {
68
+ const config = getConfig();
69
+ return requestWith<{ redirects: MagicLinkRedirect[] }>(config, {
70
+ method: "GET",
71
+ path: magicLinkRedirectsPath(config),
72
+ });
73
+ },
74
+
75
+ /**
76
+ * Register a new redirect target. `redirectUrl` must exact-match
77
+ * what a customer later passes to `requestMagicLink` — the gateway
78
+ * enforces exact match, never a prefix or wildcard.
79
+ */
80
+ async add(input: AddMagicLinkRedirectInput): Promise<Envelope<{ redirect: MagicLinkRedirect }>> {
81
+ const config = getConfig();
82
+ return requestWith<{ redirect: MagicLinkRedirect }>(config, {
83
+ method: "POST",
84
+ path: magicLinkRedirectsPath(config),
85
+ body: input,
86
+ });
87
+ },
88
+
89
+ /** Remove a previously-registered redirect target by its `id`. */
90
+ async remove(id: string): Promise<Envelope<RemoveMagicLinkRedirectResult>> {
91
+ const config = getConfig();
92
+ return requestWith<RemoveMagicLinkRedirectResult>(config, {
93
+ method: "DELETE",
94
+ path: magicLinkRedirectsPath(config, id),
95
+ });
96
+ },
97
+ };
98
+ }
99
+
100
+ /** Singleton bound to the module-level `configureGate()` config. */
101
+ export const magicLinkRedirects = makeMagicLinkRedirects(getGateConfig);
102
+
103
+ export type MagicLinkRedirectsNamespace = ReturnType<typeof makeMagicLinkRedirects>;
package/src/mode.ts ADDED
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Standalone vs Native mode wiring per ch01 §12.4.
3
+ *
4
+ * The SDK surface is identical across modes; mode determines gateway-
5
+ * side behavior (whether the end-user row scope applies on read/write paths),
6
+ * not SDK ergonomics. The mode boundary is a deployment-time decision
7
+ * per ch02; the SDK does not branch behavior at function-call time.
8
+ *
9
+ * What mode affects (today + forward):
10
+ *
11
+ * - **Billing-identity routing** (commission callout):
12
+ * Standalone customers are billed under the partner-credentialled
13
+ * contract (Gate as Auth0/Clerk/Okta alternative — Trojan Horse
14
+ * motion); Native customers compose with the broader Kilimanjaro
15
+ * billing model. The SDK records the mode on every wire request via
16
+ * the `X-Gate-Mode` header so the gateway routes consumption to the
17
+ * correct billing surface without per-function branching.
18
+ * - **Auto-scoping expectations** in marketing copy + docs hub copy
19
+ * (per memory `feedback_gate_iak_brand_architecture.md` marketing-
20
+ * honesty discipline). Standalone mode delivers Sovereign Ingress +
21
+ * Hardware-Attested Identity + Forensic Attribution + Unlimited MAUs;
22
+ * Native mode adds Automatic Identity-Aware Scoping on top.
23
+ *
24
+ * What mode does NOT affect:
25
+ *
26
+ * - Function names + signatures (identical across modes)
27
+ * - Wire-envelope shape (identical per ch01 §1)
28
+ * - Error taxonomy (identical per ch01 §2)
29
+ */
30
+
31
+ /**
32
+ * Two-mode discriminant. The third candidate "Hybrid" was rejected per
33
+ * memory `feedback_gate_iak_brand_architecture.md` — modes are
34
+ * orthogonal deployment shapes, not interleaved.
35
+ */
36
+ export type GateMode = "standalone" | "native";
37
+
38
+ /**
39
+ * Gate SDK configuration. Returned by `getGateConfig()` and consumed
40
+ * internally by the HTTP client + JWT verifier. Set via `configureGate`
41
+ * at process boot or per-test in unit tests.
42
+ */
43
+ export type GateConfig = {
44
+ mode: GateMode;
45
+ /** Project slug per v2.5.68 URL grammar (e.g. `partner-console-staging`).
46
+ * The only customer-facing project addressing form; routes resolve to
47
+ * `/@<slug>/gate/...` (`feedback_slug_addressing_v2_5_68`). Required. */
48
+ projectSlug: string;
49
+ /** Gateway base URL — e.g. `https://<orgSlug>.api.k9o.io` per v2.5.68 §5.4. */
50
+ baseUrl: string;
51
+ /**
52
+ * Optional partner-credentialled JWT for Standalone mode — used as the
53
+ * default Authorization header when no per-call bearer is supplied.
54
+ * Not required in Native mode; the gateway resolves credentials from
55
+ * the standard project context per ch02.
56
+ */
57
+ partnerToken?: string;
58
+ /**
59
+ * Optional fetch override for testing + non-browser environments. The
60
+ * SDK defaults to global `fetch` (available in Bun + Node 18+ +
61
+ * browsers) when not set.
62
+ */
63
+ fetch?: typeof fetch;
64
+ };
65
+
66
+ let _config: GateConfig | null = null;
67
+
68
+ /**
69
+ * Initialise the SDK. Must be called before any `gate.*` invocation.
70
+ * Re-calling replaces the prior config wholesale (no per-field merge —
71
+ * keeps the config-set-at-boot ergonomic clean).
72
+ */
73
+ export function configureGate(config: GateConfig): void {
74
+ validateGateConfig(config);
75
+ _config = { ...config };
76
+ }
77
+
78
+ /**
79
+ * Validate a config shape. Exposed for `createGateClient` so per-instance
80
+ * configs go through identical checks as the singleton.
81
+ */
82
+ export function validateGateConfig(config: GateConfig): void {
83
+ if (config.mode !== "standalone" && config.mode !== "native") {
84
+ throw new TypeError(
85
+ `Invalid Gate mode "${config.mode as string}"; expected "standalone" or "native"`,
86
+ );
87
+ }
88
+ const hasSlug = typeof config.projectSlug === "string" && config.projectSlug.length > 0;
89
+ if (!hasSlug) {
90
+ throw new TypeError(
91
+ `Gate config missing projectSlug (required, v2.5.68 grammar — project ids are internal-only and never customer-facing)`,
92
+ );
93
+ }
94
+ if (typeof config.baseUrl !== "string" || config.baseUrl.length === 0) {
95
+ throw new TypeError(`Invalid baseUrl "${config.baseUrl}"; expected non-empty string`);
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Read the active config. Throws when called before `configureGate(...)`.
101
+ * Tests can call `resetGateConfig()` to clear between cases.
102
+ */
103
+ export function getGateConfig(): GateConfig {
104
+ if (_config === null) {
105
+ throw new Error(
106
+ "@k9o/gate: SDK is not configured. Call configureGate({ mode, projectSlug, baseUrl }) before invoking gate functions.",
107
+ );
108
+ }
109
+ return _config;
110
+ }
111
+
112
+ /** Reset the singleton — used by tests + by app-shutdown teardown paths. */
113
+ export function resetGateConfig(): void {
114
+ _config = null;
115
+ }
package/src/paths.ts ADDED
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Shared path-resolution helper for project-scoped routes.
3
+ *
4
+ * v2.5.68 URL grammar: project-scoped resources address
5
+ * via `/@<projectSlug>/...` against the org subdomain. Slug addressing is
6
+ * the only customer-facing form — project ids are internal-only and never
7
+ * appear in customer paths (`feedback_slug_addressing_v2_5_68`); the
8
+ * retired `/v2/projects/<bareId>/...` form was dropped at pass17
9
+ * (`feedback_v2_path_is_an_error`).
10
+ *
11
+ * Caller is expected to validate that the config carries a `projectSlug`
12
+ * at construction time (see `validateGateConfig`).
13
+ */
14
+
15
+ import type { GateConfig } from "./mode.ts";
16
+
17
+ /** Return the project-scoped path root for the supplied config, e.g.
18
+ * `/@partner-console-staging`. */
19
+ export function resolveProjectPathRoot(config: GateConfig): string {
20
+ return `/@${config.projectSlug}`;
21
+ }
package/src/region.ts ADDED
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Regional host resolution.
3
+ *
4
+ * The region-free org host `<org>.api[-staging].k9o.io` redirects GET/HEAD only and REFUSES a request that carries a
5
+ * body, an `Authorization` header or a cookie (`400 K9O_INVALID_REQUEST_SHAPE`, `region_free_host_takes_no_credentials`),
6
+ * so credentials must go to `<org>.api[-staging]-<rgn>.k9o.io`. An SDK learns the region with ONE unauthenticated
7
+ * `HEAD https://<org>.api[-staging].k9o.io/`, takes the `308` `Location`, and caches the regional origin.
8
+ *
9
+ * Properties this module holds:
10
+ * - Only a region-free org host (shape `<org>.api.k9o.io` or `<org>.api-staging.k9o.io`) is ever probed. A regional,
11
+ * custom, self-hosted or dev baseUrl is used exactly as given.
12
+ * - The probe carries NO credential and none of the configured default headers (they may hold one).
13
+ * - The `Location` is trusted only if it is `https`, has no userinfo/port, and its host is exactly the SAME org on
14
+ * the SAME apex family with a 4-character region code. Anything else is ignored and the configured baseUrl stays,
15
+ * so a hostile redirect can never receive a credential.
16
+ * - Not a redirect (the platform has not cut over, or the host answers directly), or any failure: the configured
17
+ * baseUrl stays and the server's own refusal, if any, is what the caller sees. A definite answer is cached for the
18
+ * life of the client's config; a network failure is not cached.
19
+ */
20
+
21
+ /** The slice of a client config this module needs (structural, so core and gate share one implementation). */
22
+ export type RegionConfig = { baseUrl: string; fetch?: typeof globalThis.fetch | undefined };
23
+
24
+ const REGION_FREE_ORG_HOST = /^([a-z][a-z0-9-]{1,62})\.(api|api-staging)\.k9o\.io$/;
25
+ const REGION_CODE = /^[a-z]{2}\d{2}$/;
26
+
27
+ const cache = new WeakMap<RegionConfig, Promise<string>>();
28
+
29
+ /** The regional origin a `Location` may name for `host`, or null if it is not exactly that. Pure. */
30
+ export function regionalOriginFromLocation(host: string, location: string, base: string): string | null {
31
+ const m = REGION_FREE_ORG_HOST.exec(host);
32
+ if (m === null) return null;
33
+ let u: URL;
34
+ try {
35
+ u = new URL(location, base);
36
+ } catch {
37
+ return null;
38
+ }
39
+ if (u.protocol !== "https:" || u.username !== "" || u.password !== "" || u.port !== "") return null;
40
+ const [, org, apex] = m;
41
+ const want = new RegExp(`^${org}\\.${apex}-([a-z0-9]+)\\.k9o\\.io$`);
42
+ const r = want.exec(u.hostname);
43
+ if (r === null || !REGION_CODE.test(r[1]!)) return null;
44
+ return `https://${u.hostname}`;
45
+ }
46
+
47
+ async function probe(config: RegionConfig): Promise<{ origin: string; cacheable: boolean }> {
48
+ const fetchImpl = config.fetch ?? globalThis.fetch;
49
+ const configured = config.baseUrl;
50
+ if (typeof fetchImpl !== "function") return { origin: configured, cacheable: false };
51
+ let host: string;
52
+ try {
53
+ host = new URL(configured).hostname;
54
+ } catch {
55
+ return { origin: configured, cacheable: true };
56
+ }
57
+ if (!REGION_FREE_ORG_HOST.test(host)) return { origin: configured, cacheable: true };
58
+ try {
59
+ const res = await fetchImpl(`${configured.replace(/\/+$/, "")}/`, {
60
+ method: "HEAD",
61
+ redirect: "manual",
62
+ headers: { accept: "*/*" },
63
+ } as Parameters<typeof fetchImpl>[1]);
64
+ if (res.status === 308) {
65
+ const loc = res.headers.get("location");
66
+ const origin = loc === null ? null : regionalOriginFromLocation(host, loc, configured);
67
+ if (origin !== null) return { origin, cacheable: true };
68
+ }
69
+ return { origin: configured, cacheable: true };
70
+ } catch {
71
+ return { origin: configured, cacheable: false };
72
+ }
73
+ }
74
+
75
+ /** The origin requests for this client go to: the cached regional origin once learned, else the configured baseUrl. */
76
+ export function resolveRegionalOrigin(config: RegionConfig): Promise<string> {
77
+ const hit = cache.get(config);
78
+ if (hit !== undefined) return hit;
79
+ const p = probe(config).then((r) => {
80
+ if (!r.cacheable) cache.delete(config);
81
+ return r.origin;
82
+ });
83
+ cache.set(config, p);
84
+ return p;
85
+ }