@supatype/ssr 0.9.0 → 0.9.2

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 @@
1
+ {"version":3,"file":"server-env.d.ts","sourceRoot":"","sources":["../src/server-env.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,eAAO,MAAM,cAAc,iBAAiB,CAAA;AAC5C,eAAO,MAAM,mBAAmB,sBAAsB,CAAA;AAEtD;;;GAGG;AACH,eAAO,MAAM,gBAAgB,uDAAwD,CAAA;AACrF,eAAO,MAAM,qBAAqB,iEAAkE,CAAA;AAEpG;;;GAGG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAI1D"}
@@ -0,0 +1,25 @@
1
+ /**
2
+ * The two variables a Next.js server (or any server-side code) reads the deployment's address and
3
+ * anon key from: `createServerClient`'s defaults, and the values `@supatype/ssr/next` serves to the
4
+ * page. They are read where the app runs, so one build serves whichever deployment it runs as. A
5
+ * `NEXT_PUBLIC_` name, fixed into the build, is only the server client's fallback.
6
+ */
7
+ export const SERVER_URL_ENV = "SUPATYPE_URL";
8
+ export const SERVER_ANON_KEY_ENV = "SUPATYPE_ANON_KEY";
9
+ /**
10
+ * Where `createServerClient` looks for each value: the server's own name first, read where the app
11
+ * runs, then the Next.js build-time name an app may already set. The route serves only the first.
12
+ */
13
+ export const SERVER_URL_NAMES = [SERVER_URL_ENV, "NEXT_PUBLIC_SUPATYPE_URL"];
14
+ export const SERVER_ANON_KEY_NAMES = [SERVER_ANON_KEY_ENV, "NEXT_PUBLIC_SUPATYPE_ANON_KEY"];
15
+ /**
16
+ * A variable from the server's environment, trimmed; undefined when unset or blank, and where there
17
+ * is no `process` at all. Read by name at call time, so no bundler can fix its build-time value in.
18
+ */
19
+ export function serverEnv(name) {
20
+ if (typeof process === "undefined" || typeof process.env !== "object")
21
+ return undefined;
22
+ const value = process.env[name]?.trim();
23
+ return value === undefined || value === "" ? undefined : value;
24
+ }
25
+ //# sourceMappingURL=server-env.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server-env.js","sourceRoot":"","sources":["../src/server-env.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,MAAM,CAAC,MAAM,cAAc,GAAG,cAAc,CAAA;AAC5C,MAAM,CAAC,MAAM,mBAAmB,GAAG,mBAAmB,CAAA;AAEtD;;;GAGG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,cAAc,EAAE,0BAA0B,CAAU,CAAA;AACrF,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,mBAAmB,EAAE,+BAA+B,CAAU,CAAA;AAEpG;;;GAGG;AACH,MAAM,UAAU,SAAS,CAAC,IAAY;IACpC,IAAI,OAAO,OAAO,KAAK,WAAW,IAAI,OAAO,OAAO,CAAC,GAAG,KAAK,QAAQ;QAAE,OAAO,SAAS,CAAA;IACvF,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,CAAA;IACvC,OAAO,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,CAAA;AAChE,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@supatype/ssr",
3
- "version": "0.9.0",
3
+ "version": "0.9.2",
4
4
  "license": "MIT",
5
5
  "description": "Supatype server-side rendering utilities, create a client from cookie-based auth for Server Components, Route Handlers, and middleware",
6
6
  "type": "module",
@@ -10,10 +10,14 @@
10
10
  ".": {
11
11
  "import": "./dist/index.js",
12
12
  "types": "./dist/index.d.ts"
13
+ },
14
+ "./next": {
15
+ "import": "./dist/next.js",
16
+ "types": "./dist/next.d.ts"
13
17
  }
14
18
  },
15
19
  "dependencies": {
16
- "@supatype/client": "0.9.0"
20
+ "@supatype/client": "0.9.2"
17
21
  },
