@pithy-sh/auth 0.11.0 → 0.12.1
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/README.md +30 -2
- package/dist/audit/actions.d.ts +39 -0
- package/dist/audit/actions.d.ts.map +1 -1
- package/dist/audit/actions.js +40 -1
- package/dist/audit/emit.d.ts +34 -0
- package/dist/audit/emit.d.ts.map +1 -1
- package/dist/audit/emit.js +47 -1
- package/dist/audit/evidence.d.ts +8 -2
- package/dist/audit/evidence.d.ts.map +1 -1
- package/dist/capability.d.ts +31 -11
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +38 -5
- package/dist/client/api.d.ts +55 -12
- package/dist/client/api.d.ts.map +1 -1
- package/dist/client/api.js +57 -18
- package/dist/client/bearer.d.ts +110 -0
- package/dist/client/bearer.d.ts.map +1 -0
- package/dist/client/bearer.js +265 -0
- package/dist/client/handoff.d.ts +77 -0
- package/dist/client/handoff.d.ts.map +1 -0
- package/dist/client/handoff.js +119 -0
- package/dist/client/mcp.d.ts +70 -0
- package/dist/client/mcp.d.ts.map +1 -0
- package/dist/client/mcp.js +65 -0
- package/dist/data/betterAuth.d.ts +3 -2
- package/dist/data/betterAuth.d.ts.map +1 -1
- package/dist/data/betterAuth.js +5 -3
- package/dist/data/kitFields.d.ts +5 -0
- package/dist/data/kitFields.d.ts.map +1 -1
- package/dist/data/kitFields.js +5 -0
- package/dist/data/tables.d.ts +25 -4
- package/dist/data/tables.d.ts.map +1 -1
- package/dist/data/tables.js +5 -3
- package/dist/data/userLifecycle.d.ts +9 -0
- package/dist/data/userLifecycle.d.ts.map +1 -1
- package/dist/data/userLifecycle.js +6 -2
- package/dist/data/verificationOutcome.d.ts +53 -0
- package/dist/data/verificationOutcome.d.ts.map +1 -0
- package/dist/data/verificationOutcome.js +50 -0
- package/dist/email/send.js +6 -2
- package/dist/http/adminRoutes.d.ts.map +1 -1
- package/dist/http/adminRoutes.js +56 -10
- package/dist/http/csrf.d.ts.map +1 -1
- package/dist/http/csrf.js +2 -1
- package/dist/http/guards.d.ts +15 -11
- package/dist/http/guards.d.ts.map +1 -1
- package/dist/http/guards.js +46 -11
- package/dist/http/handoff.d.ts +76 -0
- package/dist/http/handoff.d.ts.map +1 -0
- package/dist/http/handoff.js +316 -0
- package/dist/http/middleware.d.ts +12 -0
- package/dist/http/middleware.d.ts.map +1 -1
- package/dist/http/middleware.js +25 -4
- package/dist/http/resolve.d.ts.map +1 -1
- package/dist/http/resolve.js +9 -3
- package/dist/http/responses.d.ts +142 -0
- package/dist/http/responses.d.ts.map +1 -1
- package/dist/http/responses.js +66 -10
- package/dist/http/routes.d.ts +2 -0
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +35 -4
- package/dist/http/schemas.d.ts +57 -0
- package/dist/http/schemas.d.ts.map +1 -1
- package/dist/http/schemas.js +44 -1
- package/dist/http/views.d.ts +22 -2
- package/dist/http/views.d.ts.map +1 -1
- package/dist/http/views.js +40 -4
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -2
- package/dist/instance/auth.d.ts +148 -10
- package/dist/instance/auth.d.ts.map +1 -1
- package/dist/instance/auth.js +86 -41
- package/dist/instance/plugins.d.ts +6 -0
- package/dist/instance/plugins.d.ts.map +1 -1
- package/dist/instance/plugins.js +14 -1
- package/dist/ledger/read.d.ts +53 -0
- package/dist/ledger/read.d.ts.map +1 -0
- package/dist/ledger/read.js +85 -0
- package/dist/ledger/record.d.ts +35 -0
- package/dist/ledger/record.d.ts.map +1 -0
- package/dist/ledger/record.js +98 -0
- package/dist/lifecycle/erasure.d.ts +9 -0
- package/dist/lifecycle/erasure.d.ts.map +1 -0
- package/dist/lifecycle/erasure.js +96 -0
- package/dist/lifecycle/inactivity.d.ts +19 -0
- package/dist/lifecycle/inactivity.d.ts.map +1 -0
- package/dist/lifecycle/inactivity.js +28 -0
- package/dist/lifecycle/transitions.d.ts +22 -1
- package/dist/lifecycle/transitions.d.ts.map +1 -1
- package/dist/lifecycle/transitions.js +51 -4
- package/dist/mcp/argumentClass.d.ts +51 -0
- package/dist/mcp/argumentClass.d.ts.map +1 -0
- package/dist/mcp/argumentClass.js +69 -0
- package/dist/mcp/capability.d.ts +50 -0
- package/dist/mcp/capability.d.ts.map +1 -0
- package/dist/mcp/capability.js +140 -0
- package/dist/mcp/clientMetadata.d.ts +40 -0
- package/dist/mcp/clientMetadata.d.ts.map +1 -0
- package/dist/mcp/clientMetadata.js +68 -0
- package/dist/mcp/consent.d.ts +49 -0
- package/dist/mcp/consent.d.ts.map +1 -0
- package/dist/mcp/consent.js +69 -0
- package/dist/mcp/dispatch.d.ts +35 -0
- package/dist/mcp/dispatch.d.ts.map +1 -0
- package/dist/mcp/dispatch.js +135 -0
- package/dist/mcp/floor.d.ts +37 -0
- package/dist/mcp/floor.d.ts.map +1 -0
- package/dist/mcp/floor.js +41 -0
- package/dist/mcp/host.d.ts +34 -0
- package/dist/mcp/host.d.ts.map +1 -0
- package/dist/mcp/host.js +2 -0
- package/dist/mcp/http/redirectList.d.ts +9 -0
- package/dist/mcp/http/redirectList.d.ts.map +1 -0
- package/dist/mcp/http/redirectList.js +24 -0
- package/dist/mcp/http/responses.d.ts +143 -0
- package/dist/mcp/http/responses.d.ts.map +1 -0
- package/dist/mcp/http/responses.js +83 -0
- package/dist/mcp/http/routes.d.ts +28 -0
- package/dist/mcp/http/routes.d.ts.map +1 -0
- package/dist/mcp/http/routes.js +517 -0
- package/dist/mcp/http/schemas.d.ts +24 -0
- package/dist/mcp/http/schemas.d.ts.map +1 -0
- package/dist/mcp/http/schemas.js +18 -0
- package/dist/mcp/marker.d.ts +15 -0
- package/dist/mcp/marker.d.ts.map +1 -0
- package/dist/mcp/marker.js +15 -0
- package/dist/mcp/provider.d.ts +78 -0
- package/dist/mcp/provider.d.ts.map +1 -0
- package/dist/mcp/provider.js +108 -0
- package/dist/mcp/purge.d.ts +15 -0
- package/dist/mcp/purge.d.ts.map +1 -0
- package/dist/mcp/purge.js +31 -0
- package/dist/mcp/rpc.d.ts +79 -0
- package/dist/mcp/rpc.d.ts.map +1 -0
- package/dist/mcp/rpc.js +103 -0
- package/dist/mcp/toolAudit.d.ts +76 -0
- package/dist/mcp/toolAudit.d.ts.map +1 -0
- package/dist/mcp/toolAudit.js +86 -0
- package/dist/migrations/0006_verification_outcomes.d.ts +15 -0
- package/dist/migrations/0006_verification_outcomes.d.ts.map +1 -0
- package/dist/migrations/0006_verification_outcomes.js +35 -0
- package/dist/migrations/0007_erasure_record.d.ts +17 -0
- package/dist/migrations/0007_erasure_record.d.ts.map +1 -0
- package/dist/migrations/0007_erasure_record.js +36 -0
- package/dist/migrations/0008_last_active.d.ts +15 -0
- package/dist/migrations/0008_last_active.d.ts.map +1 -0
- package/dist/migrations/0008_last_active.js +29 -0
- package/dist/migrations/set.d.ts +4 -1
- package/dist/migrations/set.d.ts.map +1 -1
- package/dist/migrations/set.js +8 -2
- package/dist/peer.d.ts +3 -2
- package/dist/peer.d.ts.map +1 -1
- package/dist/processing/activities.d.ts +6 -0
- package/dist/processing/activities.d.ts.map +1 -0
- package/dist/processing/activities.js +12 -0
- package/dist/purge/contribution.d.ts +20 -5
- package/dist/purge/contribution.d.ts.map +1 -1
- package/dist/purge/contribution.js +20 -6
- package/dist/purge/run.d.ts +75 -5
- package/dist/purge/run.d.ts.map +1 -1
- package/dist/purge/run.js +117 -14
- package/dist/purge/workflow.d.ts +15 -2
- package/dist/purge/workflow.d.ts.map +1 -1
- package/dist/purge/workflow.js +51 -7
- package/dist/test-utils/accountFootprint.d.ts +5 -2
- package/dist/test-utils/accountFootprint.d.ts.map +1 -1
- package/dist/test-utils/accountFootprint.js +7 -2
- package/dist/test-utils/liveApp.d.ts +6 -0
- package/dist/test-utils/liveApp.d.ts.map +1 -1
- package/dist/test-utils/liveApp.js +7 -2
- package/dist/token/handoff.d.ts +80 -0
- package/dist/token/handoff.d.ts.map +1 -0
- package/dist/token/handoff.js +136 -0
- package/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.js +1 -1
- package/docs/account-lifecycle.md +59 -7
- package/docs/apple-signin.md +32 -4
- package/docs/facebook-oauth.md +2 -2
- package/docs/github-oauth.md +2 -2
- package/docs/google-oauth.md +9 -7
- package/docs/microsoft-oauth.md +2 -2
- package/package.json +11 -5
- package/pithy.manifest.json +2 -2
- package/pithy.mcp.manifest.json +36 -0
- package/src/audit/actions.ts +39 -0
- package/src/audit/emit.ts +63 -0
- package/src/audit/evidence.ts +8 -4
- package/src/capability.ts +80 -23
- package/src/client/api.ts +69 -19
- package/src/client/bearer.ts +388 -0
- package/src/client/handoff.ts +172 -0
- package/src/client/mcp.ts +140 -0
- package/src/data/betterAuth.ts +8 -4
- package/src/data/kitFields.ts +2 -0
- package/src/data/tables.ts +4 -2
- package/src/data/userLifecycle.ts +15 -3
- package/src/data/verificationOutcome.ts +86 -0
- package/src/email/send.ts +2 -2
- package/src/http/adminRoutes.ts +68 -3
- package/src/http/csrf.ts +4 -1
- package/src/http/guards.ts +48 -11
- package/src/http/handoff.ts +350 -0
- package/src/http/middleware.ts +29 -3
- package/src/http/resolve.ts +25 -25
- package/src/http/responses.ts +134 -8
- package/src/http/routes.ts +63 -4
- package/src/http/schemas.ts +85 -0
- package/src/http/views.ts +46 -2
- package/src/index.ts +2 -0
- package/src/instance/auth.ts +51 -1
- package/src/instance/plugins.ts +20 -2
- package/src/ledger/read.ts +133 -0
- package/src/ledger/record.ts +198 -0
- package/src/lifecycle/erasure.ts +118 -0
- package/src/lifecycle/inactivity.ts +56 -0
- package/src/lifecycle/transitions.ts +75 -5
- package/src/mcp/argumentClass.ts +112 -0
- package/src/mcp/capability.ts +194 -0
- package/src/mcp/clientMetadata.ts +81 -0
- package/src/mcp/consent.ts +95 -0
- package/src/mcp/dispatch.ts +154 -0
- package/src/mcp/floor.ts +62 -0
- package/src/mcp/host.ts +36 -0
- package/src/mcp/http/redirectList.ts +26 -0
- package/src/mcp/http/responses.ts +157 -0
- package/src/mcp/http/routes.ts +635 -0
- package/src/mcp/http/schemas.ts +37 -0
- package/src/mcp/marker.ts +18 -0
- package/src/mcp/provider.ts +151 -0
- package/src/mcp/purge.ts +39 -0
- package/src/mcp/rpc.ts +135 -0
- package/src/mcp/toolAudit.ts +132 -0
- package/src/migrations/0006_verification_outcomes.ts +51 -0
- package/src/migrations/0007_erasure_record.ts +43 -0
- package/src/migrations/0008_last_active.ts +30 -0
- package/src/migrations/set.ts +7 -1
- package/src/processing/activities.ts +14 -0
- package/src/purge/contribution.ts +37 -10
- package/src/purge/run.ts +179 -16
- package/src/purge/workflow.ts +65 -7
- package/src/seeds/example.ts +2 -2
- package/src/test-utils/accountFootprint.ts +10 -1
- package/src/test-utils/liveApp.ts +10 -1
- package/src/token/handoff.ts +180 -0
- package/src/version.generated.ts +1 -1
package/dist/client/api.d.ts
CHANGED
|
@@ -13,11 +13,12 @@
|
|
|
13
13
|
* `/sign-out`, the two OTP routes, the magic link, and the social handoff — each spelling out the same
|
|
14
14
|
* transport by hand. They call this now, and this upgrades with a minor release (#370).
|
|
15
15
|
*
|
|
16
|
-
* **
|
|
17
|
-
* `credentials: "include"` and nothing else: no token in `localStorage` or
|
|
18
|
-
* `Authorization` header, no refresh rotation. The SPA and its Worker share an
|
|
19
|
-
* rides an httpOnly cookie JavaScript cannot read.
|
|
20
|
-
*
|
|
16
|
+
* **Two transports, chosen by one option.** With no `origin`, every request is a rooted path on the
|
|
17
|
+
* page's own origin carrying `credentials: "include"` and nothing else: no token in `localStorage` or
|
|
18
|
+
* `sessionStorage`, no `Authorization` header, no refresh rotation. The SPA and its Worker share an
|
|
19
|
+
* origin, so the session rides an httpOnly cookie JavaScript cannot read. With an `origin` — a native
|
|
20
|
+
* app, which no Worker serves — the request goes to that origin with `credentials: "omit"`, and the
|
|
21
|
+
* credential is the `Authorization` header the handed-in `fetch` adds. `./bearer` builds that fetch.
|
|
21
22
|
*
|
|
22
23
|
* **CSRF travels with the cookie mode, and half of it is on this side of the wire.** The server's
|
|
23
24
|
* `requireSameOrigin()` refuses a cookie-authenticated mutating request whose `Origin` does not match;
|
|
@@ -34,7 +35,7 @@
|
|
|
34
35
|
* on this side of the wire protects anything, it only decides what a screen shows.
|
|
35
36
|
*
|
|
36
37
|
* **No absolute URL literals, and no schema library.** Paths are relative, so the calls follow whatever
|
|
37
|
-
* origin the bundle is served from. Answers are narrowed by hand-written `is…(value: unknown): value is
|
|
38
|
+
* origin the bundle is served from, or the one `origin` names. Answers are narrowed by hand-written `is…(value: unknown): value is
|
|
38
39
|
* T` guards rather than Zod: this file compiles into an adopter's browser bundle, and it must not drag
|
|
39
40
|
* the Worker's schema graph in behind it. `sameOrigin.test.ts` holds the import list to empty, so the
|
|
40
41
|
* property is structural rather than a habit.
|
|
@@ -55,7 +56,10 @@ export interface AuthRequestInit {
|
|
|
55
56
|
headers?: Record<string, string>;
|
|
56
57
|
/** The JSON body, already serialized. */
|
|
57
58
|
body?: string;
|
|
58
|
-
/**
|
|
59
|
+
/**
|
|
60
|
+
* Cookie policy. `include` on the page's own origin, where the session is an httpOnly cookie; `omit`
|
|
61
|
+
* once an {@link AuthClientOptions.origin} is set, where the credential is a bearer the fetch adds.
|
|
62
|
+
*/
|
|
59
63
|
credentials?: "include" | "same-origin" | "omit";
|
|
60
64
|
}
|
|
61
65
|
/** The slice of `Response` this module reads. */
|
|
@@ -94,6 +98,13 @@ export type AuthGate = (body: Record<string, unknown>) => {
|
|
|
94
98
|
};
|
|
95
99
|
/** What every call takes: where the routes are, and the seams a test replaces. */
|
|
96
100
|
export interface AuthClientOptions {
|
|
101
|
+
/**
|
|
102
|
+
* The Worker's absolute origin, for a program it does not serve: a native app. `scheme://host[:port]`
|
|
103
|
+
* over http or https and nothing else — no path, no trailing slash. Absent, every request is a rooted
|
|
104
|
+
* path on the page's own origin carrying its cookie. Present, the request goes to this origin with no
|
|
105
|
+
* cookie, and the credential is whatever the `fetch` handed in adds.
|
|
106
|
+
*/
|
|
107
|
+
origin?: string;
|
|
97
108
|
/** Where the auth routes mount. Defaults to {@link AUTH_BASE_PATH}. */
|
|
98
109
|
basePath?: string;
|
|
99
110
|
/** The fetch to use. Defaults to the one on {@link AuthClientOptions.global}. */
|
|
@@ -127,14 +138,46 @@ export declare const AUTH_UNREADABLE: AuthFailure;
|
|
|
127
138
|
/**
|
|
128
139
|
* The request would have left this origin, so it was never sent.
|
|
129
140
|
*
|
|
130
|
-
*
|
|
131
|
-
*
|
|
132
|
-
* would attach
|
|
133
|
-
* the cookie mode exists to keep from happening.
|
|
141
|
+
* Reached through a `basePath` that is not a rooted path — an absolute URL, a protocol-relative
|
|
142
|
+
* `//host`, a backslash form a URL parser reads as one — or an `origin` that is not a bare http(s)
|
|
143
|
+
* origin. Sending it would attach a session to a request this program is not entitled to make.
|
|
134
144
|
*/
|
|
135
145
|
export declare const AUTH_CROSS_ORIGIN: AuthFailure;
|
|
136
146
|
/**
|
|
137
|
-
*
|
|
147
|
+
* Whether a composed path stays on this origin.
|
|
148
|
+
*
|
|
149
|
+
* A rooted path and nothing that resolves elsewhere. `//host` and `/\host` are the two forms a URL
|
|
150
|
+
* parser reads as an authority rather than as a path, and a browser follows both — which is why the
|
|
151
|
+
* check is on the second character rather than on a scheme it would never find after a leading `/`.
|
|
152
|
+
*/
|
|
153
|
+
export declare function isSameOriginPath(path: string): boolean;
|
|
154
|
+
/**
|
|
155
|
+
* Whether a configured origin is a bare http(s) origin: a scheme, a host, an optional port, nothing else.
|
|
156
|
+
*
|
|
157
|
+
* A regular expression rather than `new URL`, because React Native's `URL` does not implement the
|
|
158
|
+
* getters a parsed check would read. Userinfo, a path, a query, a fragment, a backslash and whitespace
|
|
159
|
+
* are all refused, so the composed URL can only ever name this host.
|
|
160
|
+
*/
|
|
161
|
+
export declare function isBareOrigin(origin: string): boolean;
|
|
162
|
+
/**
|
|
163
|
+
* The fetch a call goes through: the one passed, else the one on the injected global, else none.
|
|
164
|
+
*
|
|
165
|
+
* Exported so `./bearer` reaches the global the same way every call here does, rather than keeping a
|
|
166
|
+
* second copy of where a fetch comes from.
|
|
167
|
+
*/
|
|
168
|
+
export declare function resolveFetch(options: Pick<AuthClientOptions, "fetch" | "global"> | undefined): AuthFetch | undefined;
|
|
169
|
+
/**
|
|
170
|
+
* The same request with no cookie on it — the bearer transport's policy.
|
|
171
|
+
*
|
|
172
|
+
* Written here because this module is the one place a cookie mode is written. `./bearer` puts it on
|
|
173
|
+
* every request its session sends, which is what keeps a cookie a native `fetch` stored from a sign-in
|
|
174
|
+
* answer from riding alongside the bearer: Better Auth refuses a cookie-carrying request with no
|
|
175
|
+
* `Origin`.
|
|
176
|
+
*/
|
|
177
|
+
export declare function withoutCookies(init: AuthRequestInit | undefined): AuthRequestInit;
|
|
178
|
+
/**
|
|
179
|
+
* One call: same-origin and cookie-carrying, or to an absolute origin with no cookie; never throwing.
|
|
180
|
+
* **The only producer of either request.**
|
|
138
181
|
*
|
|
139
182
|
* The body is read before the status is judged, because a refusal's body is the failure a screen
|
|
140
183
|
* renders. A body that will not parse is the generic failure rather than a crash — a corporate proxy's
|
package/dist/client/api.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../../src/client/api.ts"],"names":[],"mappings":"AAGA
|
|
1
|
+
{"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../../src/client/api.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AAEH,iGAAiG;AACjG,eAAO,MAAM,cAAc,UAAU,CAAC;AAEtC;;;;;;GAMG;AACH,MAAM,WAAW,eAAe;IAC9B,yCAAyC;IACzC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,uBAAuB;IACvB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,yCAAyC;IACzC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd;;;OAGG;IACH,WAAW,CAAC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E;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAA;CAAE,EAC7C,OAAO,CAAC,EAAE,iBAAiB,GAC1B,OAAO,CAAC,UAAU,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,CAE9C;AAED;;;;;;;GAOG;AACH,MAAM,MAAM,YAAY,GACpB;IAAE,IAAI,EAAE,WAAW,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAClC;IAAE,IAAI,EAAE,cAAc,CAAA;CAAE,GACxB;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,OAAO,EAAE,WAAW,CAAA;CAAE,CAAC;AA0B9C;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAsB,iBAAiB,CACrC,KAAK,EAAE;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC;IAAC,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAAE,EAC3E,OAAO,CAAC,EAAE,iBAAiB,GAC1B,OAAO,CAAC,YAAY,CAAC,CAOvB"}
|
package/dist/client/api.js
CHANGED
|
@@ -14,11 +14,12 @@
|
|
|
14
14
|
* `/sign-out`, the two OTP routes, the magic link, and the social handoff — each spelling out the same
|
|
15
15
|
* transport by hand. They call this now, and this upgrades with a minor release (#370).
|
|
16
16
|
*
|
|
17
|
-
* **
|
|
18
|
-
* `credentials: "include"` and nothing else: no token in `localStorage` or
|
|
19
|
-
* `Authorization` header, no refresh rotation. The SPA and its Worker share an
|
|
20
|
-
* rides an httpOnly cookie JavaScript cannot read.
|
|
21
|
-
*
|
|
17
|
+
* **Two transports, chosen by one option.** With no `origin`, every request is a rooted path on the
|
|
18
|
+
* page's own origin carrying `credentials: "include"` and nothing else: no token in `localStorage` or
|
|
19
|
+
* `sessionStorage`, no `Authorization` header, no refresh rotation. The SPA and its Worker share an
|
|
20
|
+
* origin, so the session rides an httpOnly cookie JavaScript cannot read. With an `origin` — a native
|
|
21
|
+
* app, which no Worker serves — the request goes to that origin with `credentials: "omit"`, and the
|
|
22
|
+
* credential is the `Authorization` header the handed-in `fetch` adds. `./bearer` builds that fetch.
|
|
22
23
|
*
|
|
23
24
|
* **CSRF travels with the cookie mode, and half of it is on this side of the wire.** The server's
|
|
24
25
|
* `requireSameOrigin()` refuses a cookie-authenticated mutating request whose `Origin` does not match;
|
|
@@ -35,7 +36,7 @@
|
|
|
35
36
|
* on this side of the wire protects anything, it only decides what a screen shows.
|
|
36
37
|
*
|
|
37
38
|
* **No absolute URL literals, and no schema library.** Paths are relative, so the calls follow whatever
|
|
38
|
-
* origin the bundle is served from. Answers are narrowed by hand-written `is…(value: unknown): value is
|
|
39
|
+
* origin the bundle is served from, or the one `origin` names. Answers are narrowed by hand-written `is…(value: unknown): value is
|
|
39
40
|
* T` guards rather than Zod: this file compiles into an adopter's browser bundle, and it must not drag
|
|
40
41
|
* the Worker's schema graph in behind it. `sameOrigin.test.ts` holds the import list to empty, so the
|
|
41
42
|
* property is structural rather than a habit.
|
|
@@ -57,15 +58,14 @@ const AUTH_UNREADABLE = {
|
|
|
57
58
|
/**
|
|
58
59
|
* The request would have left this origin, so it was never sent.
|
|
59
60
|
*
|
|
60
|
-
*
|
|
61
|
-
*
|
|
62
|
-
* would attach
|
|
63
|
-
* the cookie mode exists to keep from happening.
|
|
61
|
+
* Reached through a `basePath` that is not a rooted path — an absolute URL, a protocol-relative
|
|
62
|
+
* `//host`, a backslash form a URL parser reads as one — or an `origin` that is not a bare http(s)
|
|
63
|
+
* origin. Sending it would attach a session to a request this program is not entitled to make.
|
|
64
64
|
*/
|
|
65
65
|
const AUTH_CROSS_ORIGIN = {
|
|
66
66
|
code: "client/cross_origin",
|
|
67
67
|
message: "That request would have left this site, so it wasn't sent.",
|
|
68
|
-
action: "Check the auth `basePath` in pithy.config.ts
|
|
68
|
+
action: "Check the auth `basePath` in pithy.config.ts, which is a path on the worker and not a URL, and the client's `origin`, which is a scheme and host with no path."
|
|
69
69
|
};
|
|
70
70
|
/** Whether a value is a plain record — the first step of every guard below. */
|
|
71
71
|
function isRecord(value) {
|
|
@@ -84,6 +84,39 @@ function isSameOriginPath(path) {
|
|
|
84
84
|
return second !== "/" && second !== "\\";
|
|
85
85
|
}
|
|
86
86
|
/**
|
|
87
|
+
* Whether a configured origin is a bare http(s) origin: a scheme, a host, an optional port, nothing else.
|
|
88
|
+
*
|
|
89
|
+
* A regular expression rather than `new URL`, because React Native's `URL` does not implement the
|
|
90
|
+
* getters a parsed check would read. Userinfo, a path, a query, a fragment, a backslash and whitespace
|
|
91
|
+
* are all refused, so the composed URL can only ever name this host.
|
|
92
|
+
*/
|
|
93
|
+
function isBareOrigin(origin) {
|
|
94
|
+
return /^https?:\/\/[A-Za-z0-9.-]+(?::[0-9]{1,5})?$|^https?:\/\/\[[0-9A-Fa-f:.]+\](?::[0-9]{1,5})?$/.test(origin);
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* The fetch a call goes through: the one passed, else the one on the injected global, else none.
|
|
98
|
+
*
|
|
99
|
+
* Exported so `./bearer` reaches the global the same way every call here does, rather than keeping a
|
|
100
|
+
* second copy of where a fetch comes from.
|
|
101
|
+
*/
|
|
102
|
+
function resolveFetch(options) {
|
|
103
|
+
return options?.fetch ?? (options?.global ?? globalThis).fetch;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* The same request with no cookie on it — the bearer transport's policy.
|
|
107
|
+
*
|
|
108
|
+
* Written here because this module is the one place a cookie mode is written. `./bearer` puts it on
|
|
109
|
+
* every request its session sends, which is what keeps a cookie a native `fetch` stored from a sign-in
|
|
110
|
+
* answer from riding alongside the bearer: Better Auth refuses a cookie-carrying request with no
|
|
111
|
+
* `Origin`.
|
|
112
|
+
*/
|
|
113
|
+
function withoutCookies(init) {
|
|
114
|
+
return {
|
|
115
|
+
...init,
|
|
116
|
+
credentials: "omit"
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
87
120
|
* A failure read off either shape this Worker answers with, or the generic one when the body is neither.
|
|
88
121
|
*
|
|
89
122
|
* **Two shapes, because two packages own routes here and only one of them is ours.** Everything this
|
|
@@ -127,7 +160,8 @@ function readFailure(body) {
|
|
|
127
160
|
};
|
|
128
161
|
}
|
|
129
162
|
/**
|
|
130
|
-
* One call: same-origin
|
|
163
|
+
* One call: same-origin and cookie-carrying, or to an absolute origin with no cookie; never throwing.
|
|
164
|
+
* **The only producer of either request.**
|
|
131
165
|
*
|
|
132
166
|
* The body is read before the status is judged, because a refusal's body is the failure a screen
|
|
133
167
|
* renders. A body that will not parse is the generic failure rather than a crash — a corporate proxy's
|
|
@@ -144,22 +178,27 @@ function readFailure(body) {
|
|
|
144
178
|
* dragging the Worker's schema graph in behind it would break their build rather than ours.
|
|
145
179
|
*/
|
|
146
180
|
async function callAuth(path, init, options, guard) {
|
|
147
|
-
const
|
|
148
|
-
if (!isSameOriginPath(
|
|
181
|
+
const rooted = `${options?.basePath ?? "/auth"}${path}`;
|
|
182
|
+
if (!isSameOriginPath(rooted)) return {
|
|
183
|
+
ok: false,
|
|
184
|
+
failure: AUTH_CROSS_ORIGIN
|
|
185
|
+
};
|
|
186
|
+
const origin = options?.origin;
|
|
187
|
+
if (origin !== void 0 && !isBareOrigin(origin)) return {
|
|
149
188
|
ok: false,
|
|
150
189
|
failure: AUTH_CROSS_ORIGIN
|
|
151
190
|
};
|
|
152
|
-
const fetcher =
|
|
191
|
+
const fetcher = resolveFetch(options);
|
|
153
192
|
if (!fetcher) return {
|
|
154
193
|
ok: false,
|
|
155
194
|
failure: AUTH_UNREACHABLE
|
|
156
195
|
};
|
|
157
196
|
let response;
|
|
158
197
|
try {
|
|
159
|
-
response = await fetcher(
|
|
198
|
+
response = origin === void 0 ? await fetcher(rooted, {
|
|
160
199
|
...init,
|
|
161
200
|
credentials: "include"
|
|
162
|
-
});
|
|
201
|
+
}) : await fetcher(`${origin}${rooted}`, withoutCookies(init));
|
|
163
202
|
} catch {
|
|
164
203
|
return {
|
|
165
204
|
ok: false,
|
|
@@ -399,4 +438,4 @@ async function startSocialSignIn(input, options) {
|
|
|
399
438
|
} : { kind: "unconfigured" };
|
|
400
439
|
}
|
|
401
440
|
//#endregion
|
|
402
|
-
export { AUTH_BASE_PATH, AUTH_CROSS_ORIGIN, AUTH_UNREACHABLE, AUTH_UNREADABLE, callAuth, getSession, sendMagicLink, sendOtp, signInWithOtp, signOut, startSocialSignIn, updateUser };
|
|
441
|
+
export { AUTH_BASE_PATH, AUTH_CROSS_ORIGIN, AUTH_UNREACHABLE, AUTH_UNREADABLE, callAuth, getSession, isBareOrigin, isSameOriginPath, resolveFetch, sendMagicLink, sendOtp, signInWithOtp, signOut, startSocialSignIn, updateUser, withoutCookies };
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import { type AuthClientOptions, type AuthFetch, type AuthResult } from "./api";
|
|
4
|
+
/**
|
|
5
|
+
* The bearer half of `@pithy-sh/auth`'s client: how a program this Worker does not serve — a native app —
|
|
6
|
+
* holds a session and presents it.
|
|
7
|
+
*
|
|
8
|
+
* **The credential is the raw session token**, the `token` a sign-in answers with and the `refreshToken`
|
|
9
|
+
* `/token/rotate` answers with. Never the JWT `accessToken` beside it, which the kit's own routes do not
|
|
10
|
+
* accept, and never the signed `set-auth-token` header, which the Worker cannot match against a spent
|
|
11
|
+
* credential. Only the raw token lets a replay be recognized as one.
|
|
12
|
+
*
|
|
13
|
+
* **It lives in memory and persists through a {@link SecureStore}**, the Keychain or the Keystore on a
|
|
14
|
+
* phone (`expo-secure-store`). Nothing here writes to `AsyncStorage` or `localStorage`.
|
|
15
|
+
*
|
|
16
|
+
* **Rotation is single-flight, and the successor is stored before anything uses it.** `/token/rotate`
|
|
17
|
+
* spends the credential it is shown. A second rotation of the same credential is refused, and one more
|
|
18
|
+
* than thirty seconds late is read as theft: every session descended from that sign-in is revoked. So
|
|
19
|
+
* one rotation is ever in flight, every request that arrives during it waits for it, and none proceeds
|
|
20
|
+
* until the successor is in the store — a launch that read the spent one back would present it.
|
|
21
|
+
*
|
|
22
|
+
* Nothing here throws. A store that fails costs persistence, never a crash, and every failure on the
|
|
23
|
+
* wire is an {@link AuthResult}.
|
|
24
|
+
*/
|
|
25
|
+
/** Where a credential is persisted between launches. `expo-secure-store`'s three calls have this shape. */
|
|
26
|
+
export interface SecureStore {
|
|
27
|
+
/** The value stored under `key`, or `null`. */
|
|
28
|
+
getItem(key: string): Promise<string | null>;
|
|
29
|
+
/** Store `value` under `key`. */
|
|
30
|
+
setItem(key: string, value: string): Promise<void>;
|
|
31
|
+
/** Remove whatever is stored under `key`. */
|
|
32
|
+
deleteItem(key: string): Promise<void>;
|
|
33
|
+
}
|
|
34
|
+
/** The device a sign-in registers. The Worker lists it, and revoking it signs out its sessions. */
|
|
35
|
+
export interface DeviceInfo {
|
|
36
|
+
/** A stable id the app mints once per install, at most 128 characters. */
|
|
37
|
+
id: string;
|
|
38
|
+
/** The platform the app runs on. */
|
|
39
|
+
platform: "ios" | "android" | "web";
|
|
40
|
+
/** A human label for the device, when the platform gives one. */
|
|
41
|
+
name?: string;
|
|
42
|
+
/** The hardware model, when the platform gives one. */
|
|
43
|
+
model?: string;
|
|
44
|
+
}
|
|
45
|
+
/** A bearer session: the transport every client call takes, and the credential behind it. */
|
|
46
|
+
export interface BearerSession {
|
|
47
|
+
/** `{ origin, basePath, fetch }`. Pass it to every auth call. */
|
|
48
|
+
readonly options: AuthClientOptions;
|
|
49
|
+
/**
|
|
50
|
+
* A fetch that adds `Authorization` when a credential is held, sends no cookie, and rotates first when
|
|
51
|
+
* the credential is due. Another capability's client takes it as its own `fetch`.
|
|
52
|
+
*/
|
|
53
|
+
readonly fetch: AuthFetch;
|
|
54
|
+
/** Load the credential an earlier launch stored. `true` when one was found. */
|
|
55
|
+
restore(): Promise<boolean>;
|
|
56
|
+
/** Hold the raw session token a sign-in answered with. Resolves once it is stored. */
|
|
57
|
+
adopt(token: string): Promise<void>;
|
|
58
|
+
/** Trade the credential for its successor. Concurrent calls share one request. */
|
|
59
|
+
rotate(): Promise<AuthResult<{
|
|
60
|
+
expiresAt: string;
|
|
61
|
+
}>>;
|
|
62
|
+
/** Forget the credential here and in the store. Sign-out calls this after the server call. */
|
|
63
|
+
clear(): Promise<void>;
|
|
64
|
+
/** Whether a credential is held. */
|
|
65
|
+
signedIn(): boolean;
|
|
66
|
+
/**
|
|
67
|
+
* The `Authorization` value a request to `url` would carry now, rotating first when due, for a request the
|
|
68
|
+
* platform sends itself rather than through {@link BearerSession.fetch}: an image the app draws. `null` when
|
|
69
|
+
* nothing is held, and for any URL off the Worker's origin, so the credential is still only ever presented there.
|
|
70
|
+
*/
|
|
71
|
+
authorization(url: string): Promise<string | null>;
|
|
72
|
+
}
|
|
73
|
+
/** The key a credential is stored under by default. */
|
|
74
|
+
export declare const BEARER_STORAGE_KEY = "pithy.auth.session";
|
|
75
|
+
/**
|
|
76
|
+
* How long before its expiry a credential is rotated.
|
|
77
|
+
*
|
|
78
|
+
* Wide enough to absorb a phone's clock running a few minutes off the Worker's, narrow enough that a
|
|
79
|
+
* short configured session lifetime does not rotate on every request.
|
|
80
|
+
*/
|
|
81
|
+
export declare const ROTATION_MARGIN_MS: number;
|
|
82
|
+
/** The request headers the Worker reads a device from at sign-in. */
|
|
83
|
+
export declare const BEARER_DEVICE_HEADERS: {
|
|
84
|
+
readonly id: "x-pithy-device-id";
|
|
85
|
+
readonly platform: "x-pithy-platform";
|
|
86
|
+
readonly name: "x-pithy-device-name";
|
|
87
|
+
readonly model: "x-pithy-device-model";
|
|
88
|
+
};
|
|
89
|
+
/**
|
|
90
|
+
* Start a bearer session against the Worker at `origin`.
|
|
91
|
+
*
|
|
92
|
+
* Nothing is held until {@link BearerSession.restore} or {@link BearerSession.adopt}. Device headers
|
|
93
|
+
* ride on every request to the auth routes, so whichever route creates the session registers the
|
|
94
|
+
* device; requests to another capability's routes carry the credential alone.
|
|
95
|
+
* A URL off `origin` is refused before it is sent, so the credential is only ever presented to this Worker.
|
|
96
|
+
*
|
|
97
|
+
* The expiry is learnt from what the Worker says: each rotation's `expiresAt`, and the session a
|
|
98
|
+
* `get-session` describes. Until one of those has been seen, nothing rotates on its own. A `get-session`
|
|
99
|
+
* that answers nobody means the credential is dead, and it is forgotten.
|
|
100
|
+
*/
|
|
101
|
+
export declare function createBearerSession(input: {
|
|
102
|
+
origin: string;
|
|
103
|
+
basePath?: string;
|
|
104
|
+
store: SecureStore;
|
|
105
|
+
device: DeviceInfo;
|
|
106
|
+
fetch?: AuthFetch;
|
|
107
|
+
now?: () => number;
|
|
108
|
+
storageKey?: string;
|
|
109
|
+
}): BearerSession;
|
|
110
|
+
//# sourceMappingURL=bearer.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bearer.d.ts","sourceRoot":"","sources":["../../src/client/bearer.ts"],"names":[],"mappings":"AAGA,OAAO,EAEL,KAAK,iBAAiB,EACtB,KAAK,SAAS,EAGd,KAAK,UAAU,EAKhB,MAAM,OAAO,CAAC;AAEf;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,2GAA2G;AAC3G,MAAM,WAAW,WAAW;IAC1B,+CAA+C;IAC/C,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IAC7C,iCAAiC;IACjC,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACnD,6CAA6C;IAC7C,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACxC;AAED,mGAAmG;AACnG,MAAM,WAAW,UAAU;IACzB,0EAA0E;IAC1E,EAAE,EAAE,MAAM,CAAC;IACX,oCAAoC;IACpC,QAAQ,EAAE,KAAK,GAAG,SAAS,GAAG,KAAK,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E,SAAS,CAAC;IAClB,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB,GAAG,aAAa,CA6LhB"}
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import { callAuth, isBareOrigin, resolveFetch, withoutCookies } from "./api.js";
|
|
4
|
+
//#region src/client/bearer.ts
|
|
5
|
+
/** The key a credential is stored under by default. */
|
|
6
|
+
const BEARER_STORAGE_KEY = "pithy.auth.session";
|
|
7
|
+
/**
|
|
8
|
+
* How long before its expiry a credential is rotated.
|
|
9
|
+
*
|
|
10
|
+
* Wide enough to absorb a phone's clock running a few minutes off the Worker's, narrow enough that a
|
|
11
|
+
* short configured session lifetime does not rotate on every request.
|
|
12
|
+
*/
|
|
13
|
+
const ROTATION_MARGIN_MS = 6e5;
|
|
14
|
+
/** The request headers the Worker reads a device from at sign-in. */
|
|
15
|
+
const BEARER_DEVICE_HEADERS = {
|
|
16
|
+
id: "x-pithy-device-id",
|
|
17
|
+
platform: "x-pithy-platform",
|
|
18
|
+
name: "x-pithy-device-name",
|
|
19
|
+
model: "x-pithy-device-model"
|
|
20
|
+
};
|
|
21
|
+
/** The longest device id the Worker stores. A longer one would fail the sign-in, so none is sent. */
|
|
22
|
+
const MAX_DEVICE_ID = 128;
|
|
23
|
+
/** Whether a value is a plain record. */
|
|
24
|
+
function isRecord(value) {
|
|
25
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
26
|
+
}
|
|
27
|
+
/** What `/token/rotate` answers with, as far as this client reads it. */
|
|
28
|
+
function isRotation(value) {
|
|
29
|
+
return isRecord(value) && typeof value.refreshToken === "string" && value.refreshToken !== "" && typeof value.expiresAt === "string";
|
|
30
|
+
}
|
|
31
|
+
/** An ISO instant as epoch milliseconds, or `null` when it is not one. */
|
|
32
|
+
function instant(value) {
|
|
33
|
+
if (typeof value !== "string") return null;
|
|
34
|
+
const parsed = Date.parse(value);
|
|
35
|
+
return Number.isNaN(parsed) ? null : parsed;
|
|
36
|
+
}
|
|
37
|
+
/** A stored credential read back, or `null` when the value is not one this module wrote. */
|
|
38
|
+
function readHeld(raw) {
|
|
39
|
+
if (raw === null) return null;
|
|
40
|
+
let parsed;
|
|
41
|
+
try {
|
|
42
|
+
parsed = JSON.parse(raw);
|
|
43
|
+
} catch {
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
if (!isRecord(parsed) || typeof parsed.token !== "string" || parsed.token === "") return null;
|
|
47
|
+
const expiresAt = typeof parsed.expiresAt === "number" && Number.isFinite(parsed.expiresAt) ? parsed.expiresAt : null;
|
|
48
|
+
return {
|
|
49
|
+
token: parsed.token,
|
|
50
|
+
expiresAt
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* A header value `fetch` will send: printable ASCII only, trimmed, or nothing.
|
|
55
|
+
*
|
|
56
|
+
* `fetch` rejects a header value outside Latin-1, so a phone named with a curly apostrophe or an emoji
|
|
57
|
+
* would otherwise turn every sign-in from it into an unreachable Worker.
|
|
58
|
+
*/
|
|
59
|
+
function headerValue(value) {
|
|
60
|
+
if (value === void 0) return null;
|
|
61
|
+
const cleaned = value.replace(/[^\x20-\x7e]/g, "").trim();
|
|
62
|
+
return cleaned === "" ? null : cleaned;
|
|
63
|
+
}
|
|
64
|
+
/** The device headers a sign-in carries, or none when the id is one the Worker would refuse. */
|
|
65
|
+
function deviceHeaders(device) {
|
|
66
|
+
const id = headerValue(device.id);
|
|
67
|
+
if (id === null || id.length > MAX_DEVICE_ID) return {};
|
|
68
|
+
const headers = {
|
|
69
|
+
[BEARER_DEVICE_HEADERS.id]: id,
|
|
70
|
+
[BEARER_DEVICE_HEADERS.platform]: device.platform
|
|
71
|
+
};
|
|
72
|
+
const name = headerValue(device.name);
|
|
73
|
+
if (name !== null) headers[BEARER_DEVICE_HEADERS.name] = name;
|
|
74
|
+
const model = headerValue(device.model);
|
|
75
|
+
if (model !== null) headers[BEARER_DEVICE_HEADERS.model] = model;
|
|
76
|
+
return headers;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Start a bearer session against the Worker at `origin`.
|
|
80
|
+
*
|
|
81
|
+
* Nothing is held until {@link BearerSession.restore} or {@link BearerSession.adopt}. Device headers
|
|
82
|
+
* ride on every request to the auth routes, so whichever route creates the session registers the
|
|
83
|
+
* device; requests to another capability's routes carry the credential alone.
|
|
84
|
+
* A URL off `origin` is refused before it is sent, so the credential is only ever presented to this Worker.
|
|
85
|
+
*
|
|
86
|
+
* The expiry is learnt from what the Worker says: each rotation's `expiresAt`, and the session a
|
|
87
|
+
* `get-session` describes. Until one of those has been seen, nothing rotates on its own. A `get-session`
|
|
88
|
+
* that answers nobody means the credential is dead, and it is forgotten.
|
|
89
|
+
*/
|
|
90
|
+
function createBearerSession(input) {
|
|
91
|
+
const { origin, store } = input;
|
|
92
|
+
const basePath = input.basePath ?? "/auth";
|
|
93
|
+
const key = input.storageKey ?? "pithy.auth.session";
|
|
94
|
+
const now = input.now ?? Date.now;
|
|
95
|
+
const device = deviceHeaders(input.device);
|
|
96
|
+
const authPrefix = `${origin}${basePath}/`;
|
|
97
|
+
const sessionUrl = `${origin}${basePath}/get-session`;
|
|
98
|
+
let held = null;
|
|
99
|
+
let generation = 0;
|
|
100
|
+
let inflight = null;
|
|
101
|
+
async function persist(next) {
|
|
102
|
+
try {
|
|
103
|
+
await store.setItem(key, JSON.stringify(next));
|
|
104
|
+
} catch {
|
|
105
|
+
await forget();
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
async function forget() {
|
|
109
|
+
try {
|
|
110
|
+
await store.deleteItem(key);
|
|
111
|
+
} catch {}
|
|
112
|
+
}
|
|
113
|
+
/** Whether the credential may be presented to `url`: the Worker's own origin, and nowhere else. */
|
|
114
|
+
function ownOrigin(url) {
|
|
115
|
+
return isBareOrigin(origin) && url.startsWith(`${origin}/`);
|
|
116
|
+
}
|
|
117
|
+
function send(url, init, token) {
|
|
118
|
+
if (!ownOrigin(url)) return Promise.reject(/* @__PURE__ */ new TypeError("A bearer session only sends to its own Worker's origin."));
|
|
119
|
+
const headers = {};
|
|
120
|
+
for (const [name, value] of Object.entries(init?.headers ?? {})) if (name.toLowerCase() !== "authorization") headers[name] = value;
|
|
121
|
+
if (url.startsWith(authPrefix)) Object.assign(headers, device);
|
|
122
|
+
if (token !== null) headers.authorization = `Bearer ${token}`;
|
|
123
|
+
const underlying = resolveFetch({ fetch: input.fetch });
|
|
124
|
+
if (!underlying) return Promise.reject(/* @__PURE__ */ new TypeError("No fetch is available to send this request."));
|
|
125
|
+
return underlying(url, withoutCookies({
|
|
126
|
+
...init,
|
|
127
|
+
headers
|
|
128
|
+
}));
|
|
129
|
+
}
|
|
130
|
+
function due() {
|
|
131
|
+
return held !== null && held.expiresAt !== null && now() >= held.expiresAt - 6e5;
|
|
132
|
+
}
|
|
133
|
+
async function runRotation() {
|
|
134
|
+
const started = generation;
|
|
135
|
+
const token = held?.token ?? null;
|
|
136
|
+
let status = 0;
|
|
137
|
+
const recording = async (url, init) => {
|
|
138
|
+
const response = await send(url, init, token);
|
|
139
|
+
status = response.status;
|
|
140
|
+
return response;
|
|
141
|
+
};
|
|
142
|
+
const result = await callAuth("/token/rotate", { method: "POST" }, {
|
|
143
|
+
origin,
|
|
144
|
+
basePath,
|
|
145
|
+
fetch: recording
|
|
146
|
+
}, isRotation);
|
|
147
|
+
const current = started === generation;
|
|
148
|
+
if (!result.ok) {
|
|
149
|
+
if (current && status === 401) await clear();
|
|
150
|
+
return result;
|
|
151
|
+
}
|
|
152
|
+
if (current) {
|
|
153
|
+
const next = {
|
|
154
|
+
token: result.value.refreshToken,
|
|
155
|
+
expiresAt: instant(result.value.expiresAt)
|
|
156
|
+
};
|
|
157
|
+
held = next;
|
|
158
|
+
await persist(next);
|
|
159
|
+
}
|
|
160
|
+
return {
|
|
161
|
+
ok: true,
|
|
162
|
+
value: { expiresAt: result.value.expiresAt }
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
function rotate() {
|
|
166
|
+
if (inflight) return inflight;
|
|
167
|
+
const running = runRotation().finally(() => {
|
|
168
|
+
if (inflight === running) inflight = null;
|
|
169
|
+
});
|
|
170
|
+
inflight = running;
|
|
171
|
+
return running;
|
|
172
|
+
}
|
|
173
|
+
function observeSession(body, presented) {
|
|
174
|
+
if (held === null || held.token !== presented) return;
|
|
175
|
+
if (body === null) {
|
|
176
|
+
if (inflight) {
|
|
177
|
+
const settle = () => {
|
|
178
|
+
if (held !== null && held.token === presented) clear();
|
|
179
|
+
};
|
|
180
|
+
inflight.then(settle, settle);
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
clear();
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
if (!isRecord(body) || !isRecord(body.session)) return;
|
|
187
|
+
const expiresAt = instant(body.session.expiresAt);
|
|
188
|
+
if (expiresAt === null || expiresAt === held.expiresAt) return;
|
|
189
|
+
held = {
|
|
190
|
+
token: held.token,
|
|
191
|
+
expiresAt
|
|
192
|
+
};
|
|
193
|
+
persist(held);
|
|
194
|
+
}
|
|
195
|
+
/** Wait out a rotation in flight, or start one when the credential is due. */
|
|
196
|
+
async function current() {
|
|
197
|
+
if (inflight) await inflight;
|
|
198
|
+
else if (due()) await rotate();
|
|
199
|
+
}
|
|
200
|
+
const sessionFetch = async (url, init) => {
|
|
201
|
+
await current();
|
|
202
|
+
const token = held?.token ?? null;
|
|
203
|
+
const response = await send(url, init, token);
|
|
204
|
+
if (token === null || url !== sessionUrl || !response.ok) return response;
|
|
205
|
+
return {
|
|
206
|
+
ok: response.ok,
|
|
207
|
+
status: response.status,
|
|
208
|
+
json: async () => {
|
|
209
|
+
const body = await response.json();
|
|
210
|
+
observeSession(body, token);
|
|
211
|
+
return body;
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
};
|
|
215
|
+
async function clear() {
|
|
216
|
+
generation += 1;
|
|
217
|
+
held = null;
|
|
218
|
+
await forget();
|
|
219
|
+
}
|
|
220
|
+
return {
|
|
221
|
+
options: {
|
|
222
|
+
origin,
|
|
223
|
+
basePath,
|
|
224
|
+
fetch: sessionFetch
|
|
225
|
+
},
|
|
226
|
+
fetch: sessionFetch,
|
|
227
|
+
async restore() {
|
|
228
|
+
const started = generation;
|
|
229
|
+
const before = held;
|
|
230
|
+
let raw;
|
|
231
|
+
try {
|
|
232
|
+
raw = await store.getItem(key);
|
|
233
|
+
} catch {
|
|
234
|
+
return false;
|
|
235
|
+
}
|
|
236
|
+
if (started !== generation || held !== before) return held !== null;
|
|
237
|
+
const restored = readHeld(raw);
|
|
238
|
+
if (restored === null) {
|
|
239
|
+
if (raw !== null) await forget();
|
|
240
|
+
return false;
|
|
241
|
+
}
|
|
242
|
+
held = restored;
|
|
243
|
+
return true;
|
|
244
|
+
},
|
|
245
|
+
async adopt(token) {
|
|
246
|
+
generation += 1;
|
|
247
|
+
const next = {
|
|
248
|
+
token,
|
|
249
|
+
expiresAt: null
|
|
250
|
+
};
|
|
251
|
+
held = next;
|
|
252
|
+
await persist(next);
|
|
253
|
+
},
|
|
254
|
+
rotate,
|
|
255
|
+
clear,
|
|
256
|
+
signedIn: () => held !== null,
|
|
257
|
+
async authorization(url) {
|
|
258
|
+
if (!ownOrigin(url)) return null;
|
|
259
|
+
await current();
|
|
260
|
+
return held === null ? null : `Bearer ${held.token}`;
|
|
261
|
+
}
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
//#endregion
|
|
265
|
+
export { BEARER_DEVICE_HEADERS, BEARER_STORAGE_KEY, ROTATION_MARGIN_MS, createBearerSession };
|