@superintelligentfamily/key-handler 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/lib/index.d.ts +64 -0
- package/lib/index.js +301 -0
- package/lib/store.d.ts +44 -0
- package/lib/store.js +51 -0
- package/package.json +34 -3
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Seth Shoultes
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/lib/index.d.ts
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { type VerifierOptions } from "@superintelligentfamily/key-verify";
|
|
2
|
+
import type { SessionStore } from "./store.js";
|
|
3
|
+
export { D1_SCHEMA, d1Store, type D1Like, type SessionStore, type StoredSession } from "./store.js";
|
|
4
|
+
export declare const PACKAGE_NAME = "@superintelligentfamily/key-handler";
|
|
5
|
+
export interface HandlerOptions {
|
|
6
|
+
/** Key's issuer, e.g. https://auth.superintelligentkey.com. */
|
|
7
|
+
issuer: string;
|
|
8
|
+
/** This app's id and one of its secret keys (the server's own env, never the browser's). */
|
|
9
|
+
clientId: string;
|
|
10
|
+
clientSecret: string;
|
|
11
|
+
/** This app's origin, e.g. https://app.example: the callback and the Origin every POST must carry. */
|
|
12
|
+
origin: string;
|
|
13
|
+
/** Where the handler is mounted, e.g. /api/doorman. */
|
|
14
|
+
mount: string;
|
|
15
|
+
store: SessionStore;
|
|
16
|
+
/** 32 random bytes, base64url: the AES-GCM key both tokens are sealed with in the store. */
|
|
17
|
+
sealKey: string;
|
|
18
|
+
/** Where verify reads the revocation marker (DESIGN §5.4). */
|
|
19
|
+
markers: VerifierOptions["markers"];
|
|
20
|
+
/** The scope the sign-in asks for: "openid profile" by default. Key's dashboard adds the platform scopes (doorman#66). */
|
|
21
|
+
scope?: string;
|
|
22
|
+
/** An RFC 8707 resource, e.g. the Key API's https://api.superintelligentkey.com/v1 (auth's API_RESOURCE, matched
|
|
23
|
+
* exactly): the access token's audience is then that URL, and is checked as such, with no plans claim; the ID token
|
|
24
|
+
* stays this app's. Key allows it for its own platform app only. Sent on /authorize; Key keeps it with the grant. */
|
|
25
|
+
resource?: string;
|
|
26
|
+
/** false: POST <mount>/token answers 404, so no page script can read the access token, and the server takes it with
|
|
27
|
+
* accessTokenFor(req). For a token that writes with no confirm step (Key's dashboard, doorman#66). Default true. */
|
|
28
|
+
exposeToken?: boolean;
|
|
29
|
+
now?: () => number;
|
|
30
|
+
fetch?: typeof fetch;
|
|
31
|
+
}
|
|
32
|
+
/** What accessTokenFor gives the app's server: the live token, or why there is none. */
|
|
33
|
+
export type AccessToken = {
|
|
34
|
+
access_token: string;
|
|
35
|
+
expires_at: number;
|
|
36
|
+
} | {
|
|
37
|
+
error: "signed_out" | "unavailable" | "retry";
|
|
38
|
+
};
|
|
39
|
+
export declare const SESSION_COOKIE = "__Host-dm_app";
|
|
40
|
+
/** The sign-in round trip: 10 minutes. */
|
|
41
|
+
export declare const AUTH_TTL = 600;
|
|
42
|
+
/** A stored access token is returned while more than this is left; nearer its end it is refreshed. */
|
|
43
|
+
export declare const EARLY = 60;
|
|
44
|
+
/** A refresh holds the row this long; a second caller meanwhile waits for it. */
|
|
45
|
+
export declare const LEASE = 10;
|
|
46
|
+
/** A session lasts as long as its refresh token (DESIGN §3.2: 30 days, sliding). */
|
|
47
|
+
export declare const SESSION_TTL: number;
|
|
48
|
+
/** The page's cosmetic profile (DESIGN §6.1), the same cookie doorman.js and @superintelligentfamily/key-react read: who is signed in, to
|
|
49
|
+
* show, never to grant anything. Script-readable on purpose; a visitor can forge it, and no route of this handler reads it. */
|
|
50
|
+
export declare const PROFILE_COOKIE = "dm_profile";
|
|
51
|
+
/** A path on this site only, so the return can't leave the app: no control characters or spaces (browsers drop tabs
|
|
52
|
+
* and newlines, so "/\t/evil" would become "//evil"), no backslash, and the path resolved against the app's origin
|
|
53
|
+
* must keep that origin, and the normalised result must still be a single-slash path. With `mount`, a path at or under
|
|
54
|
+
* the handler's own mount is refused too, decoded and in any case: returning to sign-in would loop through Key
|
|
55
|
+
* (doorman#92, Fable's note on site-kit#298). Else "/". */
|
|
56
|
+
export declare function safePath(p: string | null, origin: string, mount?: string): string;
|
|
57
|
+
/** dm_profile's value: base64url JSON {n, p, s}, the name (100 characters at most) and an https picture from the verified
|
|
58
|
+
* ID token, and s, random per sign-in, so two accounts with the same name and no picture never look alike to the page
|
|
59
|
+
* (mi-dev-2 on #75: @superintelligentfamily/key-react keys its cached token on this value). Over doorman.js's 1 KB cap without the
|
|
60
|
+
* picture, so the page never ignores the whole cookie. */
|
|
61
|
+
export declare function profileValue(name: unknown, picture: unknown, s: string): string;
|
|
62
|
+
export declare function createHandler(o: HandlerOptions): ((req: Request) => Promise<Response>) & {
|
|
63
|
+
accessTokenFor: (req: Request) => Promise<AccessToken>;
|
|
64
|
+
};
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
// @superintelligentfamily/key-handler (DESIGN §5.3): Key sign-in for an app with a server. Mounted where the app chooses (for example
|
|
2
|
+
// /api/doorman), it answers four routes:
|
|
3
|
+
// GET <mount>/sign-in?return_to= to Key's /authorize, with state, nonce and PKCE in a __Host- cookie of its own
|
|
4
|
+
// GET <mount>/callback the code to tokens; a new ses_ row in the SessionStore, __Host-dm_app = its id, and
|
|
5
|
+
// dm_profile, the cosmetic name and picture the page shows (DESIGN §6.1)
|
|
6
|
+
// POST <mount>/token the live access token, after the revocation marker (Fable on doorman#55); else a
|
|
7
|
+
// refresh under a lease, so one refresh wins and the loser re-reads or gets a 409
|
|
8
|
+
// POST <mount>/signout the row deleted and both cookies cleared, then Key's end_session
|
|
9
|
+
// The app's origin comes from its config, never from a request header (X-Forwarded-Host and the like).
|
|
10
|
+
import { createVerifier, Revoked, TokenExpired, TokenInvalid, TokenMissing } from "@superintelligentfamily/key-verify";
|
|
11
|
+
export { D1_SCHEMA, d1Store } from "./store.js";
|
|
12
|
+
export const PACKAGE_NAME = "@superintelligentfamily/key-handler";
|
|
13
|
+
export const SESSION_COOKIE = "__Host-dm_app";
|
|
14
|
+
/** The sign-in round trip: 10 minutes. */
|
|
15
|
+
export const AUTH_TTL = 600;
|
|
16
|
+
/** A stored access token is returned while more than this is left; nearer its end it is refreshed. */
|
|
17
|
+
export const EARLY = 60;
|
|
18
|
+
/** A refresh holds the row this long; a second caller meanwhile waits for it. */
|
|
19
|
+
export const LEASE = 10;
|
|
20
|
+
/** A session lasts as long as its refresh token (DESIGN §3.2: 30 days, sliding). */
|
|
21
|
+
export const SESSION_TTL = 30 * 86400;
|
|
22
|
+
/** The page's cosmetic profile (DESIGN §6.1), the same cookie doorman.js and @superintelligentfamily/key-react read: who is signed in, to
|
|
23
|
+
* show, never to grant anything. Script-readable on purpose; a visitor can forge it, and no route of this handler reads it. */
|
|
24
|
+
export const PROFILE_COOKIE = "dm_profile";
|
|
25
|
+
const enc = new TextEncoder();
|
|
26
|
+
const b64url = (b) => btoa(String.fromCharCode(...b)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
27
|
+
const unb64url = (s) => Uint8Array.from(atob(s.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));
|
|
28
|
+
const random = (n = 32) => b64url(crypto.getRandomValues(new Uint8Array(n)));
|
|
29
|
+
const sha256 = async (s) => b64url(new Uint8Array(await crypto.subtle.digest("SHA-256", enc.encode(s))));
|
|
30
|
+
const s256 = sha256; // PKCE's S256 is base64url(sha256(verifier))
|
|
31
|
+
function cookieOf(req, name) {
|
|
32
|
+
for (const part of (req.headers.get("cookie") ?? "").split(";")) {
|
|
33
|
+
const i = part.indexOf("=");
|
|
34
|
+
if (i > 0 && part.slice(0, i).trim() === name)
|
|
35
|
+
return part.slice(i + 1).trim();
|
|
36
|
+
}
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
const setCookie = (name, value, maxAge) => `${name}=${value}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=${maxAge}`;
|
|
40
|
+
const text = (status, body, headers = {}) => new Response(body, { status, headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store", ...headers } });
|
|
41
|
+
const json = (status, body, headers = {}) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", "cache-control": "no-store", ...headers } });
|
|
42
|
+
/** A path on this site only, so the return can't leave the app: no control characters or spaces (browsers drop tabs
|
|
43
|
+
* and newlines, so "/\t/evil" would become "//evil"), no backslash, and the path resolved against the app's origin
|
|
44
|
+
* must keep that origin, and the normalised result must still be a single-slash path. With `mount`, a path at or under
|
|
45
|
+
* the handler's own mount is refused too, decoded and in any case: returning to sign-in would loop through Key
|
|
46
|
+
* (doorman#92, Fable's note on site-kit#298). Else "/". */
|
|
47
|
+
export function safePath(p, origin, mount) {
|
|
48
|
+
if (!p || !p.startsWith("/") || [...p].some((c) => c <= " " || c === "\x7f" || c === "\\"))
|
|
49
|
+
return "/";
|
|
50
|
+
try {
|
|
51
|
+
const u = new URL(p, origin), out = u.pathname + u.search + u.hash;
|
|
52
|
+
// The normalised result is checked too: "/.//evil" resolves on this origin to "//evil", which a browser reads as a host.
|
|
53
|
+
if (u.origin !== origin || out.startsWith("//") || out.includes("\\"))
|
|
54
|
+
return "/";
|
|
55
|
+
const path = decodeURIComponent(u.pathname).toLowerCase(), m = mount?.toLowerCase();
|
|
56
|
+
return m && (path === m || path.startsWith(`${m}/`)) ? "/" : out;
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return "/";
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/** dm_profile's value: base64url JSON {n, p, s}, the name (100 characters at most) and an https picture from the verified
|
|
63
|
+
* ID token, and s, random per sign-in, so two accounts with the same name and no picture never look alike to the page
|
|
64
|
+
* (mi-dev-2 on #75: @superintelligentfamily/key-react keys its cached token on this value). Over doorman.js's 1 KB cap without the
|
|
65
|
+
* picture, so the page never ignores the whole cookie. */
|
|
66
|
+
export function profileValue(name, picture, s) {
|
|
67
|
+
const n = typeof name === "string" ? [...name].slice(0, 100).join("") : "";
|
|
68
|
+
let p = null;
|
|
69
|
+
if (typeof picture === "string") {
|
|
70
|
+
try {
|
|
71
|
+
const u = new URL(picture);
|
|
72
|
+
if (u.protocol === "https:")
|
|
73
|
+
p = u.href;
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
p = null;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
const value = (o) => b64url(enc.encode(JSON.stringify(o)));
|
|
80
|
+
const full = value(p ? { n, p, s } : { n, s });
|
|
81
|
+
return full.length <= 1024 ? full : value({ n, s });
|
|
82
|
+
}
|
|
83
|
+
const profileCookie = (value, maxAge) => `${PROFILE_COOKIE}=${value}; Path=/; Secure; SameSite=Lax; Max-Age=${maxAge}`;
|
|
84
|
+
export function createHandler(o) {
|
|
85
|
+
// Checked once, here: an origin with a path, a trailing slash or capitals would 403 every POST (Fable on #57).
|
|
86
|
+
if (new URL(o.origin).origin !== o.origin)
|
|
87
|
+
throw new TypeError(`origin must be a bare origin like https://app.example, not ${o.origin}`);
|
|
88
|
+
if (!/^\/[A-Za-z0-9._~-]+(\/[A-Za-z0-9._~-]+)*$/.test(o.mount))
|
|
89
|
+
throw new TypeError(`mount must be a path like /api/doorman, with no trailing slash, not ${o.mount}`);
|
|
90
|
+
const now = o.now ?? (() => Math.floor(Date.now() / 1000));
|
|
91
|
+
const get = o.fetch ?? ((...a) => fetch(...a));
|
|
92
|
+
const idV = createVerifier({ issuer: o.issuer, audience: o.clientId, markers: o.markers, now, fetch: get });
|
|
93
|
+
// The access token's own audience: the resource's URL when one is asked for, with the marker still read as this app.
|
|
94
|
+
const v = o.resource === undefined ? idV
|
|
95
|
+
: createVerifier({ issuer: o.issuer, audience: o.resource, markerClient: o.clientId, planless: true, markers: o.markers, now, fetch: get });
|
|
96
|
+
const callback = `${o.origin}${o.mount}/callback`;
|
|
97
|
+
const basic = `Basic ${btoa(`${encodeURIComponent(o.clientId)}:${encodeURIComponent(o.clientSecret)}`)}`;
|
|
98
|
+
let key = null;
|
|
99
|
+
const aes = () => (key ??= crypto.subtle.importKey("raw", unb64url(o.sealKey), "AES-GCM", false, ["encrypt", "decrypt"]));
|
|
100
|
+
const seal = async (s) => {
|
|
101
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
102
|
+
const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv }, await aes(), enc.encode(s)));
|
|
103
|
+
return `${b64url(iv)}.${b64url(ct)}`;
|
|
104
|
+
};
|
|
105
|
+
const open = async (s) => {
|
|
106
|
+
const [iv = "", ct = ""] = s.split(".");
|
|
107
|
+
return new TextDecoder().decode(await crypto.subtle.decrypt({ name: "AES-GCM", iv: unb64url(iv) }, await aes(), unb64url(ct)));
|
|
108
|
+
};
|
|
109
|
+
const sameOrigin = (req) => req.headers.get("origin") === o.origin;
|
|
110
|
+
const clearSession = setCookie(SESSION_COOKIE, "", 0);
|
|
111
|
+
const clearProfile = profileCookie("", 0);
|
|
112
|
+
/** Key's /token, as this app (Basic). "refused" only when Key says the grant is no good (invalid_grant); anything
|
|
113
|
+
* else that isn't tokens is "unavailable", which keeps the session (Fable on #57: one busy minute at Key must not sign
|
|
114
|
+
* everyone out). invalid_client is the app's own secret, rotated or mistyped: every session would end at once, so it
|
|
115
|
+
* keeps them too, and the 503s say to fix the secret. */
|
|
116
|
+
async function token(fields) {
|
|
117
|
+
let res;
|
|
118
|
+
try {
|
|
119
|
+
res = await get(`${o.issuer}/token`, { method: "POST", headers: { authorization: basic, "content-type": "application/x-www-form-urlencoded", accept: "application/json" }, body: new URLSearchParams(fields).toString() });
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
return "unavailable";
|
|
123
|
+
}
|
|
124
|
+
const body = (await res.json().catch(() => null));
|
|
125
|
+
if (res.ok && body && typeof body.access_token === "string")
|
|
126
|
+
return body;
|
|
127
|
+
if (res.status === 400 && body?.error === "invalid_grant")
|
|
128
|
+
return "refused";
|
|
129
|
+
return "unavailable";
|
|
130
|
+
}
|
|
131
|
+
async function signIn(req) {
|
|
132
|
+
const p = { s: random(), n: random(), v: random(), r: safePath(new URL(req.url).searchParams.get("return_to"), o.origin, o.mount) };
|
|
133
|
+
const to = new URL(`${o.issuer}/authorize`);
|
|
134
|
+
for (const [k, val] of Object.entries({ response_type: "code", client_id: o.clientId, redirect_uri: callback, scope: o.scope ?? "openid profile", state: p.s, nonce: p.n, code_challenge: await s256(p.v), code_challenge_method: "S256", ...(o.resource === undefined ? {} : { resource: o.resource }) }))
|
|
135
|
+
to.searchParams.set(k, val);
|
|
136
|
+
return new Response(null, { status: 302, headers: { location: to.href, "set-cookie": setCookie(`__Host-dm_auth_${p.s}`, await seal(JSON.stringify(p)), AUTH_TTL), "cache-control": "no-store" } });
|
|
137
|
+
}
|
|
138
|
+
async function onCallback(req) {
|
|
139
|
+
const q = new URL(req.url).searchParams;
|
|
140
|
+
const state = q.get("state") ?? "";
|
|
141
|
+
const name = `__Host-dm_auth_${state}`;
|
|
142
|
+
const raw = /^[A-Za-z0-9_-]{20,64}$/.test(state) ? cookieOf(req, name) : null;
|
|
143
|
+
let p = null;
|
|
144
|
+
try {
|
|
145
|
+
p = raw ? JSON.parse(await open(raw)) : null;
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
p = null;
|
|
149
|
+
}
|
|
150
|
+
// No matching state cookie (expired, replayed, another browser's): an error page with a way back, never a redirect.
|
|
151
|
+
if (!p || p.s !== state)
|
|
152
|
+
return text(400, `This sign-in has expired or isn't this browser's. Sign in again: ${o.mount}/sign-in`);
|
|
153
|
+
const clear = setCookie(name, "", 0);
|
|
154
|
+
const code = q.get("code");
|
|
155
|
+
if (!code)
|
|
156
|
+
return text(400, `Sign-in didn't finish. Try again: ${o.mount}/sign-in`, { "set-cookie": clear });
|
|
157
|
+
const t = await token({ grant_type: "authorization_code", code, redirect_uri: callback, code_verifier: p.v });
|
|
158
|
+
if (t === "unavailable")
|
|
159
|
+
return text(503, "Key can't be reached just now. Try again in a minute.", { "set-cookie": clear });
|
|
160
|
+
if (t === "refused" || !t.refresh_token || !t.id_token)
|
|
161
|
+
return text(400, `Key didn't accept the sign-in. Try again: ${o.mount}/sign-in`, { "set-cookie": clear });
|
|
162
|
+
let claims, profile;
|
|
163
|
+
try {
|
|
164
|
+
const id = await idV.verifyIdToken(t.id_token, p.n);
|
|
165
|
+
claims = await v.verify(t.access_token);
|
|
166
|
+
profile = profileValue(id.name, id.picture, random(12));
|
|
167
|
+
if (id.sub !== claims.sub)
|
|
168
|
+
throw new TokenInvalid("the ID and access tokens name different people");
|
|
169
|
+
}
|
|
170
|
+
catch (e) {
|
|
171
|
+
if (e instanceof TokenInvalid || e instanceof TokenExpired || e instanceof Revoked || e instanceof TokenMissing)
|
|
172
|
+
return text(400, `Key's answer didn't check out. Try again: ${o.mount}/sign-in`, { "set-cookie": clear });
|
|
173
|
+
return text(503, "Key can't be reached just now. Try again in a minute.", { "set-cookie": clear });
|
|
174
|
+
}
|
|
175
|
+
// Always a new ses_ id: a session id from before the sign-in is never reused (no fixation).
|
|
176
|
+
const id = `ses_${random()}`, at = now();
|
|
177
|
+
await o.store.create({ idHash: await sha256(id), userId: claims.sub, refreshHash: await sha256(t.refresh_token), refreshEnc: await seal(t.refresh_token), accessEnc: await seal(t.access_token), accessExp: claims.exp, exp: at + SESSION_TTL });
|
|
178
|
+
const res = new Response(null, { status: 302, headers: { location: p.r, "cache-control": "no-store" } });
|
|
179
|
+
res.headers.append("set-cookie", clear);
|
|
180
|
+
res.headers.append("set-cookie", setCookie(SESSION_COOKIE, id, SESSION_TTL));
|
|
181
|
+
res.headers.append("set-cookie", profileCookie(profile, SESSION_TTL));
|
|
182
|
+
return res;
|
|
183
|
+
}
|
|
184
|
+
/** 401 with the row gone and both cookies cleared: the session is over (revoked, refused or unknown). */
|
|
185
|
+
const ended = async (idHash) => {
|
|
186
|
+
if (idHash)
|
|
187
|
+
await o.store.delete(idHash);
|
|
188
|
+
const res = json(401, { error: "signed_out" }, { "set-cookie": clearSession });
|
|
189
|
+
res.headers.append("set-cookie", clearProfile);
|
|
190
|
+
return res;
|
|
191
|
+
};
|
|
192
|
+
async function onToken(req) {
|
|
193
|
+
if (!sameOrigin(req))
|
|
194
|
+
return json(403, { error: "bad_origin" });
|
|
195
|
+
const out = await live(req);
|
|
196
|
+
return out instanceof Response ? out : json(200, out);
|
|
197
|
+
}
|
|
198
|
+
/** The session's live access token, on the server: after the marker check, refreshed near its end. Or why there is
|
|
199
|
+
* none, as /token would say it: signed_out (no session, revoked or refused; the row is ended, and the cookies stay until
|
|
200
|
+
* the browser's next /token or sign-in), unavailable (Key out of reach: the session stands), or retry (another request
|
|
201
|
+
* holds the refresh lease). Only signed_out means sign in again (mi-dev-2 and Fable on doorman#109). */
|
|
202
|
+
async function accessTokenFor(req) {
|
|
203
|
+
const out = await live(req);
|
|
204
|
+
if (!(out instanceof Response))
|
|
205
|
+
return out;
|
|
206
|
+
return { error: out.status === 503 ? "unavailable" : out.status === 409 ? "retry" : "signed_out" };
|
|
207
|
+
}
|
|
208
|
+
/** /token's work, for both: the verified token and its exp, or the Response that says why there is none. */
|
|
209
|
+
async function live(req) {
|
|
210
|
+
const id = cookieOf(req, SESSION_COOKIE);
|
|
211
|
+
if (!id)
|
|
212
|
+
return ended(null);
|
|
213
|
+
const idHash = await sha256(id);
|
|
214
|
+
let row = await o.store.get(idHash, now());
|
|
215
|
+
if (!row)
|
|
216
|
+
return ended(null);
|
|
217
|
+
// The stored token still has time: hand it out only after verify, marker included, passes (Fable on #55).
|
|
218
|
+
if (row.accessExp - now() > EARLY) {
|
|
219
|
+
const out = await handOut(idHash, await open(row.accessEnc));
|
|
220
|
+
return out === "expired" ? refresh(idHash, row) : out;
|
|
221
|
+
}
|
|
222
|
+
return refresh(idHash, row);
|
|
223
|
+
/** Every token this route returns passes verify here first, whichever path stored it: Revoked or invalid ends the
|
|
224
|
+
* session, an outage is a 503, and expires_at is the verified token's own exp. */
|
|
225
|
+
async function handOut(h, access) {
|
|
226
|
+
try {
|
|
227
|
+
const claims = await v.verify(access);
|
|
228
|
+
return { access_token: access, expires_at: claims.exp };
|
|
229
|
+
}
|
|
230
|
+
catch (e) {
|
|
231
|
+
if (e instanceof TokenExpired)
|
|
232
|
+
return "expired";
|
|
233
|
+
if (e instanceof Revoked || e instanceof TokenInvalid)
|
|
234
|
+
return ended(h);
|
|
235
|
+
return json(503, { error: "unavailable" });
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
async function refresh(h, r) {
|
|
239
|
+
if (await o.store.claim(h, r.refreshHash, now() + LEASE, now())) {
|
|
240
|
+
const t = await token({ grant_type: "refresh_token", refresh_token: await open(r.refreshEnc) });
|
|
241
|
+
// Key out of reach or busy: keep the row (its lease runs out in LEASE seconds) and say so, never sign out.
|
|
242
|
+
if (t === "unavailable")
|
|
243
|
+
return json(503, { error: "unavailable" });
|
|
244
|
+
if (t === "refused" || !t.refresh_token)
|
|
245
|
+
return ended(h); // Key refused it (revoked, reused, the account suspended)
|
|
246
|
+
// Store the new pair before anything else can fail (mi-dev-2 on #57): Key has spent the old refresh token, so
|
|
247
|
+
// a row left holding it would replay it past Key's grace window, and Key would revoke the whole family. The
|
|
248
|
+
// stored token goes out only through handOut, so storing it first hands nothing out unchecked.
|
|
249
|
+
const accessExp = now() + (Number.isFinite(t.expires_in) ? Math.max(0, Math.floor(t.expires_in)) : 0);
|
|
250
|
+
const ok = await o.store.rotate(h, r.refreshHash, { refreshHash: await sha256(t.refresh_token), refreshEnc: await seal(t.refresh_token), accessEnc: await seal(t.access_token), accessExp, exp: now() + SESSION_TTL });
|
|
251
|
+
if (!ok)
|
|
252
|
+
return json(409, { error: "retry" });
|
|
253
|
+
const out = await handOut(h, t.access_token);
|
|
254
|
+
return out === "expired" ? ended(h) : out;
|
|
255
|
+
}
|
|
256
|
+
// Another request is refreshing this session: wait for it, then return what it stored.
|
|
257
|
+
for (let i = 0; i < 3; i++) {
|
|
258
|
+
await new Promise((done) => setTimeout(done, 200));
|
|
259
|
+
row = await o.store.get(h, now());
|
|
260
|
+
if (!row)
|
|
261
|
+
return ended(null);
|
|
262
|
+
if (row.accessExp - now() > EARLY) {
|
|
263
|
+
// What the winner stored is checked here too, never handed out on its word (it stores before it verifies).
|
|
264
|
+
const out = await handOut(h, await open(row.accessEnc));
|
|
265
|
+
return out === "expired" ? ended(h) : out;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
return json(409, { error: "retry" });
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
async function onSignOut(req) {
|
|
272
|
+
if (!sameOrigin(req))
|
|
273
|
+
return json(403, { error: "bad_origin" });
|
|
274
|
+
const id = cookieOf(req, SESSION_COOKIE);
|
|
275
|
+
if (id)
|
|
276
|
+
await o.store.delete(await sha256(id));
|
|
277
|
+
const to = new URL(`${o.issuer}/end_session`);
|
|
278
|
+
to.searchParams.set("client_id", o.clientId);
|
|
279
|
+
to.searchParams.set("post_logout_redirect_uri", `${o.origin}/`);
|
|
280
|
+
const res = new Response(null, { status: 303, headers: { location: to.href, "set-cookie": clearSession, "cache-control": "no-store" } });
|
|
281
|
+
res.headers.append("set-cookie", clearProfile);
|
|
282
|
+
return res;
|
|
283
|
+
}
|
|
284
|
+
/** The handler: a Response for its own routes (/token only while exposeToken is on), 404 or 405 for anything else under
|
|
285
|
+
* the mount; and accessTokenFor, for the app's own server code. */
|
|
286
|
+
async function handle(req) {
|
|
287
|
+
const path = new URL(req.url).pathname;
|
|
288
|
+
const routes = {
|
|
289
|
+
[`${o.mount}/sign-in`]: ["GET", signIn], [`${o.mount}/callback`]: ["GET", onCallback],
|
|
290
|
+
...(o.exposeToken === false ? {} : { [`${o.mount}/token`]: ["POST", onToken] }),
|
|
291
|
+
[`${o.mount}/signout`]: ["POST", onSignOut],
|
|
292
|
+
};
|
|
293
|
+
const route = routes[path];
|
|
294
|
+
if (!route)
|
|
295
|
+
return text(404, "Not found");
|
|
296
|
+
if (req.method !== route[0])
|
|
297
|
+
return text(405, `${path} takes ${route[0]}`, { allow: route[0] });
|
|
298
|
+
return route[1](req);
|
|
299
|
+
}
|
|
300
|
+
return Object.assign(handle, { accessTokenFor });
|
|
301
|
+
}
|
package/lib/store.d.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
export interface StoredSession {
|
|
2
|
+
/** sha256 of the ses_ id in the __Host-dm_app cookie. */
|
|
3
|
+
idHash: string;
|
|
4
|
+
userId: string;
|
|
5
|
+
/** sha256 of the live refresh token, the value every conditional write compares. */
|
|
6
|
+
refreshHash: string;
|
|
7
|
+
refreshEnc: string;
|
|
8
|
+
accessEnc: string;
|
|
9
|
+
/** The access token's exp, in seconds. */
|
|
10
|
+
accessExp: number;
|
|
11
|
+
/** When the row is gone for good, in seconds: the refresh token's own lifetime. */
|
|
12
|
+
exp: number;
|
|
13
|
+
/** A refresh in flight holds the row until then (0 when none). */
|
|
14
|
+
leaseUntil: number;
|
|
15
|
+
}
|
|
16
|
+
export type NewSession = Omit<StoredSession, "leaseUntil">;
|
|
17
|
+
export type Rotation = Pick<StoredSession, "refreshHash" | "refreshEnc" | "accessEnc" | "accessExp" | "exp">;
|
|
18
|
+
export interface SessionStore {
|
|
19
|
+
create(s: NewSession): Promise<void>;
|
|
20
|
+
/** The row, while it hasn't passed its exp. */
|
|
21
|
+
get(idHash: string, now: number): Promise<StoredSession | null>;
|
|
22
|
+
/** One winner: true only when the row still holds that refresh token and no live lease. */
|
|
23
|
+
claim(idHash: string, expectedRefreshHash: string, leaseUntil: number, now: number): Promise<boolean>;
|
|
24
|
+
/** One winner: true only when the row still holds that refresh token. Clears the lease. */
|
|
25
|
+
rotate(idHash: string, expectedRefreshHash: string, next: Rotation): Promise<boolean>;
|
|
26
|
+
delete(idHash: string): Promise<void>;
|
|
27
|
+
}
|
|
28
|
+
/** The few D1 calls the adapter makes, so a Workers D1Database (or anything shaped like it) fits. */
|
|
29
|
+
export interface D1Like {
|
|
30
|
+
prepare(sql: string): {
|
|
31
|
+
bind(...values: unknown[]): {
|
|
32
|
+
run(): Promise<{
|
|
33
|
+
meta: {
|
|
34
|
+
changes: number;
|
|
35
|
+
};
|
|
36
|
+
}>;
|
|
37
|
+
first<T>(): Promise<T | null>;
|
|
38
|
+
};
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
/** The adapter's table. Run it once in the app's own D1 (a migration); the handler never creates tables itself. */
|
|
42
|
+
export declare const D1_SCHEMA = "CREATE TABLE IF NOT EXISTS doorman_sessions (\n id_hash TEXT PRIMARY KEY,\n user_id TEXT NOT NULL,\n refresh_hash TEXT NOT NULL,\n refresh_enc TEXT NOT NULL,\n access_enc TEXT NOT NULL,\n access_exp INTEGER NOT NULL,\n exp INTEGER NOT NULL,\n lease_until INTEGER NOT NULL DEFAULT 0\n)";
|
|
43
|
+
/** SessionStore on D1: each write is one conditional statement, checked by its changes(). */
|
|
44
|
+
export declare function d1Store(db: D1Like): SessionStore;
|
package/lib/store.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// The handler's session store (DESIGN §5.3 [F5]). A row is a bearer, so nothing in it signs anyone in by itself (Fable
|
|
2
|
+
// on doorman#55): it is keyed by sha256 of the cookie's ses_ id, never the id, and both tokens are sealed with the
|
|
3
|
+
// handler's key. The refresh token's sha256 is kept beside its sealed copy for the conditional writes, so one refresh
|
|
4
|
+
// wins a race and the loser re-reads.
|
|
5
|
+
/** The adapter's table. Run it once in the app's own D1 (a migration); the handler never creates tables itself. */
|
|
6
|
+
export const D1_SCHEMA = `CREATE TABLE IF NOT EXISTS doorman_sessions (
|
|
7
|
+
id_hash TEXT PRIMARY KEY,
|
|
8
|
+
user_id TEXT NOT NULL,
|
|
9
|
+
refresh_hash TEXT NOT NULL,
|
|
10
|
+
refresh_enc TEXT NOT NULL,
|
|
11
|
+
access_enc TEXT NOT NULL,
|
|
12
|
+
access_exp INTEGER NOT NULL,
|
|
13
|
+
exp INTEGER NOT NULL,
|
|
14
|
+
lease_until INTEGER NOT NULL DEFAULT 0
|
|
15
|
+
)`;
|
|
16
|
+
/** SessionStore on D1: each write is one conditional statement, checked by its changes(). */
|
|
17
|
+
export function d1Store(db) {
|
|
18
|
+
return {
|
|
19
|
+
async create(s) {
|
|
20
|
+
await db.prepare("INSERT INTO doorman_sessions (id_hash, user_id, refresh_hash, refresh_enc, access_enc, access_exp, exp) VALUES (?, ?, ?, ?, ?, ?, ?)")
|
|
21
|
+
.bind(s.idHash, s.userId, s.refreshHash, s.refreshEnc, s.accessEnc, s.accessExp, s.exp).run();
|
|
22
|
+
// A session abandoned without sign-out keeps its sealed tokens until something deletes it (doorman#224). The handler
|
|
23
|
+
// runs in the app's Worker with no cron of its own, so each sign-in takes a few expired rows with it.
|
|
24
|
+
await db.prepare("DELETE FROM doorman_sessions WHERE rowid IN (SELECT rowid FROM doorman_sessions WHERE exp <= ? LIMIT 50)")
|
|
25
|
+
.bind(Math.floor(Date.now() / 1000)).run();
|
|
26
|
+
},
|
|
27
|
+
async get(idHash, now) {
|
|
28
|
+
const r = await db.prepare("SELECT * FROM doorman_sessions WHERE id_hash = ?").bind(idHash).first();
|
|
29
|
+
if (!r)
|
|
30
|
+
return null;
|
|
31
|
+
if (r.exp <= now) { // past its exp: absent, and deleted rather than left holding its tokens (doorman#224)
|
|
32
|
+
await db.prepare("DELETE FROM doorman_sessions WHERE id_hash = ? AND exp <= ?").bind(idHash, now).run();
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
return { idHash: r.id_hash, userId: r.user_id, refreshHash: r.refresh_hash, refreshEnc: r.refresh_enc, accessEnc: r.access_enc, accessExp: r.access_exp, exp: r.exp, leaseUntil: r.lease_until };
|
|
36
|
+
},
|
|
37
|
+
async claim(idHash, expected, leaseUntil, now) {
|
|
38
|
+
const r = await db.prepare("UPDATE doorman_sessions SET lease_until = ? WHERE id_hash = ? AND refresh_hash = ? AND lease_until <= ? AND exp > ?")
|
|
39
|
+
.bind(leaseUntil, idHash, expected, now, now).run();
|
|
40
|
+
return r.meta.changes === 1;
|
|
41
|
+
},
|
|
42
|
+
async rotate(idHash, expected, n) {
|
|
43
|
+
const r = await db.prepare("UPDATE doorman_sessions SET refresh_hash = ?, refresh_enc = ?, access_enc = ?, access_exp = ?, exp = ?, lease_until = 0 WHERE id_hash = ? AND refresh_hash = ?")
|
|
44
|
+
.bind(n.refreshHash, n.refreshEnc, n.accessEnc, n.accessExp, n.exp, idHash, expected).run();
|
|
45
|
+
return r.meta.changes === 1;
|
|
46
|
+
},
|
|
47
|
+
async delete(idHash) {
|
|
48
|
+
await db.prepare("DELETE FROM doorman_sessions WHERE id_hash = ?").bind(idHash).run();
|
|
49
|
+
},
|
|
50
|
+
};
|
|
51
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,37 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@superintelligentfamily/key-handler",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"description": "Key sign-in for an app with a server: sign-in, callback, token and sign-out routes, with sessions in a store you choose.",
|
|
6
|
+
"homepage": "https://superintelligentkey.com",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/sethshoultes/doorman.git",
|
|
10
|
+
"directory": "packages/handler"
|
|
11
|
+
},
|
|
12
|
+
"type": "module",
|
|
13
|
+
"files": [
|
|
14
|
+
"lib",
|
|
15
|
+
"LICENSE"
|
|
16
|
+
],
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"types": "./lib/index.d.ts",
|
|
20
|
+
"import": "./lib/index.js"
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
"dependencies": {
|
|
24
|
+
"@superintelligentfamily/key-verify": "0.1.0"
|
|
25
|
+
},
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public",
|
|
28
|
+
"provenance": true
|
|
29
|
+
},
|
|
30
|
+
"scripts": {
|
|
31
|
+
"typecheck": "tsc --noEmit -p .",
|
|
32
|
+
"lint": "eslint .",
|
|
33
|
+
"test": "vitest run",
|
|
34
|
+
"check": "pnpm run typecheck && pnpm run lint && pnpm run test",
|
|
35
|
+
"build:npm": "tsc -p tsconfig.build.json"
|
|
36
|
+
}
|
|
6
37
|
}
|
package/README.md
DELETED