@happyvertical/smrt-capacitor-session 0.62.14 → 0.64.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/AGENTS.md CHANGED
@@ -18,7 +18,12 @@ native-bearer stack, which has no WebView.
18
18
  `checkCookies()` when a fetch, XHR or beacon completes, so a fetch-set sign-in cookie is
19
19
  flushed within one bridge hop instead of up to `POLL_MS` later (#5160).
20
20
  - `.../CookieFlushPolicy.java`: the pure change detector, tested without Android.
21
- - `test/CookieFlushPolicyTest.java`: plain-Java test run by `pnpm test` (needs a JDK;
21
+ - `.../AppLinkPolicy.java`: the pure allow check for opt-in VIEW link routing
22
+ (`plugins.SmrtSession.links`, #5361). Only a `server.url`-origin http(s) link whose path is
23
+ listed is loaded into the WebView (`handleOnNewIntent`); `test/AppLinkPolicyTest.java` covers it.
24
+ - `.../SpentLinks.java`: SHA-256 digests of links whose page loaded, so a one-time link opens once
25
+ even when Android rebuilds a killed activity from its original intent; `test/SpentLinksTest.java`.
26
+ - `test/CookieFlushPolicyTest.java`, `test/AppLinkPolicyTest.java`: plain-Java tests run by `pnpm test` (needs a JDK;
22
27
  skipped locally without one, a failure under `CI`). `pnpm test` also runs the watch
23
28
  script against fakes in a Node vm.
24
29
  - `scripts/validate-plugin.mjs`: structural validation, also the `build` and `typecheck` step.
@@ -31,4 +36,9 @@ native-bearer stack, which has no WebView.
31
36
  most `POLL_MS` after any other cookie change. Cookies of other origins
32
37
  are flushed on pause/stop, not polled.
33
38
  - No credential, token or cookie value is read, stored or logged; the snapshot string stays in memory.
39
+ The only thing stored is the SHA-256 of an already-opened (spent) link, in private preferences.
40
+ - Link routing is off unless the shell lists path prefixes. The activity is exported, so the
41
+ allow check is the security boundary: same origin as `server.url`, listed path only, no
42
+ traversal. A link opens once (its digest is remembered when its page loads), and a launch
43
+ from Recents is ignored.
34
44
  - The Gradle compile happens in the consuming app (`cap sync`, assemble), against its Capacitor.
package/README.md CHANGED
@@ -39,3 +39,36 @@ plugins: { SmrtSession: { origins: ['https://hearthed.org'] } }
39
39
 
40
40
  A shell that serves the app from `https://localhost` and signs in against a remote origin must set
41
41
  `server.url` or list that origin. Cookies of any other origin are flushed on pause, stop and destroy only.
42
+
43
+ ## Emailed sign-in links (opt-in)
44
+
45
+ A one-time sign-in link sent by email (for example `/sign-in/email/complete#proof=…`) has to
46
+ finish in the app's own WebView. If it finishes in a browser, the browser gets the session and
47
+ the app stays signed out. Capacitor does not load an incoming link into the WebView, so the
48
+ plugin does it for the paths a shell lists (#5361):
49
+
50
+ ```js
51
+ // capacitor.config.js
52
+ plugins: { SmrtSession: { links: ['/sign-in/email/complete'] } }
53
+ ```
54
+
55
+ A VIEW intent that reaches the activity, on launch or while running, is loaded into the WebView
56
+ only when all of these hold:
57
+
58
+ - the link is http(s) with no user info;
59
+ - its origin equals the origin of `server.url` (host case and default port ignored);
60
+ - its path is a listed prefix or lies under one at a segment boundary, with no `.`/`..`
61
+ segments or encoded slashes or dots.
62
+
63
+ Query and fragment are kept. Anything else is ignored.
64
+
65
+ Each link opens once. When its page has loaded, the plugin remembers the link's SHA-256 (never
66
+ the link itself, at most 16, in the app's private preferences) and never loads that link again.
67
+ That covers Android rebuilding an activity killed in the background from the intent that first
68
+ started it, which Capacitor hands to plugins again. A link that failed to load, for example
69
+ offline, can be tapped again. A launch replayed from Recents is ignored too. Without `links`,
70
+ nothing changes.
71
+
72
+ The plugin only routes the link. The shell still declares the Android App Link: an
73
+ `autoVerify` intent filter for those paths in its `AndroidManifest.xml`, and
74
+ `/.well-known/assetlinks.json` served by the web app for its signing certificate.
@@ -0,0 +1,105 @@
1
+ package com.happyvertical.smrt.capacitor.session;
2
+
3
+ import java.net.URI;
4
+ import java.util.Locale;
5
+
6
+ /**
7
+ * Decides whether an incoming VIEW link may be loaded into the WebView (#5361).
8
+ * Pure Java so it is tested without Android.
9
+ *
10
+ * A link is accepted only when the host opted in with path prefixes
11
+ * ({@code plugins.SmrtSession.links}), the link is http(s) with no user info,
12
+ * its origin equals the origin of Capacitor's {@code server.url}, and its
13
+ * normalized path is a listed prefix or lies under one at a segment boundary.
14
+ * The activity is exported, so anything else (another origin, another path,
15
+ * a traversal) is refused rather than steering the WebView.
16
+ */
17
+ final class AppLinkPolicy {
18
+
19
+ private AppLinkPolicy() {}
20
+
21
+ /** Lower-cased scheme://host[:port] with the default port dropped, or null. */
22
+ static String origin(URI uri) {
23
+ if (uri == null || uri.getScheme() == null || uri.getHost() == null) {
24
+ return null;
25
+ }
26
+ String scheme = uri.getScheme().toLowerCase(Locale.ROOT);
27
+ if (!scheme.equals("https") && !scheme.equals("http")) {
28
+ return null;
29
+ }
30
+ int port = uri.getPort();
31
+ boolean defaultPort = port == -1 || (scheme.equals("https") && port == 443) || (scheme.equals("http") && port == 80);
32
+ return scheme + "://" + uri.getHost().toLowerCase(Locale.ROOT) + (defaultPort ? "" : ":" + port);
33
+ }
34
+
35
+ private static URI parse(String url) {
36
+ if (url == null) {
37
+ return null;
38
+ }
39
+ try {
40
+ return URI.create(url.trim());
41
+ } catch (IllegalArgumentException e) {
42
+ return null;
43
+ }
44
+ }
45
+
46
+ /** A listed prefix in canonical form ("/a/b", no trailing slash), or null when unusable. */
47
+ static String prefix(String raw) {
48
+ if (raw == null) {
49
+ return null;
50
+ }
51
+ String p = raw.trim();
52
+ if (!p.startsWith("/") || p.contains("?") || p.contains("#")) {
53
+ return null;
54
+ }
55
+ while (p.length() > 1 && p.endsWith("/")) {
56
+ p = p.substring(0, p.length() - 1);
57
+ }
58
+ return p;
59
+ }
60
+
61
+ /**
62
+ * The link to load, unchanged (query and fragment kept), or null when it is
63
+ * not allowed. {@code prefixes} null or empty means the host did not opt in.
64
+ */
65
+ static String accept(String link, String serverUrl, Iterable<String> prefixes) {
66
+ if (prefixes == null) {
67
+ return null;
68
+ }
69
+ URI uri = parse(link);
70
+ URI server = parse(serverUrl);
71
+ String linkOrigin = origin(uri);
72
+ if (linkOrigin == null || uri.getRawUserInfo() != null || !linkOrigin.equals(origin(server))) {
73
+ return null;
74
+ }
75
+ String rawPath = uri.getRawPath();
76
+ if (rawPath == null || rawPath.isEmpty()) {
77
+ rawPath = "/";
78
+ }
79
+ // An encoded slash or dot could hide a traversal from the segment check.
80
+ String lower = rawPath.toLowerCase(Locale.ROOT);
81
+ if (lower.contains("%2f") || lower.contains("%5c") || lower.contains("%2e") || rawPath.contains("\\")) {
82
+ return null;
83
+ }
84
+ // Any "." or ".." segment is refused outright, not resolved.
85
+ String path = rawPath;
86
+ String normalized = uri.normalize().getRawPath();
87
+ if (normalized == null || normalized.isEmpty()) {
88
+ normalized = "/";
89
+ }
90
+ if (!path.equals(normalized) || path.contains("/../") || path.endsWith("/..")
91
+ || path.contains("/./") || path.endsWith("/.")) {
92
+ return null;
93
+ }
94
+ for (String raw : prefixes) {
95
+ String p = prefix(raw);
96
+ if (p == null) {
97
+ continue;
98
+ }
99
+ if (p.equals("/") || path.equals(p) || path.startsWith(p + "/")) {
100
+ return link.trim();
101
+ }
102
+ }
103
+ return null;
104
+ }
105
+ }
@@ -1,5 +1,8 @@
1
1
  package com.happyvertical.smrt.capacitor.session;
2
2
 
3
+ import android.content.Context;
4
+ import android.content.Intent;
5
+ import android.content.SharedPreferences;
3
6
  import android.os.Handler;
4
7
  import android.os.Looper;
5
8
  import android.webkit.CookieManager;
@@ -9,6 +12,7 @@ import java.io.IOException;
9
12
  import java.io.InputStream;
10
13
  import java.nio.charset.StandardCharsets;
11
14
  import java.util.ArrayList;
15
+ import java.util.Arrays;
12
16
  import java.util.List;
13
17
  import java.util.Set;
14
18
  import com.getcapacitor.Logger;
@@ -42,6 +46,16 @@ import com.getcapacitor.annotation.CapacitorPlugin;
42
46
  * bridge hop of its response. It registers itself when the app runs `cap sync`;
43
47
  * the web app needs no call. `flush()` is exposed for a page that wants a
44
48
  * deterministic flush right after it sets a cookie.
49
+ *
50
+ * <p>Opt-in link routing (#5361): when {@code plugins.SmrtSession.links} lists
51
+ * path prefixes, a VIEW link that reaches the activity (an Android App Link the
52
+ * host declares, such as an emailed sign-in link) is loaded into this WebView
53
+ * when its origin is {@code server.url}'s and its path is listed, so the sign-in
54
+ * completes in the app's own cookie jar instead of a browser. See
55
+ * {@link AppLinkPolicy}. A link is opened once: when its page has loaded, its
56
+ * SHA-256 is remembered ({@link SpentLinks}) and the same link is never loaded
57
+ * again, including when Android rebuilds a killed activity from the intent that
58
+ * first started it. A launch replayed from Recents is ignored as well.
45
59
  */
46
60
  @CapacitorPlugin(name = "SmrtSession")
47
61
  public class SmrtSessionPlugin extends Plugin {
@@ -52,11 +66,21 @@ public class SmrtSessionPlugin extends Plugin {
52
66
  private final CookieFlushPolicy policy = new CookieFlushPolicy();
53
67
  private boolean polling = false;
54
68
  private String watchScript;
69
+ /** Link loaded but not yet seen to load: its digest and the page it opens. */
70
+ private String pendingDigest;
71
+ private String pendingPage;
72
+
73
+ static final String LINKS_PREFS = "smrt_session_links";
74
+ static final String SPENT_KEY = "spent";
55
75
 
56
76
  /** Checks the jar and installs the fetch-completion observer on every page load. */
57
77
  private final WebViewListener pageListener = new WebViewListener() {
58
78
  @Override
59
79
  public void onPageLoaded(WebView webView) {
80
+ String url = webView.getUrl();
81
+ if (pendingDigest != null && url != null && SpentLinks.page(url).equals(pendingPage)) {
82
+ markSpent(pendingDigest);
83
+ }
60
84
  flushIfChanged();
61
85
  if (watchScript != null) {
62
86
  webView.evaluateJavascript(watchScript, null);
@@ -84,6 +108,59 @@ public class SmrtSessionPlugin extends Plugin {
84
108
  startPolling();
85
109
  }
86
110
 
111
+ @Override
112
+ protected void handleOnNewIntent(Intent intent) {
113
+ // BridgeActivity also passes the launch intent here once the bridge exists.
114
+ if (intent == null || !Intent.ACTION_VIEW.equals(intent.getAction())
115
+ || (intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0
116
+ || intent.getData() == null || getBridge() == null) {
117
+ return;
118
+ }
119
+ String[] links = getConfig().getArray("links");
120
+ String serverUrl = getBridge().getConfig() == null ? null : getBridge().getConfig().getServerUrl();
121
+ String url = AppLinkPolicy.accept(
122
+ intent.getData().toString(), serverUrl, links == null ? null : Arrays.asList(links));
123
+ if (url == null) {
124
+ return;
125
+ }
126
+ // Clear the in-process copy; the system keeps the original, hence SpentLinks.
127
+ intent.setData(null);
128
+ String digest = SpentLinks.digest(url);
129
+ if (SpentLinks.seen(spentLinks(), digest)) {
130
+ return;
131
+ }
132
+ WebView webView = getBridge().getWebView();
133
+ if (webView == null) {
134
+ return;
135
+ }
136
+ String current = webView.getUrl();
137
+ if (current != null && SpentLinks.page(current).equals(SpentLinks.page(url))) {
138
+ // Same page: only the fragment changes and no page load follows.
139
+ markSpent(digest);
140
+ } else {
141
+ pendingDigest = digest;
142
+ pendingPage = SpentLinks.page(url);
143
+ }
144
+ webView.post(() -> webView.loadUrl(url));
145
+ }
146
+
147
+ private SharedPreferences linkPrefs() {
148
+ return getContext().getSharedPreferences(LINKS_PREFS, Context.MODE_PRIVATE);
149
+ }
150
+
151
+ private String spentLinks() {
152
+ return linkPrefs().getString(SPENT_KEY, "");
153
+ }
154
+
155
+ private void markSpent(String digest) {
156
+ // commit(), not apply(): the process may be killed right after the page loads.
157
+ linkPrefs().edit().putString(SPENT_KEY, SpentLinks.remember(spentLinks(), digest)).commit();
158
+ if (digest.equals(pendingDigest)) {
159
+ pendingDigest = null;
160
+ pendingPage = null;
161
+ }
162
+ }
163
+
87
164
  @Override
88
165
  protected void handleOnResume() {
89
166
  attachPageListener();
@@ -0,0 +1,77 @@
1
+ package com.happyvertical.smrt.capacitor.session;
2
+
3
+ import java.nio.charset.StandardCharsets;
4
+ import java.security.MessageDigest;
5
+ import java.security.NoSuchAlgorithmException;
6
+ import java.util.ArrayList;
7
+ import java.util.Arrays;
8
+ import java.util.List;
9
+
10
+ /**
11
+ * Remembers links already opened in the WebView, as SHA-256 digests, so a
12
+ * one-time link is never opened twice (#5361). Android rebuilds an activity
13
+ * killed in the background from the intent that first started it, and
14
+ * Capacitor passes that intent to plugins again; clearing its data only
15
+ * changes the in-process copy. Only digests are kept (never the link or its
16
+ * proof), newest last, at most {@link #MAX}. Pure Java so it is tested without
17
+ * Android; the plugin stores {@link #remember}'s result in its preferences.
18
+ */
19
+ final class SpentLinks {
20
+
21
+ static final int MAX = 16;
22
+
23
+ private SpentLinks() {}
24
+
25
+ /** Lower-case hex SHA-256 of the link as delivered. */
26
+ static String digest(String link) {
27
+ try {
28
+ byte[] hash = MessageDigest.getInstance("SHA-256").digest(link.getBytes(StandardCharsets.UTF_8));
29
+ StringBuilder sb = new StringBuilder(hash.length * 2);
30
+ for (byte b : hash) {
31
+ sb.append(Character.forDigit((b >> 4) & 0xF, 16)).append(Character.forDigit(b & 0xF, 16));
32
+ }
33
+ return sb.toString();
34
+ } catch (NoSuchAlgorithmException e) {
35
+ throw new IllegalStateException(e);
36
+ }
37
+ }
38
+
39
+ private static List<String> parse(String stored) {
40
+ List<String> out = new ArrayList<>();
41
+ if (stored == null || stored.isEmpty()) {
42
+ return out;
43
+ }
44
+ for (String s : Arrays.asList(stored.split(","))) {
45
+ if (s.matches("[0-9a-f]{64}")) {
46
+ out.add(s);
47
+ }
48
+ }
49
+ return out;
50
+ }
51
+
52
+ /** True when {@code digest} was remembered in {@code stored}. */
53
+ static boolean seen(String stored, String digest) {
54
+ return digest != null && parse(stored).contains(digest);
55
+ }
56
+
57
+ /** {@code stored} with {@code digest} added as newest, oldest dropped past {@link #MAX}. */
58
+ static String remember(String stored, String digest) {
59
+ List<String> list = parse(stored);
60
+ list.remove(digest);
61
+ list.add(digest);
62
+ while (list.size() > MAX) {
63
+ list.remove(0);
64
+ }
65
+ return String.join(",", list);
66
+ }
67
+
68
+ /** The link without query or fragment: the page that loading it shows. */
69
+ static String page(String link) {
70
+ int cut = link.length();
71
+ int q = link.indexOf('?');
72
+ int h = link.indexOf('#');
73
+ if (q >= 0) cut = Math.min(cut, q);
74
+ if (h >= 0) cut = Math.min(cut, h);
75
+ return link.substring(0, cut);
76
+ }
77
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@happyvertical/smrt-capacitor-session",
3
- "version": "0.62.14",
3
+ "version": "0.64.0",
4
4
  "description": "Capacitor Android plugin that keeps a WebView cookie session durable: flushes the WebView CookieManager to disk when the cookie jar changes and on pause, stop and destroy",
5
5
  "author": "HappyVertical",
6
6
  "license": "MIT",