@aglyn/shared-util-next 1.0.0-beta.143

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/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # shared-util-next
2
+
3
+ This library was generated with [Nx](https://nx.dev).
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@aglyn/shared-util-next",
3
+ "version": "1.0.0-beta.143",
4
+ "license": "Apache-2.0",
5
+ "homepage": "https://aglyn.com",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/aglyn/aglyn.git",
9
+ "directory": "libs/shared/util/next"
10
+ },
11
+ "publishConfig": {
12
+ "access": "public",
13
+ "provenance": true
14
+ },
15
+ "exports": {
16
+ ".": {
17
+ "types": "./src/index.d.ts",
18
+ "default": "./src/index.js"
19
+ },
20
+ "./*": {
21
+ "types": "./src/lib/*.d.ts",
22
+ "default": "./src/lib/*.js"
23
+ },
24
+ "./package.json": "./package.json"
25
+ },
26
+ "dependencies": {
27
+ "@aglyn/shared-util-http": "1.0.0-beta.143",
28
+ "@swc/helpers": "0.5.23"
29
+ },
30
+ "peerDependencies": {
31
+ "next": "16.3.3",
32
+ "react": "^19.2.8"
33
+ },
34
+ "sideEffects": false,
35
+ "types": "./src/index.d.ts",
36
+ "module": "./src/index.js",
37
+ "type": "module",
38
+ "main": "./src/index.js"
39
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2022 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ export * from './lib/use-continue-url';
package/src/index.js ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2022 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ export * from "./lib/use-continue-url.js";
17
+
18
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../libs/shared/util/next/src/index.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2022 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './lib/use-continue-url'\n"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,cAAc,4BAAwB"}
@@ -0,0 +1,72 @@
1
+ export type UseContinueUrlDecodedRoutePusher = (url?: string, as?: string, options?: {
2
+ shallow?: boolean;
3
+ locale?: string | false;
4
+ scroll?: boolean;
5
+ }) => void;
6
+ export type UseContinueUrlDecodedResponse = [
7
+ decoded: string,
8
+ pushNext: UseContinueUrlDecodedRoutePusher
9
+ ];
10
+ export type UseContinueUrlResponse = [
11
+ encoded: string,
12
+ decoded: string,
13
+ pushNext: UseContinueUrlDecodedRoutePusher
14
+ ];
15
+ export declare const ContinueParamName = "continue";
16
+ export declare const continueParam: (value: string) => string;
17
+ /**
18
+ * Only same-app relative paths, or same-site absolute URLs within the
19
+ * workspace domain (AGL-465), may be continued to — anything else absolute
20
+ * or protocol-relative would make the post-auth redirect an open redirect.
21
+ *
22
+ * The relative branch defers to {@link isSameOriginPath} rather than testing
23
+ * the string's shape (AGL-1881). AGL-2486 rejected `\` here because the
24
+ * WHATWG URL parser treats it as `/` in the authority position, so
25
+ * `/\evil.com` passed a `startsWith('/') && !startsWith('//')` test and still
26
+ * resolved off-site. That was true but incomplete: the same parser also
27
+ * DELETES every tab, LF and CR before parsing, so `/<TAB>/evil.com` resolves
28
+ * to `https://evil.com/` while containing neither `//` nor `\`. Enumerating
29
+ * the tricks was the mistake; the shared predicate resolves the value and
30
+ * compares origins, which is the question `window.location.assign` will
31
+ * actually ask.
32
+ *
33
+ * The absolute branch below never had that bug and keeps its own check: once
34
+ * the input is absolute the parser's `hostname` is already ground truth.
35
+ *
36
+ * A `continue` that has survived an external IdP round trip is the case that
37
+ * makes this matter: whatever we put into `state` comes back as untrusted
38
+ * input.
39
+ *
40
+ * `''` is rejected explicitly rather than by accident. `strictNullChecks` is
41
+ * off repo-wide, so an absent param arrives here as an empty string far more
42
+ * often than as `undefined`, and "no continue" must read as unsafe so the
43
+ * caller falls back to its own default instead of building `?continue=`.
44
+ */
45
+ export declare const isSafeContinueUrl: (url: string) => boolean;
46
+ /**
47
+ * Forward the continue URL onto another same-app path (AGL-2486).
48
+ *
49
+ * A signed-out user who deep-links in arrives at `/signin?continue=…`, and
50
+ * every link OUT of that page to another auth route — the SSO button above
51
+ * all — has to carry the value or the destination they were going to is
52
+ * gone. Observed on the SSO button: the url does not carry the
53
+ * continue url and is dropped entirely.
54
+ *
55
+ * Unsafe or absent values append nothing, so a poisoned `continue` degrades
56
+ * to a plain link rather than being laundered one hop further along.
57
+ */
58
+ export declare function withContinueUrl(path: string, continueUrl: string): string;
59
+ /**
60
+ * `href` for a link out of the current page that keeps the continue URL.
61
+ *
62
+ * Deliberately reads `useSearchParams` directly instead of reusing
63
+ * {@link useContinueUrlDecoded}: that hook also calls `useRouter`, and a
64
+ * link does not navigate imperatively. Pulling the router in would make
65
+ * every page that renders one of these links require an App Router context
66
+ * it does not otherwise need.
67
+ */
68
+ export declare function useContinueHref(path: string): string;
69
+ export declare function useContinueUrlDecoded(): UseContinueUrlDecodedResponse;
70
+ export declare function useContinueUrlEncoded(): string;
71
+ export declare function useContinueUrl(): UseContinueUrlResponse;
72
+ export default useContinueUrl;
@@ -0,0 +1,165 @@
1
+ var _process_env_NEXT_PUBLIC_WORKSPACE_DOMAIN;
2
+ /**
3
+ * @license
4
+ * Copyright 2024 Aglyn LLC
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */ 'use client';
18
+ import { isSameOriginPath } from "@aglyn/shared-util-http/safe-redirect";
19
+ import { usePathname, useRouter, useSearchParams } from "next/navigation";
20
+ import { useCallback, useMemo } from "react";
21
+ export const ContinueParamName = 'continue';
22
+ export const continueParam = (value)=>`${ContinueParamName}=${value}`;
23
+ const WORKSPACE_DOMAIN = (_process_env_NEXT_PUBLIC_WORKSPACE_DOMAIN = process.env.NEXT_PUBLIC_WORKSPACE_DOMAIN) != null ? _process_env_NEXT_PUBLIC_WORKSPACE_DOMAIN : 'aglyn.com';
24
+ /**
25
+ * Same-site absolute returns (AGL-465): the auth host signs a user in and
26
+ * must redirect back to the {org}.<workspaceDomain> subdomain they started
27
+ * from, which is a cross-origin URL. Allow it only when the host is within
28
+ * the workspace domain over https, so this stays first-party and never
29
+ * becomes an open redirect.
30
+ */ const isSameSiteAbsoluteUrl = (url)=>{
31
+ try {
32
+ const { protocol, hostname } = new URL(url);
33
+ if (protocol !== 'https:') return false;
34
+ return hostname === WORKSPACE_DOMAIN || hostname.endsWith(`.${WORKSPACE_DOMAIN}`);
35
+ } catch (unused) {
36
+ return false;
37
+ }
38
+ };
39
+ /**
40
+ * Only same-app relative paths, or same-site absolute URLs within the
41
+ * workspace domain (AGL-465), may be continued to — anything else absolute
42
+ * or protocol-relative would make the post-auth redirect an open redirect.
43
+ *
44
+ * The relative branch defers to {@link isSameOriginPath} rather than testing
45
+ * the string's shape (AGL-1881). AGL-2486 rejected `\` here because the
46
+ * WHATWG URL parser treats it as `/` in the authority position, so
47
+ * `/\evil.com` passed a `startsWith('/') && !startsWith('//')` test and still
48
+ * resolved off-site. That was true but incomplete: the same parser also
49
+ * DELETES every tab, LF and CR before parsing, so `/<TAB>/evil.com` resolves
50
+ * to `https://evil.com/` while containing neither `//` nor `\`. Enumerating
51
+ * the tricks was the mistake; the shared predicate resolves the value and
52
+ * compares origins, which is the question `window.location.assign` will
53
+ * actually ask.
54
+ *
55
+ * The absolute branch below never had that bug and keeps its own check: once
56
+ * the input is absolute the parser's `hostname` is already ground truth.
57
+ *
58
+ * A `continue` that has survived an external IdP round trip is the case that
59
+ * makes this matter: whatever we put into `state` comes back as untrusted
60
+ * input.
61
+ *
62
+ * `''` is rejected explicitly rather than by accident. `strictNullChecks` is
63
+ * off repo-wide, so an absent param arrives here as an empty string far more
64
+ * often than as `undefined`, and "no continue" must read as unsafe so the
65
+ * caller falls back to its own default instead of building `?continue=`.
66
+ */ export const isSafeContinueUrl = (url)=>{
67
+ if (!url) return false;
68
+ return isSameOriginPath(url) || isSameSiteAbsoluteUrl(url);
69
+ };
70
+ /**
71
+ * Forward the continue URL onto another same-app path (AGL-2486).
72
+ *
73
+ * A signed-out user who deep-links in arrives at `/signin?continue=…`, and
74
+ * every link OUT of that page to another auth route — the SSO button above
75
+ * all — has to carry the value or the destination they were going to is
76
+ * gone. Observed on the SSO button: the url does not carry the
77
+ * continue url and is dropped entirely.
78
+ *
79
+ * Unsafe or absent values append nothing, so a poisoned `continue` degrades
80
+ * to a plain link rather than being laundered one hop further along.
81
+ */ export function withContinueUrl(path, continueUrl) {
82
+ if (!isSafeContinueUrl(continueUrl)) return path;
83
+ const separator = path.includes('?') ? '&' : '?';
84
+ return `${path}${separator}${continueParam(encodeURIComponent(continueUrl))}`;
85
+ }
86
+ /**
87
+ * `href` for a link out of the current page that keeps the continue URL.
88
+ *
89
+ * Deliberately reads `useSearchParams` directly instead of reusing
90
+ * {@link useContinueUrlDecoded}: that hook also calls `useRouter`, and a
91
+ * link does not navigate imperatively. Pulling the router in would make
92
+ * every page that renders one of these links require an App Router context
93
+ * it does not otherwise need.
94
+ */ export function useContinueHref(path) {
95
+ var _ref;
96
+ const searchParams = useSearchParams();
97
+ const raw = (_ref = searchParams == null ? void 0 : searchParams.get(ContinueParamName)) != null ? _ref : '';
98
+ return useMemo(()=>withContinueUrl(path, raw), [
99
+ path,
100
+ raw
101
+ ]);
102
+ }
103
+ export function useContinueUrlDecoded() {
104
+ const router = useRouter();
105
+ // App Router: query strings live in useSearchParams — useParams only
106
+ // carries dynamic route segments, which is why the continue redirect
107
+ // silently broke after the pages→app migration (AGL-458). `get` already
108
+ // percent-decodes, so no second decode (it would corrupt paths that
109
+ // legitimately contain %-sequences).
110
+ const searchParams = useSearchParams();
111
+ const continueUrl = useMemo(()=>{
112
+ var _ref;
113
+ const url = (_ref = searchParams == null ? void 0 : searchParams.get(ContinueParamName)) != null ? _ref : '';
114
+ return isSafeContinueUrl(url) ? url : '';
115
+ }, [
116
+ searchParams
117
+ ]);
118
+ const pushNext = useCallback((url = '/', as = undefined, options)=>{
119
+ const target = continueUrl || url;
120
+ // A same-site absolute return (AGL-465) is cross-origin — the App
121
+ // Router's client navigation can't cross origins, so hand it to the
122
+ // browser. Relative paths keep the SPA transition.
123
+ if (/^https?:\/\//.test(target)) {
124
+ if (typeof window !== 'undefined') window.location.assign(target);
125
+ return;
126
+ }
127
+ return router.push(target, options);
128
+ }, [
129
+ router,
130
+ continueUrl
131
+ ]);
132
+ return useMemo(()=>{
133
+ return [
134
+ continueUrl,
135
+ pushNext
136
+ ];
137
+ }, [
138
+ continueUrl,
139
+ pushNext
140
+ ]);
141
+ }
142
+ export function useContinueUrlEncoded() {
143
+ const pathname = usePathname();
144
+ return useMemo(()=>{
145
+ return encodeURIComponent(pathname || '');
146
+ }, [
147
+ pathname
148
+ ]);
149
+ }
150
+ export function useContinueUrl() {
151
+ const encoded = useContinueUrlEncoded();
152
+ const [decoded, pushNext] = useContinueUrlDecoded();
153
+ return useMemo(()=>[
154
+ encoded,
155
+ decoded,
156
+ pushNext
157
+ ], [
158
+ encoded,
159
+ decoded,
160
+ pushNext
161
+ ]);
162
+ }
163
+ export default useContinueUrl;
164
+
165
+ //# sourceMappingURL=use-continue-url.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/shared/util/next/src/lib/use-continue-url.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2024 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { isSameOriginPath } from '@aglyn/shared-util-http/safe-redirect'\nimport { usePathname, useRouter, useSearchParams } from 'next/navigation'\nimport { useCallback, useMemo } from 'react'\n\nexport type UseContinueUrlDecodedRoutePusher = (\n url?: string,\n as?: string,\n options?: { shallow?: boolean; locale?: string | false; scroll?: boolean },\n) => void\n\nexport type UseContinueUrlDecodedResponse = [\n decoded: string,\n pushNext: UseContinueUrlDecodedRoutePusher,\n]\n\nexport type UseContinueUrlResponse = [\n encoded: string,\n decoded: string,\n pushNext: UseContinueUrlDecodedRoutePusher,\n]\n\nexport const ContinueParamName = 'continue'\nexport const continueParam = (value: string) => `${ContinueParamName}=${value}`\n\nconst WORKSPACE_DOMAIN =\n process.env.NEXT_PUBLIC_WORKSPACE_DOMAIN ?? 'aglyn.com'\n\n/**\n * Same-site absolute returns (AGL-465): the auth host signs a user in and\n * must redirect back to the {org}.<workspaceDomain> subdomain they started\n * from, which is a cross-origin URL. Allow it only when the host is within\n * the workspace domain over https, so this stays first-party and never\n * becomes an open redirect.\n */\nconst isSameSiteAbsoluteUrl = (url: string): boolean => {\n try {\n const { protocol, hostname } = new URL(url)\n if (protocol !== 'https:') return false\n return (\n hostname === WORKSPACE_DOMAIN ||\n hostname.endsWith(`.${WORKSPACE_DOMAIN}`)\n )\n } catch {\n return false\n }\n}\n\n/**\n * Only same-app relative paths, or same-site absolute URLs within the\n * workspace domain (AGL-465), may be continued to — anything else absolute\n * or protocol-relative would make the post-auth redirect an open redirect.\n *\n * The relative branch defers to {@link isSameOriginPath} rather than testing\n * the string's shape (AGL-1881). AGL-2486 rejected `\\` here because the\n * WHATWG URL parser treats it as `/` in the authority position, so\n * `/\\evil.com` passed a `startsWith('/') && !startsWith('//')` test and still\n * resolved off-site. That was true but incomplete: the same parser also\n * DELETES every tab, LF and CR before parsing, so `/<TAB>/evil.com` resolves\n * to `https://evil.com/` while containing neither `//` nor `\\`. Enumerating\n * the tricks was the mistake; the shared predicate resolves the value and\n * compares origins, which is the question `window.location.assign` will\n * actually ask.\n *\n * The absolute branch below never had that bug and keeps its own check: once\n * the input is absolute the parser's `hostname` is already ground truth.\n *\n * A `continue` that has survived an external IdP round trip is the case that\n * makes this matter: whatever we put into `state` comes back as untrusted\n * input.\n *\n * `''` is rejected explicitly rather than by accident. `strictNullChecks` is\n * off repo-wide, so an absent param arrives here as an empty string far more\n * often than as `undefined`, and \"no continue\" must read as unsafe so the\n * caller falls back to its own default instead of building `?continue=`.\n */\nexport const isSafeContinueUrl = (url: string): boolean => {\n if (!url) return false\n return isSameOriginPath(url) || isSameSiteAbsoluteUrl(url)\n}\n\n/**\n * Forward the continue URL onto another same-app path (AGL-2486).\n *\n * A signed-out user who deep-links in arrives at `/signin?continue=…`, and\n * every link OUT of that page to another auth route — the SSO button above\n * all — has to carry the value or the destination they were going to is\n * gone. Observed on the SSO button: the url does not carry the\n * continue url and is dropped entirely.\n *\n * Unsafe or absent values append nothing, so a poisoned `continue` degrades\n * to a plain link rather than being laundered one hop further along.\n */\nexport function withContinueUrl(path: string, continueUrl: string): string {\n if (!isSafeContinueUrl(continueUrl)) return path\n const separator = path.includes('?') ? '&' : '?'\n return `${path}${separator}${continueParam(encodeURIComponent(continueUrl))}`\n}\n\n/**\n * `href` for a link out of the current page that keeps the continue URL.\n *\n * Deliberately reads `useSearchParams` directly instead of reusing\n * {@link useContinueUrlDecoded}: that hook also calls `useRouter`, and a\n * link does not navigate imperatively. Pulling the router in would make\n * every page that renders one of these links require an App Router context\n * it does not otherwise need.\n */\nexport function useContinueHref(path: string): string {\n const searchParams = useSearchParams()\n const raw = searchParams?.get(ContinueParamName) ?? ''\n return useMemo(() => withContinueUrl(path, raw), [path, raw])\n}\n\nexport function useContinueUrlDecoded(): UseContinueUrlDecodedResponse {\n const router = useRouter()\n // App Router: query strings live in useSearchParams — useParams only\n // carries dynamic route segments, which is why the continue redirect\n // silently broke after the pages→app migration (AGL-458). `get` already\n // percent-decodes, so no second decode (it would corrupt paths that\n // legitimately contain %-sequences).\n const searchParams = useSearchParams()\n\n const continueUrl = useMemo(() => {\n const url = searchParams?.get(ContinueParamName) ?? ''\n return isSafeContinueUrl(url) ? url : ''\n }, [searchParams])\n\n const pushNext = useCallback(\n (\n url = '/',\n as: string | undefined = undefined,\n options?: {\n shallow?: boolean\n locale?: string | false\n scroll?: boolean\n },\n ): void => {\n const target = continueUrl || url\n // A same-site absolute return (AGL-465) is cross-origin — the App\n // Router's client navigation can't cross origins, so hand it to the\n // browser. Relative paths keep the SPA transition.\n if (/^https?:\\/\\//.test(target)) {\n if (typeof window !== 'undefined') window.location.assign(target)\n return\n }\n return router.push(target, options)\n },\n [router, continueUrl],\n )\n\n return useMemo(() => {\n return [continueUrl, pushNext]\n }, [continueUrl, pushNext])\n}\n\nexport function useContinueUrlEncoded() {\n const pathname = usePathname()\n\n return useMemo(() => {\n return encodeURIComponent(pathname || '')\n }, [pathname])\n}\n\nexport function useContinueUrl(): UseContinueUrlResponse {\n const encoded = useContinueUrlEncoded()\n const [decoded, pushNext] = useContinueUrlDecoded()\n\n return useMemo(\n () => [encoded, decoded, pushNext],\n [encoded, decoded, pushNext],\n )\n}\n\nexport default useContinueUrl\n"],"names":["process","isSameOriginPath","usePathname","useRouter","useSearchParams","useCallback","useMemo","ContinueParamName","continueParam","value","WORKSPACE_DOMAIN","env","NEXT_PUBLIC_WORKSPACE_DOMAIN","isSameSiteAbsoluteUrl","url","protocol","hostname","URL","endsWith","isSafeContinueUrl","withContinueUrl","path","continueUrl","separator","includes","encodeURIComponent","useContinueHref","searchParams","raw","get","useContinueUrlDecoded","router","pushNext","as","undefined","options","target","test","window","location","assign","push","useContinueUrlEncoded","pathname","useContinueUrl","encoded","decoded"],"mappings":"IA2CEA;AA3CF;;;;;;;;;;;;;;;CAeC,GACD;AAEA,SAASC,gBAAgB,QAAQ,wCAAuC;AACxE,SAASC,WAAW,EAAEC,SAAS,EAAEC,eAAe,QAAQ,kBAAiB;AACzE,SAASC,WAAW,EAAEC,OAAO,QAAQ,QAAO;AAmB5C,OAAO,MAAMC,oBAAoB,WAAU;AAC3C,OAAO,MAAMC,gBAAgB,CAACC,QAAkB,GAAGF,kBAAkB,CAAC,EAAEE,OAAO,CAAA;AAE/E,MAAMC,oBACJV,4C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