18
22
  "devDependencies": {
19
23
  "@types/node": "^22",
@@ -1,5 +1,6 @@
1
1
  import type { Session, User } from "@supatype/client"
2
2
  import type { CookieToSet } from "./types.js"
3
+ import { decodeBase64, isJsonObject, jwtClaims } from "./jwt-claims.js"
3
4
 
4
5
  /** The prefix `@supatype/client` names its session cookie with: `st-auth-token`. */
5
6
  export const DEFAULT_COOKIE_PREFIX = "st"
@@ -29,11 +30,6 @@ export function parseSessionFromCookies(
29
30
  return null
30
31
  }
31
32
 
32
- /** True for a JSON object: not null, not an array. */
33
- function isJsonObject(value: unknown): value is Record<string, unknown> {
34
- return typeof value === "object" && value !== null && !Array.isArray(value)
35
- }
36
-
37
33
  function parseSessionValue(value: string): Session | null {
38
34
  try {
39
35
  return normalizeSession(JSON.parse(decodeURIComponent(value)))
@@ -44,17 +40,6 @@ function parseSessionValue(value: string): Session | null {
44
40
  return null
45
41
  }
46
42
 
47
- /**
48
- * Base64 or base64url text decoded as UTF-8, with `atob` and `TextDecoder` rather than Node's
49
- * `Buffer`: the server client also runs on edge runtimes, which have no `Buffer`. Throws on input
50
- * that is not base64.
51
- */
52
- function decodeBase64(text: string): string {
53
- const standard = text.replace(/-/g, "+").replace(/_/g, "/")
54
- const binary = atob(standard + "=".repeat((4 - (standard.length % 4)) % 4))
55
- return new TextDecoder().decode(Uint8Array.from(binary, (c) => c.charCodeAt(0)))
56
- }
57
-
58
43
  /**
59
44
  * The session a cookie holds. One whose access token has expired is kept when it carries a refresh
60
45
  * token: the first request the client makes refreshes it, and the server client writes the new
@@ -76,18 +61,12 @@ function normalizeSession(r: unknown): Session | null {
76
61
  }
77
62
 
78
63
  function isJwtExpired(token: string): boolean {
79
- const parts = token.split(".")
80
- if (parts.length !== 3) return true
81
- try {
82
- const payload = JSON.parse(decodeBase64(parts[1]!))
83
- // A payload that is not an object reads as expired, as it did when reading it threw.
84
- if (!isJsonObject(payload)) return true
85
- const exp = typeof payload["exp"] === "number" ? payload["exp"] : null
86
- if (exp === null) return false
87
- return Date.now() / 1000 > exp
88
- } catch {
89
- return true
90
- }
64
+ // A token that is not a JWT, or whose payload is not an object, reads as expired.
65
+ const payload = jwtClaims(token)
66
+ if (payload === null) return true
67
+ const exp = typeof payload["exp"] === "number" ? payload["exp"] : null
68
+ if (exp === null) return false
69
+ return Date.now() / 1000 > exp
91
70
  }
92
71
 
93
72
  function normalizeUser(raw: Record<string, unknown>): User {
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Reading a JWT's claims without verifying it, in a way every runtime the server client reaches
3
+ * supports: `atob` and `TextDecoder` rather than Node's `Buffer`, which edge runtimes do not have.
4
+ * Shared by the cookie parser (a session's expiry) and the Next.js route (a service role token
5
+ * where the anon key belongs).
6
+ */
7
+
8
+ /** True for a JSON object: not null, not an array. */
9
+ export function isJsonObject(value: unknown): value is Record<string, unknown> {
10
+ return typeof value === "object" && value !== null && !Array.isArray(value)
11
+ }
12
+
13
+ /** Base64 or base64url text decoded as UTF-8. Throws on input that is not base64. */
14
+ export function decodeBase64(text: string): string {
15
+ const standard = text.replace(/-/g, "+").replace(/_/g, "/")
16
+ const binary = atob(standard + "=".repeat((4 - (standard.length % 4)) % 4))
17
+ return new TextDecoder().decode(Uint8Array.from(binary, (c) => c.charCodeAt(0)))
18
+ }
19
+
20
+ /** The payload of a three-part JWT, or null for anything else. Not verified. */
21
+ export function jwtClaims(token: string): Record<string, unknown> | null {
22
+ const payload = token.split(".")
23
+ if (payload.length !== 3 || payload[1] === undefined) return null
24
+ try {
25
+ const claims: unknown = JSON.parse(decodeBase64(payload[1]))
26
+ return isJsonObject(claims) ? claims : null
27
+ } catch {
28
+ return null
29
+ }
30
+ }
package/src/next.ts ADDED
@@ -0,0 +1,160 @@
1
+ /**
2
+ * `/supatype-env.js` for a Next.js app: the route that gives a page the deployment's API address
3
+ * and anon key when it loads, so one `next build` runs against any deployment.
4
+ *
5
+ * `next build` prerenders the static pages without the deployment's values, and the client then
6
+ * reads them from `window.__SUPATYPE_ENV__` at its first request. This route sets that global from
7
+ * `SUPATYPE_URL` and `SUPATYPE_ANON_KEY` as the running server has them, with the same body,
8
+ * headers and misconfigured answer as the Supatype server's own `/supatype-env.js`. Put it at
9
+ * `app/supatype-env.js/route.ts`:
10
+ *
11
+ * export { GET } from "@supatype/ssr/next"
12
+ *
13
+ * It must not be prerendered, or the build machine's values (usually none) would be served as a
14
+ * static file. `GET` reads the request, which is what keeps it per request on every Next version:
15
+ * Next 14 and Next 16 with `cacheComponents` stop prerendering a `GET` handler that reads its
16
+ * request, and Next 15 and 16 without it render every `GET` per request anyway. The route file
17
+ * needs no segment config, and must not have one: Next 16 with `cacheComponents` answers 500 for a
18
+ * route that exports `dynamic` (0.9.1 release test, RB6). Then load it before the app in the root
19
+ * layout:
20
+ *
21
+ * <Script src="/supatype-env.js" strategy="beforeInteractive" />
22
+ *
23
+ * The anon key is not a secret: every browser that loads the app holds it, and row-level security
24
+ * protects the data. The service role key is never read here, and an anon key variable holding a
25
+ * service role token is refused rather than published.
26
+ */
27
+
28
+ import { jwtClaims } from "./jwt-claims.js"
29
+ import { SERVER_ANON_KEY_ENV, SERVER_URL_ENV, serverEnv } from "./server-env.js"
30
+
31
+ /**
32
+ * @deprecated Do not export it from the route: Next reads no re-exported segment config, and Next 16
33
+ * with `cacheComponents` refuses a `dynamic` one. `GET` keeps itself per request (see above). Kept
34
+ * so an import of it still builds.
35
+ */
36
+ export const dynamic = "force-dynamic"
37
+
38
+ const PUBLIC_ENV_SWITCH = "SUPATYPE_PUBLIC_ENV"
39
+ const SCRIPT_GLOBAL = "window.__SUPATYPE_ENV__"
40
+
41
+ /** `<`, `>`, `&` and the two JavaScript line separators, escaped in the body as Go's JSON does. */
42
+ const SCRIPT_UNSAFE = new Set([0x3c, 0x3e, 0x26, 0x2028, 0x2029])
43
+
44
+ /**
45
+ * The deployment's values for the page; or the reason it is misconfigured, a fault to fix; or
46
+ * switched off, as if there were no route.
47
+ */
48
+ type PublicEnv = { url: string; anonKey: string } | { error: string } | "off"
49
+
50
+ /**
51
+ * `GET /supatype-env.js`: the script setting `window.__SUPATYPE_ENV__`. Misconfigured, it is still
52
+ * 200 and sets only `error`, the reason, because a browser runs no script answered with an error
53
+ * status and tells the page nothing of why: this is the one way the client can name the fault on
54
+ * its first call. Switched off it is 404, as the Supatype server answers.
55
+ *
56
+ * Next passes the request; reading it keeps the route out of the build's prerender (see the top of
57
+ * this file). Nothing in it changes the answer. It is required, not optional: Next type-checks a
58
+ * route handler's first parameter as `Request | NextRequest`, and `Request | undefined` failed
59
+ * `next build` in a Next 15 app.
60
+ */
61
+ export function GET(request: Request): Response {
62
+ void request.headers
63
+ const env = readPublicEnv()
64
+ if (env === "off") return notFound()
65
+ // A reason is kept by nothing, so the fixed configuration is read on the next load. Values are
66
+ // revalidated on every load: they change when the deployment's configuration does.
67
+ return script(env, "error" in env ? "no-store" : "no-cache")
68
+ }
69
+
70
+ /** The values to serve, read from the environment now, or why there are none. */
71
+ function readPublicEnv(): PublicEnv {
72
+ const enabled = publicEnvSwitch(serverEnv(PUBLIC_ENV_SWITCH))
73
+ if (enabled === false) return "off"
74
+ // A word it cannot read is a fault to fix, not a choice to turn the route off.
75
+ if (enabled !== true) return { error: enabled.invalid }
76
+ // Both, or neither: a page given only the key fails at its first request for want of an address,
77
+ // and the reason naming the variables says why, where the deployment is configured. Every fault
78
+ // is named in one reason, one per line and the key's first, so a single visit fixes them all.
79
+ const url = publicUrl(serverEnv(SERVER_URL_ENV))
80
+ const anonKey = serverEnv(SERVER_ANON_KEY_ENV)
81
+ const keyFault = anonKeyFault(anonKey)
82
+ const urlFault = url === undefined ? notSet(SERVER_URL_ENV) : undefined
83
+ if (url === undefined || anonKey === undefined || keyFault !== undefined) {
84
+ const faults = [keyFault, urlFault].filter((fault): fault is string => fault !== undefined)
85
+ return { error: faults.join("\n") }
86
+ }
87
+ return { url, anonKey }
88
+ }
89
+
90
+ /** Why the anon key variable cannot be served, or undefined when it can. */
91
+ function anonKeyFault(anonKey: string | undefined): string | undefined {
92
+ if (anonKey === undefined) return notSet(SERVER_ANON_KEY_ENV)
93
+ if (jwtClaims(anonKey)?.["role"] !== "service_role") return undefined
94
+ return (
95
+ `public env unavailable: ${SERVER_ANON_KEY_ENV} holds a service_role token, which must never ` +
96
+ "reach a browser. Set it to the project's anon key."
97
+ )
98
+ }
99
+
100
+ /** The reason line for a variable the server does not have, as the Supatype server words it. */
101
+ function notSet(name: string): string {
102
+ return `public env unavailable: ${name} is not set on this server`
103
+ }
104
+
105
+ /**
106
+ * `SUPATYPE_PUBLIC_ENV` as the server reads it: on when blank or 1, true, yes or on; off for 0, false,
107
+ * no or off. Any other word stops the server from starting; here, with no start to stop, the route
108
+ * is a reason naming the variable and the words it takes.
109
+ */
110
+ function publicEnvSwitch(raw: string | undefined): boolean | { invalid: string } {
111
+ const value = (raw ?? "").toLowerCase()
112
+ if (["", "1", "true", "yes", "on"].includes(value)) return true
113
+ if (["0", "false", "no", "off"].includes(value)) return false
114
+ return {
115
+ invalid:
116
+ `public env unavailable: ${PUBLIC_ENV_SWITCH}=${JSON.stringify(raw)} is not a switch value. Use ` +
117
+ "true, 1, yes or on (or leave it blank) to serve it, and false, 0, no or off to turn it off.",
118
+ }
119
+ }
120
+
121
+ /** The API root, as the server gives it: no trailing slash, no auth service mount. */
122
+ function publicUrl(raw: string | undefined): string | undefined {
123
+ const trimmed = raw?.replace(/\/+$/, "").replace(/\/auth\/v1$/, "")
124
+ return trimmed === undefined || trimmed === "" ? undefined : trimmed
125
+ }
126
+
127
+ /** JSON that cannot close the script element or end the statement early. */
128
+ function escapeForScript(json: string): string {
129
+ let out = ""
130
+ for (const ch of json) {
131
+ const code = ch.codePointAt(0) ?? 0
132
+ out += SCRIPT_UNSAFE.has(code) ? `\\u${code.toString(16).padStart(4, "0")}` : ch
133
+ }
134
+ return out
135
+ }
136
+
137
+ /** The statement setting `window.__SUPATYPE_ENV__` to `doc`, with the server's headers. */
138
+ function script(doc: object, cacheControl: "no-cache" | "no-store"): Response {
139
+ const body = `${SCRIPT_GLOBAL} = ${escapeForScript(JSON.stringify(doc))};\n`
140
+ return new Response(body, {
141
+ status: 200,
142
+ headers: {
143
+ "Content-Type": "application/javascript; charset=utf-8",
144
+ "Cache-Control": cacheControl,
145
+ "X-Content-Type-Options": "nosniff",
146
+ },
147
+ })
148
+ }
149
+
150
+ /** A 404 nothing keeps, so switching the route back on is seen at once, as the server answers. */
151
+ function notFound(): Response {
152
+ return new Response("404 page not found\n", {
153
+ status: 404,
154
+ headers: {
155
+ "Content-Type": "text/plain; charset=utf-8",
156
+ "Cache-Control": "no-store",
157
+ "X-Content-Type-Options": "nosniff",
158
+ },
159
+ })
160
+ }
@@ -1,6 +1,7 @@
1
1
  import { createClient } from "@supatype/client"
2
2
  import type { SupatypeClient, AnyDatabase } from "@supatype/client"
3
3
  import { DEFAULT_COOKIE_PREFIX, parseSessionFromCookies, sessionCookie } from "./cookie-parser.js"
4
+ import { SERVER_ANON_KEY_NAMES, SERVER_URL_NAMES, serverEnv } from "./server-env.js"
4
5
  import type { CookieAdapter, ServerClientOptions } from "./types.js"
5
6
 
6
7
  /**
@@ -14,17 +15,30 @@ import type { CookieAdapter, ServerClientOptions } from "./types.js"
14
15
  * Without `setAll` (a Server Component) it never refreshes: an expired access token is sent as it
15
16
  * is and refused. A refresh there would spend the browser's refresh token and return one the
16
17
  * browser never receives, so the browser's own next refresh would be refused and sign it out.
18
+ *
19
+ * The address and anon key default to `SUPATYPE_URL` and `SUPATYPE_ANON_KEY` from the server's
20
+ * environment, read now: pass only the options, or `undefined` for either. These are the same two
21
+ * variables `@supatype/ssr/next` serves to the page. Where one is unset, `NEXT_PUBLIC_SUPATYPE_URL`
22
+ * or `NEXT_PUBLIC_SUPATYPE_ANON_KEY` is used instead. With none given or set, the client's first
23
+ * request throws the error naming them.
17
24
  */
18
25
  export function createServerClient<TDatabase extends AnyDatabase = AnyDatabase>(
19
- url: string,
20
- anonKey: string,
21
26
  options: ServerClientOptions,
27
+ ): SupatypeClient<TDatabase>
28
+ export function createServerClient<TDatabase extends AnyDatabase = AnyDatabase>(
29
+ url: string | undefined,
30
+ anonKey: string | undefined,
31
+ options: ServerClientOptions,
32
+ ): SupatypeClient<TDatabase>
33
+ export function createServerClient<TDatabase extends AnyDatabase = AnyDatabase>(
34
+ ...args: [ServerClientOptions] | [string | undefined, string | undefined, ServerClientOptions]
22
35
  ): SupatypeClient<TDatabase> {
36
+ const [url, anonKey, options] = args.length === 1 ? [undefined, undefined, args[0]] : args
23
37
  const prefix = options.cookiePrefix ?? DEFAULT_COOKIE_PREFIX
24
38
  const session = parseSessionFromCookies(options.cookies.getAll(), prefix)
25
39
  const client = createClient<TDatabase>({
26
- url,
27
- anonKey,
40
+ url: givenOrServerEnv(url, SERVER_URL_NAMES),
41
+ anonKey: givenOrServerEnv(anonKey, SERVER_ANON_KEY_NAMES),
28
42
  auth: {
29
43
  persistSession: false,
30
44
  autoRefreshToken: false,
@@ -37,6 +51,16 @@ export function createServerClient<TDatabase extends AnyDatabase = AnyDatabase>(
37
51
  return client
38
52
  }
39
53
 
54
+ /** The value given, unless it is missing or blank, else the first of the server's `names` that is set. */
55
+ function givenOrServerEnv(given: string | undefined, names: readonly string[]): string | undefined {
56
+ if (given !== undefined && given.trim() !== "") return given
57
+ for (const name of names) {
58
+ const value = serverEnv(name)
59
+ if (value !== undefined) return value
60
+ }
61
+ return undefined
62
+ }
63
+
40
64
  /**
41
65
  * Send every change to the client's session (a refresh, a sign-in, a sign-out) back to the browser
42
66
  * through the adapter's `setAll`, so the next request reads the new tokens rather than the old ones.
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The two variables a Next.js server (or any server-side code) reads the deployment's address and
3
+ * anon key from: `createServerClient`'s defaults, and the values `@supatype/ssr/next` serves to the
4
+ * page. They are read where the app runs, so one build serves whichever deployment it runs as. A
5
+ * `NEXT_PUBLIC_` name, fixed into the build, is only the server client's fallback.
6
+ */
7
+
8
+ export const SERVER_URL_ENV = "SUPATYPE_URL"
9
+ export const SERVER_ANON_KEY_ENV = "SUPATYPE_ANON_KEY"
10
+
11
+ /**
12
+ * Where `createServerClient` looks for each value: the server's own name first, read where the app
13
+ * runs, then the Next.js build-time name an app may already set. The route serves only the first.
14
+ */
15
+ export const SERVER_URL_NAMES = [SERVER_URL_ENV, "NEXT_PUBLIC_SUPATYPE_URL"] as const
16
+ export const SERVER_ANON_KEY_NAMES = [SERVER_ANON_KEY_ENV, "NEXT_PUBLIC_SUPATYPE_ANON_KEY"] as const
17
+
18
+ /**
19
+ * A variable from the server's environment, trimmed; undefined when unset or blank, and where there
20
+ * is no `process` at all. Read by name at call time, so no bundler can fix its build-time value in.
21
+ */
22
+ export function serverEnv(name: string): string | undefined {
23
+ if (typeof process === "undefined" || typeof process.env !== "object") return undefined
24
+ const value = process.env[name]?.trim()
25
+ return value === undefined || value === "" ? undefined : value
26
+ }
@@ -0,0 +1,205 @@
1
+ /**
2
+ * `@supatype/ssr/next`: `/supatype-env.js` served by a Next.js app, from the server's environment.
3
+ *
4
+ * `next build` prerenders the app's pages without the deployment's values. The route below answers
5
+ * every page load with the ones the running server has, in the same body, headers and refusals as
6
+ * the Supatype server's own `/supatype-env.js`, so one build runs on any deployment.
7
+ */
8
+ import { runInNewContext } from "node:vm"
9
+ import { afterEach, assert, describe, expect, expectTypeOf, it, vi } from "vitest"
10
+ import { GET } from "../src/next.js"
11
+
12
+ afterEach(() => {
13
+ vi.unstubAllEnvs()
14
+ })
15
+
16
+ /** A page load of the route, as Next hands it to GET. */
17
+ function load(): Response {
18
+ return GET(new Request("http://localhost/supatype-env.js"))
19
+ }
20
+
21
+ /** An unsigned JWT carrying `role`. */
22
+ function jwtFor(role: string): string {
23
+ return `e30.${Buffer.from(JSON.stringify({ role })).toString("base64url")}.sig`
24
+ }
25
+
26
+ /** Set the two variables the route reads; undefined removes one. */
27
+ function serverEnv(url: string | undefined, anonKey: string | undefined): void {
28
+ vi.stubEnv("SUPATYPE_URL", url)
29
+ vi.stubEnv("SUPATYPE_ANON_KEY", anonKey)
30
+ }
31
+
32
+ /** What the page's global holds after running `body`, as a browser would. */
33
+ function pageEnvAfter(body: string): unknown {
34
+ const window: Record<string, unknown> = {}
35
+ runInNewContext(body, { window })
36
+ return window["__SUPATYPE_ENV__"]
37
+ }
38
+
39
+ /**
40
+ * The reason a misconfigured route gives the page. A browser runs no script answered with an error
41
+ * status and tells the page nothing of why, so the route answers 200, kept by nothing, with a
42
+ * script that sets only `error`: the one way the client can name the fault on its first call.
43
+ */
44
+ async function reasonFrom(res: Response): Promise<{ error: string; body: string }> {
45
+ expect(res.status).toBe(200)
46
+ expect(res.headers.get("content-type")).toBe("application/javascript; charset=utf-8")
47
+ expect(res.headers.get("cache-control")).toBe("no-store")
48
+ expect(res.headers.get("x-content-type-options")).toBe("nosniff")
49
+ const body = await res.text()
50
+ const env = pageEnvAfter(body)
51
+ assert(typeof env === "object" && env !== null && "error" in env && typeof env.error === "string")
52
+ expect(Object.keys(env)).toEqual(["error"])
53
+ return { error: env.error, body }
54
+ }
55
+
56
+ describe("GET /supatype-env.js", () => {
57
+ // 0.9.1 release test (RB6): Next stops prerendering a GET handler that reads the request (Next 14
58
+ // and 16 with cacheComponents; 15 renders every GET per request), so `next build` cannot bake the
59
+ // build machine's values into a static file. The route file exports no segment config to do it.
60
+ // Next type-checks a route handler's first parameter as Request | NextRequest, and an optional
61
+ // one (Request | undefined) failed `next build` in a Next 15 app (the blog example).
62
+ it("takes the request as a required parameter, as Next type-checks it", () => {
63
+ expectTypeOf<Parameters<typeof GET>>().toEqualTypeOf<[request: Request]>()
64
+ })
65
+
66
+ it("reads the request, which keeps Next from prerendering it", () => {
67
+ serverEnv("https://api.example.com", "anon-key")
68
+ const request = new Request("http://localhost/supatype-env.js")
69
+ let headersRead = 0
70
+ const headers = request.headers
71
+ Object.defineProperty(request, "headers", { get: () => { headersRead += 1; return headers } })
72
+
73
+ expect(GET(request).status).toBe(200)
74
+ expect(headersRead).toBeGreaterThan(0)
75
+ })
76
+
77
+ it("sets window.__SUPATYPE_ENV__ to the server's address and anon key", async () => {
78
+ serverEnv("https://api.example.com", "anon-key")
79
+ const res = load()
80
+
81
+ expect(res.status).toBe(200)
82
+ expect(await res.text()).toBe('window.__SUPATYPE_ENV__ = {"url":"https://api.example.com","anonKey":"anon-key"};\n')
83
+ })
84
+
85
+ it("carries the server's headers: a script, revalidated on every load, never sniffed", () => {
86
+ serverEnv("https://api.example.com", "anon-key")
87
+ const res = load()
88
+
89
+ expect(res.headers.get("content-type")).toBe("application/javascript; charset=utf-8")
90
+ expect(res.headers.get("cache-control")).toBe("no-cache")
91
+ expect(res.headers.get("x-content-type-options")).toBe("nosniff")
92
+ })
93
+
94
+ it("reads the environment per request, so one build serves whichever values it runs with", async () => {
95
+ serverEnv("https://one.example.com", "key-one")
96
+ const first = pageEnvAfter(await load().text())
97
+ serverEnv("https://two.example.com", "key-two")
98
+ const second = pageEnvAfter(await load().text())
99
+
100
+ expect(first).toEqual({ url: "https://one.example.com", anonKey: "key-one" })
101
+ expect(second).toEqual({ url: "https://two.example.com", anonKey: "key-two" })
102
+ })
103
+
104
+ it("sets only the reason, 200 no-store, naming the variable, when the address is unset", async () => {
105
+ serverEnv(undefined, "anon-key")
106
+ const { error, body } = await reasonFrom(load())
107
+
108
+ expect(error).toBe("public env unavailable: SUPATYPE_URL is not set on this server")
109
+ expect(body).not.toContain("anon-key")
110
+ })
111
+
112
+ it("trims the address as the server does", async () => {
113
+ serverEnv(" https://api.example.com/auth/v1/ ", " anon-key ")
114
+ expect(pageEnvAfter(await load().text())).toEqual({ url: "https://api.example.com", anonKey: "anon-key" })
115
+ })
116
+
117
+ it("escapes what could end the script element or the statement", async () => {
118
+ const hostile = "</script><script>alert(1)</script>\u2028\u2029&"
119
+ serverEnv("https://api.example.com", hostile)
120
+ const body = await load().text()
121
+
122
+ expect(body).not.toContain("</script>")
123
+ expect(body).not.toMatch(/[<>&\u2028\u2029]/)
124
+ expect(pageEnvAfter(body)).toEqual({ url: "https://api.example.com", anonKey: hostile })
125
+ })
126
+
127
+ it("sets only the reason, 200 no-store, naming the variable, when the anon key is unset", async () => {
128
+ serverEnv("https://api.example.com", undefined)
129
+ const { error } = await reasonFrom(load())
130
+
131
+ expect(error).toBe("public env unavailable: SUPATYPE_ANON_KEY is not set on this server")
132
+ })
133
+
134
+ it("names every unset setting in one reason, the anon key first, so one fix covers both", async () => {
135
+ serverEnv(undefined, undefined)
136
+ const { body } = await reasonFrom(load())
137
+
138
+ expect(body).toBe(
139
+ 'window.__SUPATYPE_ENV__ = {"error":"public env unavailable: SUPATYPE_ANON_KEY is not set on this server\\n' +
140
+ 'public env unavailable: SUPATYPE_URL is not set on this server"};\n',
141
+ )
142
+ })
143
+
144
+ it("names an unset address beside a service role anon key, whose refusal reads as before", async () => {
145
+ const service = jwtFor("service_role")
146
+ serverEnv(undefined, service)
147
+ const { error, body } = await reasonFrom(load())
148
+ const lines = error.split("\n")
149
+
150
+ expect(lines).toHaveLength(2)
151
+ expect(lines[0]).toContain("holds a service_role token")
152
+ expect(lines[1]).toBe("public env unavailable: SUPATYPE_URL is not set on this server")
153
+ expect(body).not.toContain(service)
154
+ })
155
+
156
+ it.each(["false", "0", "no", "off", " FALSE "])("is 404 no-store when SUPATYPE_PUBLIC_ENV is %j", async (off) => {
157
+ serverEnv("https://api.example.com", "anon-key")
158
+ vi.stubEnv("SUPATYPE_PUBLIC_ENV", off)
159
+ const res = load()
160
+
161
+ expect(res.status).toBe(404)
162
+ expect(res.headers.get("cache-control")).toBe("no-store")
163
+ expect(await res.text()).not.toContain("anon-key")
164
+ })
165
+
166
+ it.each(["", "true", "1", "yes", "on"])("serves when SUPATYPE_PUBLIC_ENV is %j", (on) => {
167
+ serverEnv("https://api.example.com", "anon-key")
168
+ vi.stubEnv("SUPATYPE_PUBLIC_ENV", on)
169
+ expect(load().status).toBe(200)
170
+ })
171
+
172
+ it("sets only the reason for a SUPATYPE_PUBLIC_ENV it cannot read, naming it and the words it takes", async () => {
173
+ serverEnv("https://api.example.com", "anon-key")
174
+ vi.stubEnv("SUPATYPE_PUBLIC_ENV", "nope")
175
+ const { error, body } = await reasonFrom(load())
176
+
177
+ expect(error).toContain('SUPATYPE_PUBLIC_ENV="nope"')
178
+ for (const word of ["true", "1", "yes", "on", "false", "0", "no", "off"]) expect(error).toContain(word)
179
+ expect(body).not.toContain("anon-key")
180
+ })
181
+
182
+ it("never serves a service role value", async () => {
183
+ const service = jwtFor("service_role")
184
+ serverEnv("https://api.example.com", "anon-key")
185
+ vi.stubEnv("SUPATYPE_SERVICE_ROLE_KEY", service)
186
+ vi.stubEnv("SERVICE_ROLE_KEY", service)
187
+
188
+ expect(await load().text()).not.toContain(service)
189
+ })
190
+
191
+ it("sets only the reason for an anon key that is a service role token, rather than publish it", async () => {
192
+ const service = jwtFor("service_role")
193
+ serverEnv("https://api.example.com", service)
194
+ const { error, body } = await reasonFrom(load())
195
+
196
+ expect(body).not.toContain(service)
197
+ expect(error).toContain("service_role")
198
+ })
199
+
200
+ it("serves an anon key that is an anon token", async () => {
201
+ const anon = jwtFor("anon")
202
+ serverEnv("https://api.example.com", anon)
203
+ expect(pageEnvAfter(await load().text())).toEqual({ url: "https://api.example.com", anonKey: anon })
204
+ })
205
+ })