@segmentstream-cloud/app 0.0.0-stage → 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 ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,2 @@
1
+ SegmentStream App SDK
2
+ Copyright 2026 SegmentStream
package/README.md CHANGED
@@ -1,3 +1,113 @@
1
- # Temporary Holding Version
1
+ # @segmentstream-cloud/app
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Sign-in and sessions for SegmentStream workspace apps built with Next.js (App Router,
4
+ version 16 or later). Every visitor signs in with their SegmentStream account, and only
5
+ members of the app's workspace get in.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install @segmentstream-cloud/app
11
+ ```
12
+
13
+ ## Add three files
14
+
15
+ **`src/segmentstream.ts`** configures the app once:
16
+
17
+ ```ts
18
+ import { createSegmentStreamApp } from "@segmentstream-cloud/app";
19
+
20
+ export const segmentstream = createSegmentStreamApp({
21
+ workspaceId: "your-workspace-id",
22
+ organizationId: "your-organization-id",
23
+ });
24
+ ```
25
+
26
+ **`src/proxy.ts`** keeps every page and API route signed in:
27
+
28
+ ```ts
29
+ import { segmentstream } from "./segmentstream";
30
+
31
+ export const proxy = segmentstream.proxy({
32
+ // Optional: paths that anyone may open. `/health` also covers `/health/live`.
33
+ publicPaths: ["/health"],
34
+ });
35
+
36
+ export const config = {
37
+ matcher: ["/((?!_next/static|_next/image|favicon.ico|robots.txt).*)"],
38
+ };
39
+ ```
40
+
41
+ **`src/app/api/segmentstream/[...path]/route.ts`** handles the sign-in callback and
42
+ sign-out:
43
+
44
+ ```ts
45
+ import { segmentstream } from "../../../../segmentstream";
46
+
47
+ export const { GET, POST } = segmentstream.handlers();
48
+ ```
49
+
50
+ ## Read the signed-in user
51
+
52
+ ```tsx
53
+ import { segmentstream } from "@/segmentstream";
54
+
55
+ export default async function Page() {
56
+ const user = await segmentstream.requireUser();
57
+
58
+ return <p>Signed in as {user.email ?? user.id}</p>;
59
+ }
60
+ ```
61
+
62
+ - `getUser()` returns `{ id, email?, name?, organizationId, workspaceId }` or `null`.
63
+ - `requireUser()` returns the user, or redirects to `/api/segmentstream/sign-in` when
64
+ there is none. Next.js `unauthorized()` needs the experimental `authInterrupts` flag,
65
+ so the SDK restarts sign-in instead. The proxy normally signs users in first, so this
66
+ only happens on paths the proxy matcher excludes.
67
+ - `getAccessToken()` returns the verified app session token for calls to SegmentStream.
68
+
69
+ Use them in Server Components, Route Handlers, and Server Functions. Always check the
70
+ user in Server Functions and Route Handlers too; do not rely on the proxy alone.
71
+
72
+ To sign out, post a form to the SDK route:
73
+
74
+ ```tsx
75
+ <form action="/api/segmentstream/sign-out" method="post">
76
+ <button type="submit">Sign out</button>
77
+ </form>
78
+ ```
79
+
80
+ ## How requests are handled
81
+
82
+ - Page navigations without a session are redirected to SegmentStream to sign in, then
83
+ return to the page they started on.
84
+ - API routes, `fetch` calls, non-GET requests, and Next.js data requests receive
85
+ `401 {"error":"unauthenticated"}` instead of a redirect.
86
+ - `/api/segmentstream/*` and your `publicPaths` never require a session.
87
+
88
+ ## Environment
89
+
90
+ | Variable | Purpose |
91
+ | ------------------- | -------------------------------------------------------------------- |
92
+ | `SEGMENTSTREAM_URL` | SegmentStream origin. Defaults to `https://cloud.segmentstream.com`. |
93
+
94
+ ## Local development
95
+
96
+ `next dev` on `http://localhost` works. SegmentStream accepts loopback redirect URIs,
97
+ and the SDK drops the `__Host-` prefix and `Secure` attribute only for `http://localhost`,
98
+ `127.0.0.1`, and `[::1]`, which browsers otherwise reject over plain HTTP.
99
+
100
+ ## Security
101
+
102
+ - The app never sees SegmentStream's identity-provider tokens. It receives a short-lived
103
+ (5-minute) ES256 session token scoped to this workspace app and a rotating refresh
104
+ token, both in `HttpOnly`, `SameSite=Lax` cookies (`__Host-` and `Secure` in production).
105
+ - Session tokens are verified locally against SegmentStream's published keys: issuer,
106
+ expiry, workspace, organization, and an `app:` audience.
107
+ - The proxy refreshes expired sessions silently. When access is revoked, the next refresh
108
+ fails and the user is signed out.
109
+ - Sign-in uses the authorization-code flow with PKCE (S256) and a single-use `state`.
110
+
111
+ ## License
112
+
113
+ Apache-2.0
package/dist/app.d.ts ADDED
@@ -0,0 +1,23 @@
1
+ import type { SegmentStreamAppConfig } from "./config.js";
2
+ import type { SegmentStreamRouteHandlers } from "./handlers.js";
3
+ import type { ProxyOptions, SegmentStreamProxy } from "./proxy.js";
4
+ import type { Fetch } from "./sessions.js";
5
+ import type { AppUser, KeySet } from "./tokens.js";
6
+ export interface SegmentStreamApp {
7
+ /** The Next.js Proxy that keeps every non-public request signed in. */
8
+ readonly proxy: (options?: ProxyOptions) => SegmentStreamProxy;
9
+ /** Route Handlers for `app/api/segmentstream/[...path]/route.ts`. */
10
+ readonly handlers: () => SegmentStreamRouteHandlers;
11
+ /** The signed-in user for this request, or `null`. */
12
+ readonly getUser: () => Promise<AppUser | null>;
13
+ /** The signed-in user; redirects to sign-in when there is none. */
14
+ readonly requireUser: () => Promise<AppUser>;
15
+ /** The verified app session token for this request, or `null`. */
16
+ readonly getAccessToken: () => Promise<string | null>;
17
+ }
18
+ /** Replaceable capabilities, for tests. */
19
+ export interface AppDependencies {
20
+ readonly fetch: Fetch;
21
+ readonly keySet: KeySet;
22
+ }
23
+ export declare function createApp(config: SegmentStreamAppConfig, dependencies?: Partial<AppDependencies>): SegmentStreamApp;
package/dist/app.js ADDED
@@ -0,0 +1,26 @@
1
+ import { resolveConfig } from "./config.js";
2
+ import { createHandlers } from "./handlers.js";
3
+ import { createProxy } from "./proxy.js";
4
+ import { createServerSession } from "./server.js";
5
+ import { createSessionClient } from "./sessions.js";
6
+ import { createTokenVerifier, remoteKeySet } from "./tokens.js";
7
+ export function createApp(config, dependencies = {}) {
8
+ const resolved = resolveConfig(config);
9
+ const keySet = dependencies.keySet ?? remoteKeySet(resolved.baseUrl);
10
+ const fetchImplementation = dependencies.fetch ?? ((input, init) => fetch(input, init));
11
+ const sessionClient = createSessionClient(resolved, fetchImplementation);
12
+ const context = {
13
+ config: resolved,
14
+ verifyToken: createTokenVerifier(resolved, keySet),
15
+ requestToken: sessionClient.requestToken,
16
+ revokeSession: sessionClient.revoke,
17
+ };
18
+ const serverSession = createServerSession(context);
19
+ return {
20
+ proxy: (options) => createProxy(context, options),
21
+ handlers: () => createHandlers(context),
22
+ getUser: serverSession.getUser,
23
+ requireUser: serverSession.requireUser,
24
+ getAccessToken: serverSession.getAccessToken,
25
+ };
26
+ }
@@ -0,0 +1,18 @@
1
+ export declare const DEFAULT_BASE_URL = "https://cloud.segmentstream.com";
2
+ export interface SegmentStreamAppConfig {
3
+ /** The SegmentStream workspace that owns this app. */
4
+ readonly workspaceId: string;
5
+ /** The SegmentStream organization that owns the workspace. */
6
+ readonly organizationId: string;
7
+ /** SegmentStream origin. Defaults to `SEGMENTSTREAM_URL`, then `https://cloud.segmentstream.com`. */
8
+ readonly baseUrl?: string;
9
+ }
10
+ export interface ResolvedConfig {
11
+ readonly workspaceId: string;
12
+ readonly organizationId: string;
13
+ readonly baseUrl: string;
14
+ readonly issuer: string;
15
+ }
16
+ export declare function resolveConfig(config: SegmentStreamAppConfig): ResolvedConfig;
17
+ /** Linear-time trailing slash removal; `/\/+$/` backtracks quadratically on slash runs. */
18
+ export declare function trimTrailingSlashes(value: string): string;
package/dist/config.js ADDED
@@ -0,0 +1,41 @@
1
+ export const DEFAULT_BASE_URL = "https://cloud.segmentstream.com";
2
+ export function resolveConfig(config) {
3
+ const workspaceId = requireIdentifier("workspaceId", config.workspaceId);
4
+ const organizationId = requireIdentifier("organizationId", config.organizationId);
5
+ const baseUrl = normalizeBaseUrl(config.baseUrl ?? readEnvironment("SEGMENTSTREAM_URL") ?? DEFAULT_BASE_URL);
6
+ const issuer = readEnvironment("SEGMENTSTREAM_APP_TOKEN_ISSUER") ?? new URL(baseUrl).origin;
7
+ return { workspaceId, organizationId, baseUrl, issuer };
8
+ }
9
+ function requireIdentifier(name, value) {
10
+ const trimmed = typeof value === "string" ? value.trim() : "";
11
+ if (trimmed === "") {
12
+ throw new Error(`createSegmentStreamApp requires a non-empty ${name}.`);
13
+ }
14
+ return trimmed;
15
+ }
16
+ /** Linear-time trailing slash removal; `/\/+$/` backtracks quadratically on slash runs. */
17
+ export function trimTrailingSlashes(value) {
18
+ let end = value.length;
19
+ while (end > 0 && value.charCodeAt(end - 1) === 47) {
20
+ end -= 1;
21
+ }
22
+ return value.slice(0, end);
23
+ }
24
+ function normalizeBaseUrl(value) {
25
+ const trimmed = trimTrailingSlashes(value.trim());
26
+ let url;
27
+ try {
28
+ url = new URL(trimmed);
29
+ }
30
+ catch (error) {
31
+ throw new Error(`SegmentStream base URL is not a valid URL: ${trimmed}`, { cause: error });
32
+ }
33
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
34
+ throw new Error(`SegmentStream base URL must use http or https: ${trimmed}`);
35
+ }
36
+ return trimmed;
37
+ }
38
+ function readEnvironment(name) {
39
+ const value = typeof process === "undefined" ? undefined : process.env[name];
40
+ return value === undefined || value.trim() === "" ? undefined : value.trim();
41
+ }
@@ -0,0 +1,10 @@
1
+ import type { ResolvedConfig } from "./config.js";
2
+ import type { TokenExchange, TokenGrant } from "./sessions.js";
3
+ import type { TokenVerification } from "./tokens.js";
4
+ /** The resolved configuration and capabilities shared by the proxy, handlers, and server helpers. */
5
+ export interface AppContext {
6
+ readonly config: ResolvedConfig;
7
+ readonly verifyToken: (token: string) => Promise<TokenVerification>;
8
+ readonly requestToken: (grant: TokenGrant) => Promise<TokenExchange>;
9
+ readonly revokeSession: (refreshToken: string) => Promise<void>;
10
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,47 @@
1
+ import type { NextResponse } from "next/server";
2
+ export declare const REFRESH_COOKIE_MAX_AGE_SECONDS: number;
3
+ export declare const AUTH_FLOW_COOKIE_MAX_AGE_SECONDS: number;
4
+ export interface CookieNames {
5
+ readonly session: string;
6
+ readonly refresh: string;
7
+ readonly authFlow: string;
8
+ }
9
+ /** Cookie names and attributes for one request origin. */
10
+ export interface CookiePolicy {
11
+ readonly secure: boolean;
12
+ readonly names: CookieNames;
13
+ }
14
+ /** The PKCE flow state kept between starting sign-in and the callback. */
15
+ export interface AuthFlowState {
16
+ readonly state: string;
17
+ readonly codeVerifier: string;
18
+ readonly redirectUri: string;
19
+ readonly returnTo: string;
20
+ }
21
+ export interface SessionTokens {
22
+ readonly accessToken: string;
23
+ readonly expiresIn: number;
24
+ readonly refreshToken: string;
25
+ }
26
+ export declare function isLoopbackHostname(hostname: string): boolean;
27
+ /**
28
+ * Browsers reject `Secure` and `__Host-` cookies on plain-HTTP origins, except that
29
+ * local development on http://localhost should still work. Every other origin uses
30
+ * `__Host-` cookies, which cannot be set by sibling subdomains.
31
+ */
32
+ export declare function cookiePolicyFor(url: URL): CookiePolicy;
33
+ /** Candidate cookie names for code that only knows the request host (Server Components). */
34
+ export declare function sessionCookieCandidates(hostname: string): readonly string[];
35
+ export declare function setSessionCookies(response: NextResponse, policy: CookiePolicy, tokens: SessionTokens): void;
36
+ export declare function clearSessionCookies(response: NextResponse, policy: CookiePolicy): void;
37
+ export declare function setAuthFlowCookie(response: NextResponse, policy: CookiePolicy, flow: AuthFlowState): void;
38
+ export declare function clearAuthFlowCookie(response: NextResponse, policy: CookiePolicy): void;
39
+ export declare function encodeAuthFlowState(flow: AuthFlowState): string;
40
+ export declare function decodeAuthFlowState(value: string | undefined): AuthFlowState | null;
41
+ /** Reduces a return path to a same-origin relative path, falling back to `/`. */
42
+ export declare function safeReturnTo(value: string | null | undefined): string;
43
+ /**
44
+ * Replaces the named cookies in a raw `Cookie` request header while preserving every
45
+ * other cookie byte for byte.
46
+ */
47
+ export declare function replaceRequestCookies(cookieHeader: string | null, replacements: Record<string, string>): string;
@@ -0,0 +1,142 @@
1
+ import { base64UrlDecode, base64UrlEncode } from "./pkce.js";
2
+ export const REFRESH_COOKIE_MAX_AGE_SECONDS = 30 * 24 * 60 * 60;
3
+ export const AUTH_FLOW_COOKIE_MAX_AGE_SECONDS = 10 * 60;
4
+ const SECURE_NAMES = {
5
+ session: "__Host-ss_app_session",
6
+ refresh: "__Host-ss_app_refresh",
7
+ authFlow: "__Host-ss_app_auth",
8
+ };
9
+ const LOOPBACK_NAMES = {
10
+ session: "ss_app_session",
11
+ refresh: "ss_app_refresh",
12
+ authFlow: "ss_app_auth",
13
+ };
14
+ export function isLoopbackHostname(hostname) {
15
+ const normalized = hostname.toLowerCase();
16
+ return (normalized === "localhost" ||
17
+ normalized.endsWith(".localhost") ||
18
+ normalized === "[::1]" ||
19
+ normalized === "::1" ||
20
+ /^127(?:\.\d{1,3}){3}$/.test(normalized));
21
+ }
22
+ /**
23
+ * Browsers reject `Secure` and `__Host-` cookies on plain-HTTP origins, except that
24
+ * local development on http://localhost should still work. Every other origin uses
25
+ * `__Host-` cookies, which cannot be set by sibling subdomains.
26
+ */
27
+ export function cookiePolicyFor(url) {
28
+ const insecureLoopback = url.protocol === "http:" && isLoopbackHostname(url.hostname);
29
+ return insecureLoopback
30
+ ? { secure: false, names: LOOPBACK_NAMES }
31
+ : { secure: true, names: SECURE_NAMES };
32
+ }
33
+ /** Candidate cookie names for code that only knows the request host (Server Components). */
34
+ export function sessionCookieCandidates(hostname) {
35
+ return isLoopbackHostname(hostname)
36
+ ? [SECURE_NAMES.session, LOOPBACK_NAMES.session]
37
+ : [SECURE_NAMES.session];
38
+ }
39
+ function cookieAttributes(policy, maxAge) {
40
+ return {
41
+ httpOnly: true,
42
+ secure: policy.secure,
43
+ sameSite: "lax",
44
+ path: "/",
45
+ maxAge,
46
+ };
47
+ }
48
+ export function setSessionCookies(response, policy, tokens) {
49
+ const accessMaxAge = Math.max(1, Math.floor(tokens.expiresIn));
50
+ response.cookies.set(policy.names.session, tokens.accessToken, cookieAttributes(policy, accessMaxAge));
51
+ response.cookies.set(policy.names.refresh, tokens.refreshToken, cookieAttributes(policy, REFRESH_COOKIE_MAX_AGE_SECONDS));
52
+ }
53
+ export function clearSessionCookies(response, policy) {
54
+ clearCookie(response, policy, policy.names.session);
55
+ clearCookie(response, policy, policy.names.refresh);
56
+ }
57
+ export function setAuthFlowCookie(response, policy, flow) {
58
+ response.cookies.set(policy.names.authFlow, encodeAuthFlowState(flow), cookieAttributes(policy, AUTH_FLOW_COOKIE_MAX_AGE_SECONDS));
59
+ }
60
+ export function clearAuthFlowCookie(response, policy) {
61
+ clearCookie(response, policy, policy.names.authFlow);
62
+ }
63
+ // `__Host-` cookies are only replaced when the clearing cookie repeats Secure and Path=/.
64
+ function clearCookie(response, policy, name) {
65
+ response.cookies.set(name, "", { ...cookieAttributes(policy, 0), expires: new Date(0) });
66
+ }
67
+ export function encodeAuthFlowState(flow) {
68
+ return base64UrlEncode(new TextEncoder().encode(JSON.stringify(flow)));
69
+ }
70
+ export function decodeAuthFlowState(value) {
71
+ if (value === undefined || value === "") {
72
+ return null;
73
+ }
74
+ let candidate;
75
+ try {
76
+ candidate = JSON.parse(new TextDecoder().decode(base64UrlDecode(value)));
77
+ }
78
+ catch {
79
+ return null;
80
+ }
81
+ if (!isAuthFlowState(candidate)) {
82
+ return null;
83
+ }
84
+ return {
85
+ state: candidate.state,
86
+ codeVerifier: candidate.codeVerifier,
87
+ redirectUri: candidate.redirectUri,
88
+ returnTo: safeReturnTo(candidate.returnTo),
89
+ };
90
+ }
91
+ function isAuthFlowState(value) {
92
+ if (typeof value !== "object" || value === null) {
93
+ return false;
94
+ }
95
+ const record = value;
96
+ return (typeof record.state === "string" &&
97
+ typeof record.codeVerifier === "string" &&
98
+ typeof record.redirectUri === "string" &&
99
+ typeof record.returnTo === "string");
100
+ }
101
+ /** Reduces a return path to a same-origin relative path, falling back to `/`. */
102
+ export function safeReturnTo(value) {
103
+ if (typeof value !== "string" ||
104
+ !value.startsWith("/") ||
105
+ value.startsWith("//") ||
106
+ value.startsWith("/\\")) {
107
+ return "/";
108
+ }
109
+ if (/[\u0000-\u001f\u007f]/.test(value)) {
110
+ return "/";
111
+ }
112
+ const placeholderOrigin = "https://return-to.invalid";
113
+ let url;
114
+ try {
115
+ url = new URL(value, placeholderOrigin);
116
+ }
117
+ catch {
118
+ return "/";
119
+ }
120
+ if (url.origin !== placeholderOrigin) {
121
+ return "/";
122
+ }
123
+ return `${url.pathname}${url.search}${url.hash}`;
124
+ }
125
+ /**
126
+ * Replaces the named cookies in a raw `Cookie` request header while preserving every
127
+ * other cookie byte for byte.
128
+ */
129
+ export function replaceRequestCookies(cookieHeader, replacements) {
130
+ const replacedNames = new Set(Object.keys(replacements));
131
+ const preserved = (cookieHeader ?? "")
132
+ .split(";")
133
+ .map((pair) => pair.trim())
134
+ .filter((pair) => pair !== "")
135
+ .filter((pair) => !replacedNames.has(cookiePairName(pair)));
136
+ const replaced = Object.entries(replacements).map(([name, value]) => `${name}=${value}`);
137
+ return [...preserved, ...replaced].join("; ");
138
+ }
139
+ function cookiePairName(pair) {
140
+ const separator = pair.indexOf("=");
141
+ return (separator === -1 ? pair : pair.slice(0, separator)).trim();
142
+ }
@@ -0,0 +1,8 @@
1
+ import type { NextRequest } from "next/server";
2
+ import type { AppContext } from "./context.js";
3
+ export type RouteHandler = (request: NextRequest) => Promise<Response>;
4
+ export interface SegmentStreamRouteHandlers {
5
+ readonly GET: RouteHandler;
6
+ readonly POST: RouteHandler;
7
+ }
8
+ export declare function createHandlers(context: AppContext): SegmentStreamRouteHandlers;