@pithy-sh/auth 0.10.0 → 0.12.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/README.md +30 -2
- package/dist/admin/users.js +1 -1
- package/dist/audit/actions.d.ts +58 -0
- package/dist/audit/actions.d.ts.map +1 -1
- package/dist/audit/actions.js +59 -1
- package/dist/audit/emit.d.ts +36 -0
- package/dist/audit/emit.d.ts.map +1 -1
- package/dist/audit/emit.js +48 -2
- package/dist/audit/evidence.d.ts +8 -2
- package/dist/audit/evidence.d.ts.map +1 -1
- package/dist/capability.d.ts +47 -8
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +56 -6
- 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 +26 -4
- package/dist/data/tables.d.ts.map +1 -1
- package/dist/data/tables.js +5 -3
- package/dist/data/userLifecycle.d.ts +10 -0
- package/dist/data/userLifecycle.d.ts.map +1 -1
- package/dist/data/userLifecycle.js +8 -3
- 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 +319 -8
- package/dist/http/csrf.d.ts.map +1 -1
- package/dist/http/csrf.js +2 -1
- package/dist/http/guards.d.ts +15 -10
- package/dist/http/guards.d.ts.map +1 -1
- package/dist/http/guards.js +76 -10
- 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 +37 -1
- package/dist/http/middleware.d.ts.map +1 -1
- package/dist/http/middleware.js +68 -6
- package/dist/http/resolve.d.ts.map +1 -1
- package/dist/http/resolve.js +9 -3
- package/dist/http/responses.d.ts +322 -0
- package/dist/http/responses.d.ts.map +1 -1
- package/dist/http/responses.js +202 -5
- package/dist/http/routes.d.ts +3 -0
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +78 -5
- package/dist/http/schemas.d.ts +114 -0
- package/dist/http/schemas.d.ts.map +1 -1
- package/dist/http/schemas.js +94 -1
- package/dist/http/views.d.ts +60 -3
- package/dist/http/views.d.ts.map +1 -1
- package/dist/http/views.js +143 -3
- 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 +87 -42
- 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/audited.d.ts +48 -0
- package/dist/lifecycle/audited.d.ts.map +1 -0
- package/dist/lifecycle/audited.js +65 -0
- package/dist/lifecycle/enforce.d.ts +37 -2
- package/dist/lifecycle/enforce.d.ts.map +1 -1
- package/dist/lifecycle/enforce.js +46 -5
- 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/reason.d.ts +11 -0
- package/dist/lifecycle/reason.d.ts.map +1 -0
- package/dist/lifecycle/reason.js +13 -0
- package/dist/lifecycle/request.d.ts +5 -2
- package/dist/lifecycle/request.d.ts.map +1 -1
- package/dist/lifecycle/request.js +6 -2
- package/dist/lifecycle/transitions.d.ts +179 -18
- package/dist/lifecycle/transitions.d.ts.map +1 -1
- package/dist/lifecycle/transitions.js +391 -70
- 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/0005_purge_once.d.ts +22 -0
- package/dist/migrations/0005_purge_once.d.ts.map +1 -0
- package/dist/migrations/0005_purge_once.js +35 -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/pluginTables.d.ts +8 -0
- package/dist/migrations/pluginTables.d.ts.map +1 -1
- package/dist/migrations/pluginTables.js +8 -1
- package/dist/migrations/set.d.ts +5 -1
- package/dist/migrations/set.d.ts.map +1 -1
- package/dist/migrations/set.js +10 -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 +62 -0
- package/dist/purge/contribution.d.ts.map +1 -0
- package/dist/purge/contribution.js +155 -0
- package/dist/purge/retryPolicy.d.ts +22 -0
- package/dist/purge/retryPolicy.d.ts.map +1 -0
- package/dist/purge/retryPolicy.js +26 -0
- package/dist/purge/run.d.ts +158 -0
- package/dist/purge/run.d.ts.map +1 -0
- package/dist/purge/run.js +205 -0
- package/dist/purge/specs.d.ts +71 -0
- package/dist/purge/specs.d.ts.map +1 -0
- package/dist/purge/specs.js +72 -0
- package/dist/purge/start.d.ts +42 -0
- package/dist/purge/start.d.ts.map +1 -0
- package/dist/purge/start.js +37 -0
- package/dist/purge/workflow.d.ts +71 -0
- package/dist/purge/workflow.d.ts.map +1 -0
- package/dist/purge/workflow.js +140 -0
- package/dist/test-utils/accountFootprint.d.ts +13 -0
- package/dist/test-utils/accountFootprint.d.ts.map +1 -0
- package/dist/test-utils/accountFootprint.js +49 -0
- 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 +176 -12
- 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 +58 -0
- package/src/audit/emit.ts +66 -1
- package/src/audit/evidence.ts +8 -4
- package/src/capability.ts +122 -18
- 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 +19 -4
- package/src/data/verificationOutcome.ts +86 -0
- package/src/email/send.ts +2 -2
- package/src/http/adminRoutes.ts +465 -4
- package/src/http/csrf.ts +4 -1
- package/src/http/guards.ts +79 -10
- package/src/http/handoff.ts +350 -0
- package/src/http/middleware.ts +74 -5
- package/src/http/resolve.ts +25 -25
- package/src/http/responses.ts +374 -3
- package/src/http/routes.ts +116 -5
- package/src/http/schemas.ts +195 -0
- package/src/http/views.ts +192 -3
- package/src/index.ts +2 -0
- package/src/instance/auth.ts +58 -3
- package/src/instance/plugins.ts +20 -2
- package/src/ledger/read.ts +133 -0
- package/src/ledger/record.ts +198 -0
- package/src/lifecycle/audited.ts +104 -0
- package/src/lifecycle/enforce.ts +55 -5
- package/src/lifecycle/erasure.ts +118 -0
- package/src/lifecycle/inactivity.ts +56 -0
- package/src/lifecycle/reason.ts +11 -0
- package/src/lifecycle/request.ts +10 -2
- package/src/lifecycle/transitions.ts +552 -93
- 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/0005_purge_once.ts +42 -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/pluginTables.ts +19 -1
- package/src/migrations/set.ts +9 -1
- package/src/processing/activities.ts +14 -0
- package/src/purge/contribution.ts +218 -0
- package/src/purge/retryPolicy.ts +26 -0
- package/src/purge/run.ts +348 -0
- package/src/purge/specs.ts +95 -0
- package/src/purge/start.ts +79 -0
- package/src/purge/workflow.ts +202 -0
- package/src/seeds/example.ts +2 -2
- package/src/test-utils/accountFootprint.ts +104 -0
- package/src/test-utils/liveApp.ts +10 -1
- package/src/token/handoff.ts +180 -0
- package/src/version.generated.ts +1 -1
|
@@ -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 };
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import { type AuthClientOptions, type AuthResult } from "./api";
|
|
4
|
+
/**
|
|
5
|
+
* The native end of a redirect sign-in. Before it starts, the app makes a verifier with
|
|
6
|
+
* {@link createHandoffVerifier} and keeps it in memory, and opens {@link nativeSignInStartURL} in the system
|
|
7
|
+
* browser's sign-in sheet with {@link handoffCallbackURL} as `callbackURL`: its own link carrying the verifier's
|
|
8
|
+
* S256 challenge. That link is best an https universal link (iOS) or app link (Android), which the system opens only
|
|
9
|
+
* in the app that proves it owns the domain; a custom scheme works too for a social sign-in, and any app can claim
|
|
10
|
+
* one. A magic link is handed off only to an https link, because whoever asks for it chooses the challenge and
|
|
11
|
+
* somebody else opens it; without a universal link, sign in by email with a one-time code. The sign-in
|
|
12
|
+
* returns to that link with a one-time `code`, never the session; the app trades the code and the verifier once,
|
|
13
|
+
* within a minute, for the raw session token, and hands that to its bearer session's `adopt`. Another app that
|
|
14
|
+
* catches the link has the code and not the verifier, so it has nothing it can trade.
|
|
15
|
+
*/
|
|
16
|
+
/** The app-link query parameter the Worker puts the one-time code in. */
|
|
17
|
+
export declare const HANDOFF_CODE_PARAM = "code";
|
|
18
|
+
/** The `callbackURL` query parameter the S256 challenge travels in. */
|
|
19
|
+
export declare const HANDOFF_CHALLENGE_PARAM = "handoff_challenge";
|
|
20
|
+
/**
|
|
21
|
+
* The two primitives a verifier needs, injected so this module reaches for no platform: on React Native,
|
|
22
|
+
* expo-crypto's `getRandomBytes` and `digest`; on the web, `crypto.getRandomValues` and `crypto.subtle.digest`.
|
|
23
|
+
*/
|
|
24
|
+
export interface HandoffCrypto {
|
|
25
|
+
/** `length` cryptographically random bytes. */
|
|
26
|
+
randomBytes(length: number): Uint8Array;
|
|
27
|
+
/** The SHA-256 digest of `data`. */
|
|
28
|
+
sha256(data: Uint8Array): Promise<ArrayBuffer>;
|
|
29
|
+
}
|
|
30
|
+
/** A verifier the app keeps to itself and the challenge it sends with the sign-in. */
|
|
31
|
+
export interface HandoffVerifier {
|
|
32
|
+
verifier: string;
|
|
33
|
+
challenge: string;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Make a fresh verifier and its S256 challenge, as RFC 7636 does: 32 random octets, base64url-encoded, is the
|
|
37
|
+
* verifier; the base64url SHA-256 of the verifier's ASCII is the challenge. Make one per sign-in.
|
|
38
|
+
*/
|
|
39
|
+
export declare function createHandoffVerifier(source: HandoffCrypto): Promise<HandoffVerifier>;
|
|
40
|
+
/** The app's link with the challenge on it: what a native sign-in passes as `callbackURL`. */
|
|
41
|
+
export declare function handoffCallbackURL(deepLink: string, challenge: string): string;
|
|
42
|
+
/**
|
|
43
|
+
* The address a native app opens in the system browser's sign-in sheet to start a redirect sign-in: the Worker's
|
|
44
|
+
* `GET {basePath}/sign-in/social/start`. Open it with `WebBrowser.openAuthSessionAsync` rather than posting
|
|
45
|
+
* `/sign-in/social` from the app: the provider's state cookie is set on this answer, so it lands in the sheet's jar,
|
|
46
|
+
* and the sheet is what comes back through the provider's callback. `callbackURL` is {@link handoffCallbackURL}'s.
|
|
47
|
+
* Null for an origin that is not a bare http(s) origin, or a `basePath` that would leave it. Built without `URL`,
|
|
48
|
+
* which React Native does not fully implement.
|
|
49
|
+
*/
|
|
50
|
+
export declare function nativeSignInStartURL(input: {
|
|
51
|
+
origin: string;
|
|
52
|
+
basePath?: string;
|
|
53
|
+
provider: string;
|
|
54
|
+
callbackURL: string;
|
|
55
|
+
errorCallbackURL?: string;
|
|
56
|
+
}): string | null;
|
|
57
|
+
/** What a trade answers: the raw session token and when the session lapses unless rotated first. */
|
|
58
|
+
export interface HandoffSession {
|
|
59
|
+
token: string;
|
|
60
|
+
expiresAt: string;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* The one-time code on the link the sign-in returned to, a custom-scheme deep link or an https universal link, or
|
|
64
|
+
* null when it carries none. Read from the query string by hand, since React Native's `URL` lacks `searchParams` on
|
|
65
|
+
* some runtimes.
|
|
66
|
+
*/
|
|
67
|
+
export declare function handoffCode(link: string): string | null;
|
|
68
|
+
/**
|
|
69
|
+
* Trade the code, with the verifier whose challenge started the sign-in, for the session. A spent, expired or
|
|
70
|
+
* unknown code, or a wrong verifier, is refused as `auth/handoff_invalid`, and the remedy is to sign in again.
|
|
71
|
+
* Pass a bearer session's `options`, so the device headers ride along.
|
|
72
|
+
*/
|
|
73
|
+
export declare function exchangeHandoff(input: {
|
|
74
|
+
code: string;
|
|
75
|
+
verifier: string;
|
|
76
|
+
}, options?: AuthClientOptions): Promise<AuthResult<HandoffSession>>;
|
|
77
|
+
//# sourceMappingURL=handoff.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"handoff.d.ts","sourceRoot":"","sources":["../../src/client/handoff.ts"],"names":[],"mappings":"AAGA,OAAO,EAEL,KAAK,iBAAiB,EACtB,KAAK,UAAU,EAIhB,MAAM,OAAO,CAAC;AAEf;;;;;;;;;;;GAWG;AAEH,yEAAyE;AACzE,eAAO,MAAM,kBAAkB,SAAS,CAAC;AAEzC,uEAAuE;AACvE,eAAO,MAAM,uBAAuB,sBAAsB,CAAC;AAE3D;;;GAGG;AACH,MAAM,WAAW,aAAa;IAC5B,+CAA+C;IAC/C,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,UAAU,CAAC;IACxC,oCAAoC;IACpC,MAAM,CAAC,IAAI,EAAE,UAAU,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC;CAChD;AAED,sFAAsF;AACtF,MAAM,WAAW,eAAe;IAC9B,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;CACnB;AAmBD;;;GAGG;AACH,wBAAsB,qBAAqB,CAAC,MAAM,EAAE,aAAa,GAAG,OAAO,CAAC,eAAe,CAAC,CAK3F;AAED,8FAA8F;AAC9F,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,CAG9E;AAED;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE;IAC1C,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B,GAAG,MAAM,GAAG,IAAI,CAYhB;AAED,oGAAoG;AACpG,MAAM,WAAW,cAAc;IAC7B,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;CACnB;AAWD;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAcvD;AAQD;;;;GAIG;AACH,wBAAgB,eAAe,CAC7B,KAAK,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,EACzC,OAAO,CAAC,EAAE,iBAAiB,GAC1B,OAAO,CAAC,UAAU,CAAC,cAAc,CAAC,CAAC,CAWrC"}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import { callAuth, isBareOrigin, isSameOriginPath } from "./api.js";
|
|
4
|
+
//#region src/client/handoff.ts
|
|
5
|
+
/**
|
|
6
|
+
* The native end of a redirect sign-in. Before it starts, the app makes a verifier with
|
|
7
|
+
* {@link createHandoffVerifier} and keeps it in memory, and opens {@link nativeSignInStartURL} in the system
|
|
8
|
+
* browser's sign-in sheet with {@link handoffCallbackURL} as `callbackURL`: its own link carrying the verifier's
|
|
9
|
+
* S256 challenge. That link is best an https universal link (iOS) or app link (Android), which the system opens only
|
|
10
|
+
* in the app that proves it owns the domain; a custom scheme works too for a social sign-in, and any app can claim
|
|
11
|
+
* one. A magic link is handed off only to an https link, because whoever asks for it chooses the challenge and
|
|
12
|
+
* somebody else opens it; without a universal link, sign in by email with a one-time code. The sign-in
|
|
13
|
+
* returns to that link with a one-time `code`, never the session; the app trades the code and the verifier once,
|
|
14
|
+
* within a minute, for the raw session token, and hands that to its bearer session's `adopt`. Another app that
|
|
15
|
+
* catches the link has the code and not the verifier, so it has nothing it can trade.
|
|
16
|
+
*/
|
|
17
|
+
/** The app-link query parameter the Worker puts the one-time code in. */
|
|
18
|
+
const HANDOFF_CODE_PARAM = "code";
|
|
19
|
+
/** The `callbackURL` query parameter the S256 challenge travels in. */
|
|
20
|
+
const HANDOFF_CHALLENGE_PARAM = "handoff_challenge";
|
|
21
|
+
const BASE64URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
|
22
|
+
/** Unpadded base64url, written out so it needs neither `btoa` nor `Buffer`. */
|
|
23
|
+
function base64Url(bytes) {
|
|
24
|
+
let out = "";
|
|
25
|
+
for (let i = 0; i < bytes.length; i += 3) {
|
|
26
|
+
const a = bytes[i] ?? 0;
|
|
27
|
+
const b = bytes[i + 1];
|
|
28
|
+
const c = bytes[i + 2];
|
|
29
|
+
out += BASE64URL[a >> 2];
|
|
30
|
+
out += BASE64URL[(a & 3) << 4 | (b ?? 0) >> 4];
|
|
31
|
+
if (b !== void 0) out += BASE64URL[(b & 15) << 2 | (c ?? 0) >> 6];
|
|
32
|
+
if (c !== void 0) out += BASE64URL[c & 63];
|
|
33
|
+
}
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Make a fresh verifier and its S256 challenge, as RFC 7636 does: 32 random octets, base64url-encoded, is the
|
|
38
|
+
* verifier; the base64url SHA-256 of the verifier's ASCII is the challenge. Make one per sign-in.
|
|
39
|
+
*/
|
|
40
|
+
async function createHandoffVerifier(source) {
|
|
41
|
+
const verifier = base64Url(source.randomBytes(32));
|
|
42
|
+
const ascii = Uint8Array.from(verifier, (char) => char.charCodeAt(0));
|
|
43
|
+
return {
|
|
44
|
+
verifier,
|
|
45
|
+
challenge: base64Url(new Uint8Array(await source.sha256(ascii)))
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
/** The app's link with the challenge on it: what a native sign-in passes as `callbackURL`. */
|
|
49
|
+
function handoffCallbackURL(deepLink, challenge) {
|
|
50
|
+
return `${deepLink}${deepLink.includes("?") ? "&" : "?"}${HANDOFF_CHALLENGE_PARAM}=${encodeURIComponent(challenge)}`;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* The address a native app opens in the system browser's sign-in sheet to start a redirect sign-in: the Worker's
|
|
54
|
+
* `GET {basePath}/sign-in/social/start`. Open it with `WebBrowser.openAuthSessionAsync` rather than posting
|
|
55
|
+
* `/sign-in/social` from the app: the provider's state cookie is set on this answer, so it lands in the sheet's jar,
|
|
56
|
+
* and the sheet is what comes back through the provider's callback. `callbackURL` is {@link handoffCallbackURL}'s.
|
|
57
|
+
* Null for an origin that is not a bare http(s) origin, or a `basePath` that would leave it. Built without `URL`,
|
|
58
|
+
* which React Native does not fully implement.
|
|
59
|
+
*/
|
|
60
|
+
function nativeSignInStartURL(input) {
|
|
61
|
+
const rooted = `${input.basePath ?? "/auth"}/sign-in/social/start`;
|
|
62
|
+
if (!isBareOrigin(input.origin) || !isSameOriginPath(rooted)) return null;
|
|
63
|
+
const query = [
|
|
64
|
+
["provider", input.provider],
|
|
65
|
+
["callbackURL", input.callbackURL],
|
|
66
|
+
["errorCallbackURL", input.errorCallbackURL]
|
|
67
|
+
].filter((pair) => pair[1] !== void 0).map(([name, value]) => `${name}=${encodeURIComponent(value)}`).join("&");
|
|
68
|
+
return `${input.origin}${rooted}?${query}`;
|
|
69
|
+
}
|
|
70
|
+
/** One query-string component, decoded as `application/x-www-form-urlencoded` does, or null when it is not valid. */
|
|
71
|
+
function decodeQueryComponent(raw) {
|
|
72
|
+
try {
|
|
73
|
+
return decodeURIComponent(raw.replaceAll("+", " "));
|
|
74
|
+
} catch {
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* The one-time code on the link the sign-in returned to, a custom-scheme deep link or an https universal link, or
|
|
80
|
+
* null when it carries none. Read from the query string by hand, since React Native's `URL` lacks `searchParams` on
|
|
81
|
+
* some runtimes.
|
|
82
|
+
*/
|
|
83
|
+
function handoffCode(link) {
|
|
84
|
+
const fragmentStart = link.indexOf("#");
|
|
85
|
+
const beforeFragment = fragmentStart === -1 ? link : link.slice(0, fragmentStart);
|
|
86
|
+
const queryStart = beforeFragment.indexOf("?");
|
|
87
|
+
if (queryStart === -1) return null;
|
|
88
|
+
const query = beforeFragment.slice(queryStart + 1);
|
|
89
|
+
for (const pair of query.split("&")) {
|
|
90
|
+
const equals = pair.indexOf("=");
|
|
91
|
+
if (equals === -1) continue;
|
|
92
|
+
if (decodeQueryComponent(pair.slice(0, equals)) !== "code") continue;
|
|
93
|
+
const code = decodeQueryComponent(pair.slice(equals + 1));
|
|
94
|
+
return code ? code : null;
|
|
95
|
+
}
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
function isHandoffSession(value) {
|
|
99
|
+
if (typeof value !== "object" || value === null) return false;
|
|
100
|
+
const record = value;
|
|
101
|
+
return typeof record.token === "string" && record.token.length > 0 && typeof record.expiresAt === "string";
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Trade the code, with the verifier whose challenge started the sign-in, for the session. A spent, expired or
|
|
105
|
+
* unknown code, or a wrong verifier, is refused as `auth/handoff_invalid`, and the remedy is to sign in again.
|
|
106
|
+
* Pass a bearer session's `options`, so the device headers ride along.
|
|
107
|
+
*/
|
|
108
|
+
function exchangeHandoff(input, options) {
|
|
109
|
+
return callAuth("/handoff", {
|
|
110
|
+
method: "POST",
|
|
111
|
+
headers: { "content-type": "application/json" },
|
|
112
|
+
body: JSON.stringify({
|
|
113
|
+
code: input.code,
|
|
114
|
+
verifier: input.verifier
|
|
115
|
+
})
|
|
116
|
+
}, options, isHandoffSession);
|
|
117
|
+
}
|
|
118
|
+
//#endregion
|
|
119
|
+
export { HANDOFF_CHALLENGE_PARAM, HANDOFF_CODE_PARAM, createHandoffVerifier, exchangeHandoff, handoffCallbackURL, handoffCode, nativeSignInStartURL };
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import { type AuthClientOptions, type AuthResult } from "./api";
|
|
4
|
+
/**
|
|
5
|
+
* The browser half of the MCP capability's two screens: the consent screen and connected applications.
|
|
6
|
+
*
|
|
7
|
+
* Every call goes through {@link callAuth}, the one producer of a same-origin request, with the base path pointed
|
|
8
|
+
* at the MCP endpoint instead of auth's. **Zod-free**, like everything on this side of the wire: each answer is
|
|
9
|
+
* narrowed by a hand-written guard, because this compiles into an adopter's browser bundle.
|
|
10
|
+
*/
|
|
11
|
+
/** Where the MCP capability mounts unless configured otherwise. */
|
|
12
|
+
export declare const MCP_BASE_PATH = "/mcp";
|
|
13
|
+
/** One operation a consent row lists. */
|
|
14
|
+
export interface ConsentOperation {
|
|
15
|
+
readonly tool: string;
|
|
16
|
+
readonly summary: string;
|
|
17
|
+
readonly effect: "writes" | "sends" | "charges" | "deletes" | null;
|
|
18
|
+
}
|
|
19
|
+
/** One capability, as the unit of consent. */
|
|
20
|
+
export interface ConsentCapability {
|
|
21
|
+
readonly capability: string;
|
|
22
|
+
readonly operations: readonly ConsentOperation[];
|
|
23
|
+
readonly reachable: number;
|
|
24
|
+
readonly total: number;
|
|
25
|
+
readonly effects: {
|
|
26
|
+
readonly writes: number;
|
|
27
|
+
readonly sends: number;
|
|
28
|
+
readonly charges: number;
|
|
29
|
+
readonly deletes: number;
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
/** Everything the consent screen shows. See the server's `ConsentView`. */
|
|
33
|
+
export interface ConsentView {
|
|
34
|
+
readonly client: {
|
|
35
|
+
readonly id: string;
|
|
36
|
+
/** The host its metadata document proved it by. Absent or `null` when nothing verified it. */
|
|
37
|
+
readonly verifiedHost?: string | null;
|
|
38
|
+
readonly reportedName: string | null;
|
|
39
|
+
readonly reportedUri: string | null;
|
|
40
|
+
readonly redirectUri: string;
|
|
41
|
+
};
|
|
42
|
+
readonly capabilities: readonly ConsentCapability[];
|
|
43
|
+
readonly requested: readonly {
|
|
44
|
+
readonly scope: string;
|
|
45
|
+
readonly granted: boolean;
|
|
46
|
+
readonly reason: "role" | "unknown" | null;
|
|
47
|
+
}[];
|
|
48
|
+
}
|
|
49
|
+
/** One application acting as the user. */
|
|
50
|
+
export interface ConnectedApplication {
|
|
51
|
+
readonly clientId: string;
|
|
52
|
+
/** The host its metadata document proved it by. Absent or `null` when nothing verified it. */
|
|
53
|
+
readonly verifiedHost?: string | null;
|
|
54
|
+
readonly reportedName: string | null;
|
|
55
|
+
readonly redirectUris: readonly string[];
|
|
56
|
+
readonly approvedAt: string;
|
|
57
|
+
}
|
|
58
|
+
/** What the application asking for access will be able to do. `oauthQuery` is the screen's own query string. */
|
|
59
|
+
export declare function readConsent(oauthQuery: string, options?: AuthClientOptions): Promise<AuthResult<ConsentView>>;
|
|
60
|
+
/** The one decision. Answers where to send the browser: the application's redirect, with a code or a refusal. */
|
|
61
|
+
export declare function decideConsent(oauthQuery: string, accept: boolean, options?: AuthClientOptions): Promise<AuthResult<{
|
|
62
|
+
redirect: string;
|
|
63
|
+
}>>;
|
|
64
|
+
/** Every application acting as the signed-in user, newest first. */
|
|
65
|
+
export declare function listConnectedApplications(options?: AuthClientOptions): Promise<AuthResult<readonly ConnectedApplication[]>>;
|
|
66
|
+
/** Revoke one. Its next call is refused. */
|
|
67
|
+
export declare function revokeConnectedApplication(clientId: string, options?: AuthClientOptions): Promise<AuthResult<{
|
|
68
|
+
revoked: true;
|
|
69
|
+
}>>;
|
|
70
|
+
//# sourceMappingURL=mcp.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcp.d.ts","sourceRoot":"","sources":["../../src/client/mcp.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,iBAAiB,EAAE,KAAK,UAAU,EAAY,MAAM,OAAO,CAAC;AAE1E;;;;;;GAMG;AAEH,mEAAmE;AACnE,eAAO,MAAM,aAAa,SAAS,CAAC;AAEpC,yCAAyC;AACzC,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,MAAM,EAAE,QAAQ,GAAG,OAAO,GAAG,SAAS,GAAG,SAAS,GAAG,IAAI,CAAC;CACpE;AAED,8CAA8C;AAC9C,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,UAAU,EAAE,SAAS,gBAAgB,EAAE,CAAC;IACjD,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,OAAO,EAAE;QAChB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;QACxB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;QACvB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;QACzB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;KAC1B,CAAC;CACH;AAED,2EAA2E;AAC3E,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,MAAM,EAAE;QACf,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;QACpB,8FAA8F;QAC9F,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;QACtC,QAAQ,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;QACrC,QAAQ,CAAC,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;QACpC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;KAC9B,CAAC;IACF,QAAQ,CAAC,YAAY,EAAE,SAAS,iBAAiB,EAAE,CAAC;IACpD,QAAQ,CAAC,SAAS,EAAE,SAAS;QAC3B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;QACvB,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;QAC1B,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,CAAC;KAC5C,EAAE,CAAC;CACL;AAED,0CAA0C;AAC1C,MAAM,WAAW,oBAAoB;IACnC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,8FAA8F;IAC9F,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACtC,QAAQ,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IACrC,QAAQ,CAAC,YAAY,EAAE,SAAS,MAAM,EAAE,CAAC;IACzC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;CAC7B;AAsCD,gHAAgH;AAChH,wBAAgB,WAAW,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,iBAAiB,GAAG,OAAO,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC,CAG7G;AAED,iHAAiH;AACjH,wBAAgB,aAAa,CAC3B,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,OAAO,EACf,OAAO,CAAC,EAAE,iBAAiB,GAC1B,OAAO,CAAC,UAAU,CAAC;IAAE,QAAQ,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC,CAW3C;AAED,oEAAoE;AACpE,wBAAsB,yBAAyB,CAC7C,OAAO,CAAC,EAAE,iBAAiB,GAC1B,OAAO,CAAC,UAAU,CAAC,SAAS,oBAAoB,EAAE,CAAC,CAAC,CAGtD;AAED,4CAA4C;AAC5C,wBAAgB,0BAA0B,CACxC,QAAQ,EAAE,MAAM,EAChB,OAAO,CAAC,EAAE,iBAAiB,GAC1B,OAAO,CAAC,UAAU,CAAC;IAAE,OAAO,EAAE,IAAI,CAAA;CAAE,CAAC,CAAC,CAExC"}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import { callAuth } from "./api.js";
|
|
4
|
+
//#region src/client/mcp.ts
|
|
5
|
+
/**
|
|
6
|
+
* The browser half of the MCP capability's two screens: the consent screen and connected applications.
|
|
7
|
+
*
|
|
8
|
+
* Every call goes through {@link callAuth}, the one producer of a same-origin request, with the base path pointed
|
|
9
|
+
* at the MCP endpoint instead of auth's. **Zod-free**, like everything on this side of the wire: each answer is
|
|
10
|
+
* narrowed by a hand-written guard, because this compiles into an adopter's browser bundle.
|
|
11
|
+
*/
|
|
12
|
+
/** Where the MCP capability mounts unless configured otherwise. */
|
|
13
|
+
const MCP_BASE_PATH = "/mcp";
|
|
14
|
+
function isRecord(value) {
|
|
15
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
16
|
+
}
|
|
17
|
+
function isConsentView(value) {
|
|
18
|
+
return isRecord(value) && isRecord(value.client) && typeof value.client.id === "string" && typeof value.client.redirectUri === "string" && Array.isArray(value.capabilities) && Array.isArray(value.requested);
|
|
19
|
+
}
|
|
20
|
+
function isDecision(value) {
|
|
21
|
+
return isRecord(value) && typeof value.redirect === "string";
|
|
22
|
+
}
|
|
23
|
+
function isConnections(value) {
|
|
24
|
+
return isRecord(value) && Array.isArray(value.applications) && value.applications.every((entry) => isRecord(entry) && typeof entry.clientId === "string");
|
|
25
|
+
}
|
|
26
|
+
function isRevoked(value) {
|
|
27
|
+
return isRecord(value) && value.revoked === true;
|
|
28
|
+
}
|
|
29
|
+
/** The options a call runs with: the MCP base path, unless the caller named another. */
|
|
30
|
+
function mcpOptions(options) {
|
|
31
|
+
return {
|
|
32
|
+
...options,
|
|
33
|
+
basePath: options?.basePath ?? "/mcp"
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
/** What the application asking for access will be able to do. `oauthQuery` is the screen's own query string. */
|
|
37
|
+
function readConsent(oauthQuery, options) {
|
|
38
|
+
const query = new URLSearchParams({ oauth_query: oauthQuery.replace(/^\?/, "") });
|
|
39
|
+
return callAuth(`/consent?${query}`, { method: "GET" }, mcpOptions(options), isConsentView);
|
|
40
|
+
}
|
|
41
|
+
/** The one decision. Answers where to send the browser: the application's redirect, with a code or a refusal. */
|
|
42
|
+
function decideConsent(oauthQuery, accept, options) {
|
|
43
|
+
return callAuth("/consent", {
|
|
44
|
+
method: "POST",
|
|
45
|
+
headers: { "content-type": "application/json" },
|
|
46
|
+
body: JSON.stringify({
|
|
47
|
+
oauth_query: oauthQuery.replace(/^\?/, ""),
|
|
48
|
+
accept
|
|
49
|
+
})
|
|
50
|
+
}, mcpOptions(options), isDecision);
|
|
51
|
+
}
|
|
52
|
+
/** Every application acting as the signed-in user, newest first. */
|
|
53
|
+
async function listConnectedApplications(options) {
|
|
54
|
+
const result = await callAuth("/connections", { method: "GET" }, mcpOptions(options), isConnections);
|
|
55
|
+
return result.ok ? {
|
|
56
|
+
ok: true,
|
|
57
|
+
value: result.value.applications
|
|
58
|
+
} : result;
|
|
59
|
+
}
|
|
60
|
+
/** Revoke one. Its next call is refused. */
|
|
61
|
+
function revokeConnectedApplication(clientId, options) {
|
|
62
|
+
return callAuth(`/connections/${encodeURIComponent(clientId)}`, { method: "DELETE" }, mcpOptions(options), isRevoked);
|
|
63
|
+
}
|
|
64
|
+
//#endregion
|
|
65
|
+
export { MCP_BASE_PATH, decideConsent, listConnectedApplications, readConsent, revokeConnectedApplication };
|
|
@@ -4,8 +4,8 @@ import { z } from "zod";
|
|
|
4
4
|
/** `pithy_auth_users` — one end user. Text/UUID id (anti-enumeration); email is unique. */
|
|
5
5
|
export declare const User: z.ZodObject<{
|
|
6
6
|
id: z.ZodString;
|
|
7
|
-
name: z.ZodString
|
|
8
|
-
email: z.ZodString
|
|
7
|
+
name: import("@pithy-sh/core/src/privacy/classes").Marked<z.ZodString, "pii">;
|
|
8
|
+
email: import("@pithy-sh/core/src/privacy/classes").Marked<z.ZodString, "pii">;
|
|
9
9
|
emailVerified: z.ZodCodec<z.ZodUnion<readonly [z.ZodLiteral<0>, z.ZodLiteral<1>, z.ZodBoolean, z.ZodString]>, z.ZodBoolean>;
|
|
10
10
|
image: z.ZodNullable<z.ZodString>;
|
|
11
11
|
locale: z.ZodNullable<z.ZodString>;
|
|
@@ -15,6 +15,7 @@ export declare const User: z.ZodObject<{
|
|
|
15
15
|
suspendedUntil: z.ZodOptional<z.ZodNullable<z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>>>;
|
|
16
16
|
deletedAt: z.ZodOptional<z.ZodNullable<z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>>>;
|
|
17
17
|
purgeAfter: z.ZodOptional<z.ZodNullable<z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>>>;
|
|
18
|
+
lastActiveAt: z.ZodOptional<z.ZodNullable<z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>>>;
|
|
18
19
|
}, z.core.$strip>;
|
|
19
20
|
export type User = z.output<typeof User>;
|
|
20
21
|
/** `pithy_auth_sessions` — one active session (the long-lived, bearer/cookie credential). */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"betterAuth.d.ts","sourceRoot":"","sources":["../../src/data/betterAuth.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"betterAuth.d.ts","sourceRoot":"","sources":["../../src/data/betterAuth.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAuBxB,2FAA2F;AAC3F,eAAO,MAAM,IAAI;;;;;;;;;;;;;;iBAiDwF,CAAC;AAC1G,MAAM,MAAM,IAAI,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,IAAI,CAAC,CAAC;AAEzC,6FAA6F;AAC7F,eAAO,MAAM,OAAO;;;;;;;;;;;;iBAqCqF,CAAC;AAC1G,MAAM,MAAM,OAAO,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,OAAO,CAAC,CAAC;AAE/C,mGAAmG;AACnG,eAAO,MAAM,OAAO;;;;;;;;;;;;;;;iBA0CqF,CAAC;AAC1G,MAAM,MAAM,OAAO,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,OAAO,CAAC,CAAC;AAE/C,8FAA8F;AAC9F,eAAO,MAAM,YAAY;;;;;;;iBAmBtB,CAAC;AACJ,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,YAAY,CAAC,CAAC;AAEzD,gGAAgG;AAChG,eAAO,MAAM,IAAI;;;;;;;;iBA8Bd,CAAC;AACJ,MAAM,MAAM,IAAI,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,IAAI,CAAC,CAAC;AAEzC,sHAAsH;AACtH,eAAO,MAAM,SAAS;;;;;iBAcnB,CAAC;AACJ,MAAM,MAAM,SAAS,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,SAAS,CAAC,CAAC"}
|
package/dist/data/betterAuth.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
import { z } from "zod";
|
|
4
4
|
import { JsonDate, SQLiteBoolean, SQLiteDate } from "@pithy-sh/core/src/data/codecs";
|
|
5
5
|
import { Locale } from "@pithy-sh/core/src/i18n/locale";
|
|
6
|
+
import { pii } from "@pithy-sh/core/src/privacy/classes";
|
|
6
7
|
//#region src/data/betterAuth.ts
|
|
7
8
|
/**
|
|
8
9
|
* The Better-Auth-managed tables, one Zod object per table.
|
|
@@ -26,8 +27,8 @@ const BetterAuthDate = JsonDate;
|
|
|
26
27
|
/** `pithy_auth_users` — one end user. Text/UUID id (anti-enumeration); email is unique. */
|
|
27
28
|
const User = z.object({
|
|
28
29
|
id: z.string().describe("Primary key. A random/UUID text id (not auto-increment) so users cannot be enumerated."),
|
|
29
|
-
name: z.string().describe("The user's display name, supplied by the provider profile or at sign-up."),
|
|
30
|
-
email: z.string().describe("The user's email address. Unique across all users; the identity key for passwordless sign-in."),
|
|
30
|
+
name: pii(z.string()).describe("The user's display name, supplied by the provider profile or at sign-up."),
|
|
31
|
+
email: pii(z.string()).describe("The user's email address. Unique across all users; the identity key for passwordless sign-in."),
|
|
31
32
|
emailVerified: SQLiteBoolean.describe("Whether the email has been verified. Stored as `0|1`; magic-link/OTP sign-in sets it true."),
|
|
32
33
|
image: z.string().nullable().describe("The user's picture: a URL on the provider that signed them in, or bytes this application stores as a bounded `data:` URL — see `../profile/profile.ts` for why the column takes two shapes. Null when nobody has set one, and then a caller draws initials, which is a real answer and not a placeholder.\n\n**Permissive here and strict on the write, exactly as `name` is, and the asymmetry is the point.** `UserImage` runs at the database hook, so nothing this kit writes can put an unacceptable value in the column. What this schema decodes is what is *already there* — a row a provider wrote before the rule existed, a repair script, a restored backup. A strict column turns one such row into a `ZodError` on every read that touches it, and `getUsers` parses a page of rows at once: one poisoned row would take down the whole roster for every operator rather than drawing one gap. That is the failure mode `./kitFields.ts` records for `locale`, and it is worse here, because a roster is read by people who did not write the row.\n\nThe value is made safe on the way **out** instead. `userImageSource` answers null for anything the rule does not recognize, so an unrecognized value renders as initials; and the serving route refuses to hand out bytes it cannot type."),
|
|
33
34
|
locale: Locale.nullable().describe("The reader's chosen language as a BCP-47 tag, or null when they have never chosen. Null is not the default locale: it means negotiate from `Accept-Language`, so an unchosen reader follows their device. A stored tag outranks the header."),
|
|
@@ -36,7 +37,8 @@ const User = z.object({
|
|
|
36
37
|
suspendedAt: SQLiteDate.nullish().describe("When this account was suspended, or null when it is not. A suspended account cannot sign in, refresh a token, or act on any route. Ms-epoch in SQLite; a `Date` in app code."),
|
|
37
38
|
suspendedUntil: SQLiteDate.nullish().describe("When the current suspension ends by itself, or null for one that lasts until an operator reinstates the account. A suspension past this instant is treated as absent, with no write needed to expire it. Ms-epoch in SQLite."),
|
|
38
39
|
deletedAt: SQLiteDate.nullish().describe("When this account was deleted, or null when it is not. A deleted account cannot sign in or act, and can be restored until `purgeAfter`. Ms-epoch in SQLite."),
|
|
39
|
-
purgeAfter: SQLiteDate.nullish().describe("When a deleted account's data may be erased — the deletion instant plus `retention.purgeAfterDays`. Null unless the account is deleted. Ms-epoch in SQLite.")
|
|
40
|
+
purgeAfter: SQLiteDate.nullish().describe("When a deleted account's data may be erased — the deletion instant plus `retention.purgeAfterDays`. Null unless the account is deleted. Ms-epoch in SQLite."),
|
|
41
|
+
lastActiveAt: SQLiteDate.nullish().describe("When this account last opened a session — a sign-in or a token refresh — which a sign-out does not erase. The retention policy's class ages count inactivity from it. Stamped on every existing account when the column arrived. Ms-epoch in SQLite.")
|
|
40
42
|
}).describe("A user in `pithy_auth_users` — the canonical identity every session and account hangs off.");
|
|
41
43
|
/** `pithy_auth_sessions` — one active session (the long-lived, bearer/cookie credential). */
|
|
42
44
|
const Session = z.object({
|