direct-auth 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/README.md +486 -2
- package/dist/accounts.d.ts +118 -0
- package/dist/accounts.js +314 -0
- package/dist/apps.d.ts +85 -0
- package/dist/apps.js +449 -0
- package/dist/auth.d.ts +396 -0
- package/dist/auth.js +699 -0
- package/dist/base64.d.ts +20 -0
- package/dist/base64.js +45 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +463 -0
- package/dist/client.d.ts +170 -0
- package/dist/client.js +438 -0
- package/dist/codes.d.ts +81 -0
- package/dist/codes.js +91 -0
- package/dist/crypto.d.ts +11 -0
- package/dist/crypto.js +37 -0
- package/dist/d1.d.ts +2 -0
- package/dist/d1.js +2 -0
- package/dist/db/limits.d.ts +16 -0
- package/dist/db/limits.js +23 -0
- package/dist/db/schema.d.ts +25 -0
- package/dist/db/schema.js +136 -0
- package/dist/db/sql.d.ts +52 -0
- package/dist/db/sql.js +121 -0
- package/dist/dns.d.ts +48 -0
- package/dist/dns.js +133 -0
- package/dist/env.d.ts +39 -0
- package/dist/env.js +169 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +14 -0
- package/dist/init.d.ts +134 -0
- package/dist/init.js +912 -0
- package/dist/jwks.d.ts +18 -0
- package/dist/jwks.js +63 -0
- package/dist/jwt.d.ts +90 -0
- package/dist/jwt.js +99 -0
- package/dist/keys.d.ts +33 -0
- package/dist/keys.js +54 -0
- package/dist/messages.d.ts +26 -0
- package/dist/messages.js +57 -0
- package/dist/migrate-cli.d.ts +82 -0
- package/dist/migrate-cli.js +564 -0
- package/dist/migrate.d.ts +99 -0
- package/dist/migrate.js +396 -0
- package/dist/node.d.ts +16 -0
- package/dist/node.js +63 -0
- package/dist/passkeys.d.ts +126 -0
- package/dist/passkeys.js +383 -0
- package/dist/passwords.d.ts +53 -0
- package/dist/passwords.js +326 -0
- package/dist/pgwire.d.ts +86 -0
- package/dist/pgwire.js +445 -0
- package/dist/phone.d.ts +11 -0
- package/dist/phone.js +18 -0
- package/dist/postgres.d.ts +2 -0
- package/dist/postgres.js +2 -0
- package/dist/providers/apple-revoke.d.ts +55 -0
- package/dist/providers/apple-revoke.js +113 -0
- package/dist/providers/apple.d.ts +28 -0
- package/dist/providers/apple.js +51 -0
- package/dist/providers/github.d.ts +28 -0
- package/dist/providers/github.js +67 -0
- package/dist/providers/google.d.ts +23 -0
- package/dist/providers/google.js +47 -0
- package/dist/providers/identity.d.ts +24 -0
- package/dist/providers/identity.js +3 -0
- package/dist/proxy.d.ts +19 -0
- package/dist/proxy.js +43 -0
- package/dist/records.d.ts +91 -0
- package/dist/records.js +264 -0
- package/dist/scrypt.d.ts +26 -0
- package/dist/scrypt.js +179 -0
- package/dist/senders/aws.d.ts +13 -0
- package/dist/senders/aws.js +47 -0
- package/dist/senders/dev.d.ts +6 -0
- package/dist/senders/dev.js +13 -0
- package/dist/senders/index.d.ts +5 -0
- package/dist/senders/index.js +4 -0
- package/dist/senders/mail.d.ts +26 -0
- package/dist/senders/mail.js +66 -0
- package/dist/senders/sms.d.ts +34 -0
- package/dist/senders/sms.js +69 -0
- package/dist/senders/smtp.d.ts +32 -0
- package/dist/senders/smtp.js +145 -0
- package/dist/senders/types.d.ts +31 -0
- package/dist/senders/types.js +25 -0
- package/dist/server.d.ts +67 -0
- package/dist/server.js +494 -0
- package/dist/sessions.d.ts +74 -0
- package/dist/sessions.js +146 -0
- package/dist/skill.d.ts +25 -0
- package/dist/skill.js +66 -0
- package/dist/sources.d.ts +138 -0
- package/dist/sources.js +931 -0
- package/dist/sqlite.d.ts +2 -0
- package/dist/sqlite.js +2 -0
- package/dist/stores/d1.d.ts +22 -0
- package/dist/stores/d1.js +23 -0
- package/dist/stores/postgres.d.ts +33 -0
- package/dist/stores/postgres.js +71 -0
- package/dist/stores/sqlite.d.ts +27 -0
- package/dist/stores/sqlite.js +55 -0
- package/dist/supabase.d.ts +71 -0
- package/dist/supabase.js +283 -0
- package/dist/tui.d.ts +178 -0
- package/dist/tui.js +537 -0
- package/package.json +90 -4
- package/skills/direct-auth/SKILL.md +101 -0
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The browser's client: signing in against a direct-auth server, keeping the session, and handing a fresh access
|
|
3
|
+
* token to whatever calls the API.
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* import { createAuthClient } from "direct-auth/client";
|
|
7
|
+
*
|
|
8
|
+
* const auth = createAuthClient({ url: "https://api.example.com/auth" });
|
|
9
|
+
* await auth.startEmail("ana@example.com");
|
|
10
|
+
* await auth.verifyEmail("ana@example.com", code);
|
|
11
|
+
*
|
|
12
|
+
* // supabase-js, with direct-auth as the project's Third-Party Auth issuer:
|
|
13
|
+
* const supabase = createClient(url, anonKey, { accessToken: () => auth.accessToken() });
|
|
14
|
+
* ```
|
|
15
|
+
*
|
|
16
|
+
* Where the refresh token lives:
|
|
17
|
+
*
|
|
18
|
+
* - `cookie: true` (a site on the same site as the server): in an HttpOnly cookie the server sets, which page
|
|
19
|
+
* scripts can't read. The access token stays in memory; a reload gets a new one from the cookie.
|
|
20
|
+
* - Otherwise in `localStorage` (or the `storage` given), which scripts on the page can read: fine for a site
|
|
21
|
+
* whose every script is its own, and the only way when the server is on another site.
|
|
22
|
+
*
|
|
23
|
+
* Sign in with Apple and Google on the web give an ID token through their own scripts (Sign in with Apple JS,
|
|
24
|
+
* Google Identity Services); hand it here. Nothing runs on import, and every call is safe where there is no browser.
|
|
25
|
+
*/
|
|
26
|
+
export interface ClientUser {
|
|
27
|
+
id: string;
|
|
28
|
+
email: string | null;
|
|
29
|
+
phone: string | null;
|
|
30
|
+
name: string | null;
|
|
31
|
+
picture: string | null;
|
|
32
|
+
createdAt: number;
|
|
33
|
+
/** Made with `signInAsGuest`: nothing to sign in with yet, until a way in is linked. */
|
|
34
|
+
isGuest?: boolean;
|
|
35
|
+
hasPassword?: boolean;
|
|
36
|
+
}
|
|
37
|
+
export interface ClientSession {
|
|
38
|
+
user: ClientUser;
|
|
39
|
+
accessToken: string;
|
|
40
|
+
/** Absent in cookie mode. */
|
|
41
|
+
refreshToken?: string;
|
|
42
|
+
/** Milliseconds since 1970 when the access token stops working. */
|
|
43
|
+
expiresAt: number;
|
|
44
|
+
sessionId: string;
|
|
45
|
+
}
|
|
46
|
+
export interface KeyValueStorage {
|
|
47
|
+
getItem(key: string): string | null;
|
|
48
|
+
setItem(key: string, value: string): void;
|
|
49
|
+
removeItem(key: string): void;
|
|
50
|
+
}
|
|
51
|
+
export interface AuthClientOptions {
|
|
52
|
+
/** The server's URL with its base path (`https://api.example.com/auth`). */
|
|
53
|
+
url: string;
|
|
54
|
+
/** The refresh token in an HttpOnly cookie (same-site servers). */
|
|
55
|
+
cookie?: boolean;
|
|
56
|
+
/** Where the session is kept when not in cookie mode (`localStorage`). */
|
|
57
|
+
storage?: KeyValueStorage;
|
|
58
|
+
/** The storage key (`direct-auth`). */
|
|
59
|
+
key?: string;
|
|
60
|
+
fetch?: typeof fetch;
|
|
61
|
+
}
|
|
62
|
+
export interface GitHubStart {
|
|
63
|
+
/** The OAuth app's client ID (public). */
|
|
64
|
+
clientId: string;
|
|
65
|
+
/** Where GitHub sends the browser back: a page of the app that calls `finishGitHub()`. One of the app's callback URLs. */
|
|
66
|
+
redirectUri: string;
|
|
67
|
+
/** `read:user user:email` by default: the name and picture, and the addresses GitHub checked. */
|
|
68
|
+
scope?: string;
|
|
69
|
+
}
|
|
70
|
+
export declare class AuthClientError extends Error {
|
|
71
|
+
name: string;
|
|
72
|
+
readonly reason: string;
|
|
73
|
+
readonly status: number;
|
|
74
|
+
constructor(reason: string, status: number);
|
|
75
|
+
}
|
|
76
|
+
export declare function createAuthClient(o: AuthClientOptions): {
|
|
77
|
+
/** The session kept, or null (in cookie mode, null until `accessToken()` or a sign-in). */
|
|
78
|
+
readonly session: ClientSession | null;
|
|
79
|
+
readonly user: ClientUser | null;
|
|
80
|
+
/** Called with the session on every change (sign-in, refresh, sign-out); answers a function that stops it. */
|
|
81
|
+
onChange(listener: (s: ClientSession | null) => void): () => void;
|
|
82
|
+
accessToken: () => Promise<string | null>;
|
|
83
|
+
refresh: () => Promise<ClientSession | null>;
|
|
84
|
+
signInWithApple: (a: {
|
|
85
|
+
idToken: string;
|
|
86
|
+
nonce?: string;
|
|
87
|
+
name?: string;
|
|
88
|
+
authorizationCode?: string;
|
|
89
|
+
redirectUri?: string;
|
|
90
|
+
}) => Promise<ClientSession>;
|
|
91
|
+
signInWithGoogle: (a: {
|
|
92
|
+
idToken: string;
|
|
93
|
+
nonce?: string;
|
|
94
|
+
}) => Promise<ClientSession>;
|
|
95
|
+
/**
|
|
96
|
+
* GitHub, step one: the address to send the browser to (`location.assign(await auth.startGitHub({...}))`). The
|
|
97
|
+
* state and the PKCE verifier wait in this tab's sessionStorage.
|
|
98
|
+
*/
|
|
99
|
+
startGitHub(g: GitHubStart): Promise<string>;
|
|
100
|
+
/** GitHub, step two, on the redirect page: signs in with the code GitHub put in the URL (`location.href`). */
|
|
101
|
+
finishGitHub: (url?: string) => Promise<ClientSession>;
|
|
102
|
+
/** Like `finishGitHub`, adding GitHub to the signed-in account. `identity_in_use` (409) when it signs someone else in. */
|
|
103
|
+
linkGitHub: (url?: string) => Promise<ClientSession>;
|
|
104
|
+
startEmail: (email: string, locale?: string) => Promise<undefined>;
|
|
105
|
+
verifyEmail: (email: string, code: string) => Promise<ClientSession>;
|
|
106
|
+
/** A guest: an account with nothing to sign in with yet. Linking a way in later keeps its id and its data. */
|
|
107
|
+
signInAsGuest: (name?: string) => Promise<ClientSession>;
|
|
108
|
+
/**
|
|
109
|
+
* A guest moved from Supabase Auth: the refresh token of the anonymous session supabase-js kept. Once, at the new
|
|
110
|
+
* version's first start, before anything else; then forget the Supabase session. `invalid_token` when it can't.
|
|
111
|
+
*/
|
|
112
|
+
claimGuest: (supabaseRefreshToken: string) => Promise<ClientSession>;
|
|
113
|
+
signInWithPassword: (email: string, password: string) => Promise<ClientSession>;
|
|
114
|
+
/** After `startEmail(email)`: the code proves the address, and the account is made with this password. */
|
|
115
|
+
signUpWithPassword: (email: string, code: string, password: string) => Promise<ClientSession>;
|
|
116
|
+
/** After `startEmail(email)`: a new password, and every other device signed out. */
|
|
117
|
+
resetPassword: (email: string, code: string, password: string) => Promise<ClientSession>;
|
|
118
|
+
/** Sets or changes the signed-in user's password (needs a recent sign-in: `reauth_needed` otherwise). */
|
|
119
|
+
setPassword: (password: string) => Promise<ClientSession>;
|
|
120
|
+
removePassword: () => Promise<ClientSession>;
|
|
121
|
+
/**
|
|
122
|
+
* Adds a way in to the signed-in account (a guest's included, which then stops being one). `identity_in_use`
|
|
123
|
+
* (409) when it signs someone else in: offer to switch to that account instead.
|
|
124
|
+
*/
|
|
125
|
+
linkApple: (a: {
|
|
126
|
+
idToken: string;
|
|
127
|
+
nonce: string;
|
|
128
|
+
name?: string;
|
|
129
|
+
authorizationCode?: string;
|
|
130
|
+
redirectUri?: string;
|
|
131
|
+
}) => Promise<ClientSession>;
|
|
132
|
+
linkGoogle: (a: {
|
|
133
|
+
idToken: string;
|
|
134
|
+
nonce: string;
|
|
135
|
+
}) => Promise<ClientSession>;
|
|
136
|
+
/** After `startEmail(email)`. */
|
|
137
|
+
linkEmail: (email: string, code: string) => Promise<ClientSession>;
|
|
138
|
+
/** After `startEmail(newEmail)`: the account's address becomes this one. */
|
|
139
|
+
changeEmail: (email: string, code: string) => Promise<ClientSession>;
|
|
140
|
+
/** Removes a way in (`fetchUser()`'s `identities[].id`); never the last (`last_way_in`). */
|
|
141
|
+
unlink: (identityId: string) => Promise<ClientSession>;
|
|
142
|
+
startSms: (phone: string, locale?: string) => Promise<undefined>;
|
|
143
|
+
verifySms: (phone: string, code: string) => Promise<ClientSession>;
|
|
144
|
+
/** Signs in with a passkey the browser or the password manager offers. */
|
|
145
|
+
signInWithPasskey(): Promise<ClientSession>;
|
|
146
|
+
/** Makes a passkey for the signed-in user. */
|
|
147
|
+
registerPasskey(name?: string): Promise<{
|
|
148
|
+
id: string;
|
|
149
|
+
name: string | null;
|
|
150
|
+
createdAt: number;
|
|
151
|
+
}>;
|
|
152
|
+
deletePasskey: (id: string) => Promise<undefined>;
|
|
153
|
+
fetchUser: () => Promise<Record<string, unknown>>;
|
|
154
|
+
signOut(everywhere?: boolean): Promise<void>;
|
|
155
|
+
/**
|
|
156
|
+
* Deletes the account. Needs a recent sign-in (`reauth_needed`, status 401, otherwise: sign in again, then call
|
|
157
|
+
* this). A user who signed in with Apple may get `apple_code_needed` (status 409): run Sign in with Apple JS
|
|
158
|
+
* again and call this with its authorization code.
|
|
159
|
+
*/
|
|
160
|
+
deleteAccount(appleAuthorizationCode?: string): Promise<void>;
|
|
161
|
+
};
|
|
162
|
+
export type AuthClient = ReturnType<typeof createAuthClient>;
|
|
163
|
+
/**
|
|
164
|
+
* A nonce for Sign in with Apple JS: give `hashed` to `AppleID.auth.init({ nonce })` and `raw` to `signInWithApple`.
|
|
165
|
+
* Only the hash is in Apple's token, so the token alone can't be sent again by whoever sees it.
|
|
166
|
+
*/
|
|
167
|
+
export declare function appleNonce(): Promise<{
|
|
168
|
+
raw: string;
|
|
169
|
+
hashed: string;
|
|
170
|
+
}>;
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,438 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The browser's client: signing in against a direct-auth server, keeping the session, and handing a fresh access
|
|
3
|
+
* token to whatever calls the API.
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* import { createAuthClient } from "direct-auth/client";
|
|
7
|
+
*
|
|
8
|
+
* const auth = createAuthClient({ url: "https://api.example.com/auth" });
|
|
9
|
+
* await auth.startEmail("ana@example.com");
|
|
10
|
+
* await auth.verifyEmail("ana@example.com", code);
|
|
11
|
+
*
|
|
12
|
+
* // supabase-js, with direct-auth as the project's Third-Party Auth issuer:
|
|
13
|
+
* const supabase = createClient(url, anonKey, { accessToken: () => auth.accessToken() });
|
|
14
|
+
* ```
|
|
15
|
+
*
|
|
16
|
+
* Where the refresh token lives:
|
|
17
|
+
*
|
|
18
|
+
* - `cookie: true` (a site on the same site as the server): in an HttpOnly cookie the server sets, which page
|
|
19
|
+
* scripts can't read. The access token stays in memory; a reload gets a new one from the cookie.
|
|
20
|
+
* - Otherwise in `localStorage` (or the `storage` given), which scripts on the page can read: fine for a site
|
|
21
|
+
* whose every script is its own, and the only way when the server is on another site.
|
|
22
|
+
*
|
|
23
|
+
* Sign in with Apple and Google on the web give an ID token through their own scripts (Sign in with Apple JS,
|
|
24
|
+
* Google Identity Services); hand it here. Nothing runs on import, and every call is safe where there is no browser.
|
|
25
|
+
*/
|
|
26
|
+
import { b64url, fromBase64 } from "./base64.js";
|
|
27
|
+
export class AuthClientError extends Error {
|
|
28
|
+
name = "AuthClientError";
|
|
29
|
+
reason;
|
|
30
|
+
status;
|
|
31
|
+
constructor(reason, status) {
|
|
32
|
+
super(reason);
|
|
33
|
+
this.reason = reason;
|
|
34
|
+
this.status = status;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
const ENDED = new Set(["session_ended", "token_reused", "invalid_token"]);
|
|
38
|
+
export function createAuthClient(o) {
|
|
39
|
+
const base = o.url.replace(/\/+$/, "");
|
|
40
|
+
const key = o.key ?? "direct-auth";
|
|
41
|
+
const http = (...a) => (o.fetch ?? globalThis.fetch)(...a);
|
|
42
|
+
const storage = () => {
|
|
43
|
+
if (o.cookie)
|
|
44
|
+
return null;
|
|
45
|
+
if (o.storage)
|
|
46
|
+
return o.storage;
|
|
47
|
+
try {
|
|
48
|
+
return globalThis.localStorage ?? null;
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
let session = null;
|
|
55
|
+
// The text last read from storage or written to it: another tab's write shows as a change.
|
|
56
|
+
let seen;
|
|
57
|
+
let refreshing = null;
|
|
58
|
+
const listeners = new Set();
|
|
59
|
+
/**
|
|
60
|
+
* The session as storage has it now: tabs of one app share it, and another may have refreshed it, signed out or
|
|
61
|
+
* signed in since this one last looked. True when it changed.
|
|
62
|
+
*/
|
|
63
|
+
const load = () => {
|
|
64
|
+
const st = storage();
|
|
65
|
+
if (!st)
|
|
66
|
+
return false;
|
|
67
|
+
let text;
|
|
68
|
+
try {
|
|
69
|
+
text = st.getItem(key);
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
if (text === seen)
|
|
75
|
+
return false;
|
|
76
|
+
seen = text;
|
|
77
|
+
let next = null;
|
|
78
|
+
if (text) {
|
|
79
|
+
try {
|
|
80
|
+
next = JSON.parse(text);
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
st.removeItem(key);
|
|
84
|
+
seen = null;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
session = next;
|
|
88
|
+
return true;
|
|
89
|
+
};
|
|
90
|
+
const set = (s) => {
|
|
91
|
+
session = s;
|
|
92
|
+
const st = storage();
|
|
93
|
+
if (st) {
|
|
94
|
+
seen = s ? JSON.stringify(s) : null;
|
|
95
|
+
if (seen)
|
|
96
|
+
st.setItem(key, seen);
|
|
97
|
+
else
|
|
98
|
+
st.removeItem(key);
|
|
99
|
+
}
|
|
100
|
+
for (const l of listeners)
|
|
101
|
+
l(s);
|
|
102
|
+
};
|
|
103
|
+
// Another tab's sign-in, refresh or sign-out, as it happens.
|
|
104
|
+
if (!o.cookie && typeof globalThis.addEventListener === "function") {
|
|
105
|
+
globalThis.addEventListener("storage", (e) => {
|
|
106
|
+
const k = e.key;
|
|
107
|
+
if ((k === key || k === null) && load())
|
|
108
|
+
for (const l of listeners)
|
|
109
|
+
l(session);
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
const call = async (method, path, body, token) => {
|
|
113
|
+
const headers = { "content-type": "application/json" };
|
|
114
|
+
if (o.cookie)
|
|
115
|
+
headers["x-direct-auth-cookie"] = "1";
|
|
116
|
+
if (token)
|
|
117
|
+
headers.authorization = `Bearer ${token}`;
|
|
118
|
+
let res;
|
|
119
|
+
try {
|
|
120
|
+
res = await http(`${base}${path}`, {
|
|
121
|
+
method,
|
|
122
|
+
headers,
|
|
123
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
124
|
+
credentials: o.cookie ? "include" : "same-origin",
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
throw new AuthClientError("network", 0);
|
|
129
|
+
}
|
|
130
|
+
const json = (await res.json().catch(() => ({})));
|
|
131
|
+
if (!res.ok)
|
|
132
|
+
throw new AuthClientError(typeof json.error === "string" ? json.error : "bad_response", res.status);
|
|
133
|
+
return json;
|
|
134
|
+
};
|
|
135
|
+
const accept = (json, keepRefresh) => {
|
|
136
|
+
const s = {
|
|
137
|
+
user: json.user,
|
|
138
|
+
accessToken: String(json.accessToken),
|
|
139
|
+
refreshToken: typeof json.refreshToken === "string" ? json.refreshToken : keepRefresh,
|
|
140
|
+
expiresAt: Date.now() + Number(json.expiresIn ?? 3600) * 1000,
|
|
141
|
+
sessionId: String(json.sessionId),
|
|
142
|
+
};
|
|
143
|
+
set(s);
|
|
144
|
+
return s;
|
|
145
|
+
};
|
|
146
|
+
const signIn = async (path, body) => accept(await call("POST", path, body));
|
|
147
|
+
// GitHub's redirect flow: the state and the PKCE verifier wait in sessionStorage (this tab's) for the way back.
|
|
148
|
+
const pending = () => {
|
|
149
|
+
try {
|
|
150
|
+
return globalThis.sessionStorage ?? o.storage ?? null;
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
return o.storage ?? null;
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
const githubKey = `${key}:github`;
|
|
157
|
+
const githubBack = async (url) => {
|
|
158
|
+
const back = new URL(url);
|
|
159
|
+
const st = pending();
|
|
160
|
+
const saved = st?.getItem(githubKey);
|
|
161
|
+
st?.removeItem(githubKey);
|
|
162
|
+
let p = null;
|
|
163
|
+
try {
|
|
164
|
+
p = saved ? JSON.parse(saved) : null;
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
// Not what startGitHub kept: no request of this tab's to answer.
|
|
168
|
+
}
|
|
169
|
+
if (back.searchParams.get("error"))
|
|
170
|
+
throw new AuthClientError(back.searchParams.get("error") === "access_denied" ? "cancelled" : "github_failed", 0);
|
|
171
|
+
const code = back.searchParams.get("code");
|
|
172
|
+
// Only an answer to the request this tab made: a link someone else sent carries another state, or none.
|
|
173
|
+
if (!p || typeof p !== "object" || typeof p.state !== "string" || !code || back.searchParams.get("state") !== p.state)
|
|
174
|
+
throw new AuthClientError("github_state", 0);
|
|
175
|
+
return { code, redirectUri: p.redirectUri, codeVerifier: p.verifier };
|
|
176
|
+
};
|
|
177
|
+
/**
|
|
178
|
+
* A change to the signed-in account: the same session, with the user and the access token it answers. Signed out,
|
|
179
|
+
* or signed in as someone else, while it was on its way: the answer is for a session that is no longer this one,
|
|
180
|
+
* and is dropped.
|
|
181
|
+
*/
|
|
182
|
+
const change = async (method, path, body) => {
|
|
183
|
+
load();
|
|
184
|
+
const before = session?.sessionId;
|
|
185
|
+
const json = await authed(method, path, body);
|
|
186
|
+
load();
|
|
187
|
+
if (!session || session.sessionId !== before)
|
|
188
|
+
throw new AuthClientError("signed_out", 0);
|
|
189
|
+
const s = {
|
|
190
|
+
...session,
|
|
191
|
+
user: json.user,
|
|
192
|
+
accessToken: String(json.accessToken),
|
|
193
|
+
expiresAt: Date.now() + Number(json.expiresIn ?? 3600) * 1000,
|
|
194
|
+
};
|
|
195
|
+
set(s);
|
|
196
|
+
return s;
|
|
197
|
+
};
|
|
198
|
+
// One refresh at a time: callers meanwhile share it, and tabs take turns (Web Locks, where there are). Cleared once
|
|
199
|
+
// it settles (a `.finally` after the assignment, so even a refresh that ends at once, signed out, doesn't stay
|
|
200
|
+
// behind as the answer for good).
|
|
201
|
+
const refresh = () => {
|
|
202
|
+
if (refreshing)
|
|
203
|
+
return refreshing;
|
|
204
|
+
load();
|
|
205
|
+
const had = session?.refreshToken;
|
|
206
|
+
const go = async () => {
|
|
207
|
+
// Another tab may have refreshed (or signed out) while this one waited: its token is the one that works now.
|
|
208
|
+
load();
|
|
209
|
+
if (!o.cookie && !session?.refreshToken)
|
|
210
|
+
return null;
|
|
211
|
+
if (!o.cookie && session.refreshToken !== had && session.expiresAt - 60_000 > Date.now())
|
|
212
|
+
return session;
|
|
213
|
+
const used = session?.refreshToken;
|
|
214
|
+
try {
|
|
215
|
+
return accept(await call("POST", "/refresh", o.cookie ? {} : { refreshToken: used }));
|
|
216
|
+
}
|
|
217
|
+
catch (e) {
|
|
218
|
+
if (e instanceof AuthClientError && (ENDED.has(e.reason) || e.status === 401)) {
|
|
219
|
+
// Ended for this token; a tab that signed in again meanwhile keeps its own.
|
|
220
|
+
load();
|
|
221
|
+
if (o.cookie || session?.refreshToken === used)
|
|
222
|
+
set(null);
|
|
223
|
+
else
|
|
224
|
+
return session;
|
|
225
|
+
}
|
|
226
|
+
if (e instanceof AuthClientError && e.reason !== "network" && !ENDED.has(e.reason) && e.status !== 401)
|
|
227
|
+
throw e;
|
|
228
|
+
return null;
|
|
229
|
+
}
|
|
230
|
+
};
|
|
231
|
+
const locks = globalThis.navigator?.locks;
|
|
232
|
+
const run = typeof locks?.request === "function" ? locks.request(`direct-auth ${base} ${key}`, go) : go();
|
|
233
|
+
const shared = run.finally(() => {
|
|
234
|
+
if (refreshing === shared)
|
|
235
|
+
refreshing = null;
|
|
236
|
+
});
|
|
237
|
+
refreshing = shared;
|
|
238
|
+
return shared;
|
|
239
|
+
};
|
|
240
|
+
/** A token good for at least a minute, refreshed if needed; null when signed out. */
|
|
241
|
+
const accessToken = async () => {
|
|
242
|
+
load();
|
|
243
|
+
if (session && session.expiresAt - 60_000 > Date.now())
|
|
244
|
+
return session.accessToken;
|
|
245
|
+
if (!session && !o.cookie)
|
|
246
|
+
return null;
|
|
247
|
+
return (await refresh())?.accessToken ?? null;
|
|
248
|
+
};
|
|
249
|
+
/** A signed-in call: refreshes once and tries again when the server says the token is no good. */
|
|
250
|
+
const authed = async (method, path, body) => {
|
|
251
|
+
const token = await accessToken();
|
|
252
|
+
if (!token)
|
|
253
|
+
throw new AuthClientError("signed_out", 0);
|
|
254
|
+
try {
|
|
255
|
+
return await call(method, path, body, token);
|
|
256
|
+
}
|
|
257
|
+
catch (e) {
|
|
258
|
+
if (!(e instanceof AuthClientError) || e.reason !== "unauthorized")
|
|
259
|
+
throw e;
|
|
260
|
+
const again = (await refresh())?.accessToken;
|
|
261
|
+
if (!again)
|
|
262
|
+
throw new AuthClientError("signed_out", 0);
|
|
263
|
+
return call(method, path, body, again);
|
|
264
|
+
}
|
|
265
|
+
};
|
|
266
|
+
return {
|
|
267
|
+
/** The session kept, or null (in cookie mode, null until `accessToken()` or a sign-in). */
|
|
268
|
+
get session() {
|
|
269
|
+
load();
|
|
270
|
+
return session;
|
|
271
|
+
},
|
|
272
|
+
get user() {
|
|
273
|
+
load();
|
|
274
|
+
return session?.user ?? null;
|
|
275
|
+
},
|
|
276
|
+
/** Called with the session on every change (sign-in, refresh, sign-out); answers a function that stops it. */
|
|
277
|
+
onChange(listener) {
|
|
278
|
+
listeners.add(listener);
|
|
279
|
+
return () => listeners.delete(listener);
|
|
280
|
+
},
|
|
281
|
+
accessToken,
|
|
282
|
+
refresh,
|
|
283
|
+
signInWithApple: (a) => signIn("/apple", a),
|
|
284
|
+
signInWithGoogle: (a) => signIn("/google", a),
|
|
285
|
+
/**
|
|
286
|
+
* GitHub, step one: the address to send the browser to (`location.assign(await auth.startGitHub({...}))`). The
|
|
287
|
+
* state and the PKCE verifier wait in this tab's sessionStorage.
|
|
288
|
+
*/
|
|
289
|
+
async startGitHub(g) {
|
|
290
|
+
const verifier = b64url(crypto.getRandomValues(new Uint8Array(32)));
|
|
291
|
+
const challenge = b64url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))));
|
|
292
|
+
const state = b64url(crypto.getRandomValues(new Uint8Array(16)));
|
|
293
|
+
pending()?.setItem(githubKey, JSON.stringify({ state, verifier, redirectUri: g.redirectUri }));
|
|
294
|
+
const u = new URL("https://github.com/login/oauth/authorize");
|
|
295
|
+
u.searchParams.set("client_id", g.clientId);
|
|
296
|
+
u.searchParams.set("redirect_uri", g.redirectUri);
|
|
297
|
+
u.searchParams.set("scope", g.scope ?? "read:user user:email");
|
|
298
|
+
u.searchParams.set("state", state);
|
|
299
|
+
u.searchParams.set("code_challenge", challenge);
|
|
300
|
+
u.searchParams.set("code_challenge_method", "S256");
|
|
301
|
+
u.searchParams.set("allow_signup", "true");
|
|
302
|
+
return u.toString();
|
|
303
|
+
},
|
|
304
|
+
/** GitHub, step two, on the redirect page: signs in with the code GitHub put in the URL (`location.href`). */
|
|
305
|
+
finishGitHub: async (url = globalThis.location?.href ?? "") => signIn("/github", await githubBack(url)),
|
|
306
|
+
/** Like `finishGitHub`, adding GitHub to the signed-in account. `identity_in_use` (409) when it signs someone else in. */
|
|
307
|
+
linkGitHub: async (url = globalThis.location?.href ?? "") => change("POST", "/link/github", await githubBack(url)),
|
|
308
|
+
startEmail: async (email, locale = globalThis.navigator?.language) => void (await call("POST", "/email/start", { email, locale })),
|
|
309
|
+
verifyEmail: (email, code) => signIn("/email/verify", { email, code }),
|
|
310
|
+
/** A guest: an account with nothing to sign in with yet. Linking a way in later keeps its id and its data. */
|
|
311
|
+
signInAsGuest: (name) => signIn("/guest", name ? { name } : {}),
|
|
312
|
+
/**
|
|
313
|
+
* A guest moved from Supabase Auth: the refresh token of the anonymous session supabase-js kept. Once, at the new
|
|
314
|
+
* version's first start, before anything else; then forget the Supabase session. `invalid_token` when it can't.
|
|
315
|
+
*/
|
|
316
|
+
claimGuest: (supabaseRefreshToken) => signIn("/guest/claim", { supabaseRefreshToken }),
|
|
317
|
+
signInWithPassword: (email, password) => signIn("/password/signin", { email, password }),
|
|
318
|
+
/** After `startEmail(email)`: the code proves the address, and the account is made with this password. */
|
|
319
|
+
signUpWithPassword: (email, code, password) => signIn("/password/signup", { email, code, password }),
|
|
320
|
+
/** After `startEmail(email)`: a new password, and every other device signed out. */
|
|
321
|
+
resetPassword: (email, code, password) => signIn("/password/reset", { email, code, password }),
|
|
322
|
+
/** Sets or changes the signed-in user's password (needs a recent sign-in: `reauth_needed` otherwise). */
|
|
323
|
+
setPassword: async (password) => change("POST", "/password", { password }),
|
|
324
|
+
removePassword: async () => change("DELETE", "/password"),
|
|
325
|
+
/**
|
|
326
|
+
* Adds a way in to the signed-in account (a guest's included, which then stops being one). `identity_in_use`
|
|
327
|
+
* (409) when it signs someone else in: offer to switch to that account instead.
|
|
328
|
+
*/
|
|
329
|
+
linkApple: async (a) => change("POST", "/link/apple", a),
|
|
330
|
+
linkGoogle: async (a) => change("POST", "/link/google", a),
|
|
331
|
+
/** After `startEmail(email)`. */
|
|
332
|
+
linkEmail: async (email, code) => change("POST", "/link/email", { email, code }),
|
|
333
|
+
/** After `startEmail(newEmail)`: the account's address becomes this one. */
|
|
334
|
+
changeEmail: async (email, code) => change("POST", "/email/change", { email, code }),
|
|
335
|
+
/** Removes a way in (`fetchUser()`'s `identities[].id`); never the last (`last_way_in`). */
|
|
336
|
+
unlink: async (identityId) => change("DELETE", `/identity/${encodeURIComponent(identityId)}`),
|
|
337
|
+
startSms: async (phone, locale = globalThis.navigator?.language) => void (await call("POST", "/sms/start", { phone, locale })),
|
|
338
|
+
verifySms: (phone, code) => signIn("/sms/verify", { phone, code }),
|
|
339
|
+
/** Signs in with a passkey the browser or the password manager offers. */
|
|
340
|
+
async signInWithPasskey() {
|
|
341
|
+
const start = await call("POST", "/passkey/signin/start", {});
|
|
342
|
+
const options = requestOptions(start.options);
|
|
343
|
+
const credential = (await navigator.credentials.get({ publicKey: options }));
|
|
344
|
+
if (!credential)
|
|
345
|
+
throw new AuthClientError("cancelled", 0);
|
|
346
|
+
return signIn("/passkey/signin/finish", { challengeId: start.challengeId, credential: assertionJson(credential) });
|
|
347
|
+
},
|
|
348
|
+
/** Makes a passkey for the signed-in user. */
|
|
349
|
+
async registerPasskey(name) {
|
|
350
|
+
const start = await authed("POST", "/passkey/register/start", {});
|
|
351
|
+
const options = creationOptions(start.options);
|
|
352
|
+
const credential = (await navigator.credentials.create({ publicKey: options }));
|
|
353
|
+
if (!credential)
|
|
354
|
+
throw new AuthClientError("cancelled", 0);
|
|
355
|
+
const r = await authed("POST", "/passkey/register/finish", { challengeId: start.challengeId, credential: registrationJson(credential), name });
|
|
356
|
+
return r.passkey;
|
|
357
|
+
},
|
|
358
|
+
deletePasskey: async (id) => void (await authed("DELETE", `/passkey/${encodeURIComponent(id)}`)),
|
|
359
|
+
fetchUser: () => authed("GET", "/user"),
|
|
360
|
+
async signOut(everywhere = false) {
|
|
361
|
+
load();
|
|
362
|
+
try {
|
|
363
|
+
if (session || o.cookie)
|
|
364
|
+
await authed("POST", "/signout", { everywhere });
|
|
365
|
+
}
|
|
366
|
+
catch {
|
|
367
|
+
// Signed out here whatever the server said.
|
|
368
|
+
}
|
|
369
|
+
set(null);
|
|
370
|
+
},
|
|
371
|
+
/**
|
|
372
|
+
* Deletes the account. Needs a recent sign-in (`reauth_needed`, status 401, otherwise: sign in again, then call
|
|
373
|
+
* this). A user who signed in with Apple may get `apple_code_needed` (status 409): run Sign in with Apple JS
|
|
374
|
+
* again and call this with its authorization code.
|
|
375
|
+
*/
|
|
376
|
+
async deleteAccount(appleAuthorizationCode) {
|
|
377
|
+
await authed("DELETE", "/user", appleAuthorizationCode ? { appleAuthorizationCode } : {});
|
|
378
|
+
set(null);
|
|
379
|
+
},
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* A nonce for Sign in with Apple JS: give `hashed` to `AppleID.auth.init({ nonce })` and `raw` to `signInWithApple`.
|
|
384
|
+
* Only the hash is in Apple's token, so the token alone can't be sent again by whoever sees it.
|
|
385
|
+
*/
|
|
386
|
+
export async function appleNonce() {
|
|
387
|
+
const raw = b64url(crypto.getRandomValues(new Uint8Array(32)));
|
|
388
|
+
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(raw)));
|
|
389
|
+
return { raw, hashed: Array.from(digest, (b) => b.toString(16).padStart(2, "0")).join("") };
|
|
390
|
+
}
|
|
391
|
+
// --- WebAuthn JSON, for browsers without PublicKeyCredential.parse*FromJSON ---
|
|
392
|
+
const buf = (s) => fromBase64(s).buffer;
|
|
393
|
+
const str = (b) => (b ? b64url(new Uint8Array(b)) : undefined);
|
|
394
|
+
function creationOptions(j) {
|
|
395
|
+
const user = j.user;
|
|
396
|
+
const exclude = j.excludeCredentials ?? [];
|
|
397
|
+
return {
|
|
398
|
+
...j,
|
|
399
|
+
challenge: buf(j.challenge),
|
|
400
|
+
user: { ...user, id: buf(user.id) },
|
|
401
|
+
excludeCredentials: exclude.map((c) => ({ ...c, id: buf(c.id) })),
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
function requestOptions(j) {
|
|
405
|
+
const allow = j.allowCredentials ?? [];
|
|
406
|
+
return { ...j, challenge: buf(j.challenge), allowCredentials: allow.map((c) => ({ ...c, id: buf(c.id) })) };
|
|
407
|
+
}
|
|
408
|
+
function registrationJson(c) {
|
|
409
|
+
const r = c.response;
|
|
410
|
+
return {
|
|
411
|
+
id: c.id,
|
|
412
|
+
rawId: str(c.rawId),
|
|
413
|
+
type: c.type,
|
|
414
|
+
response: {
|
|
415
|
+
clientDataJSON: str(r.clientDataJSON),
|
|
416
|
+
attestationObject: str(r.attestationObject),
|
|
417
|
+
transports: typeof r.getTransports === "function" ? r.getTransports() : undefined,
|
|
418
|
+
},
|
|
419
|
+
authenticatorAttachment: c.authenticatorAttachment ?? undefined,
|
|
420
|
+
clientExtensionResults: {},
|
|
421
|
+
};
|
|
422
|
+
}
|
|
423
|
+
function assertionJson(c) {
|
|
424
|
+
const r = c.response;
|
|
425
|
+
return {
|
|
426
|
+
id: c.id,
|
|
427
|
+
rawId: str(c.rawId),
|
|
428
|
+
type: c.type,
|
|
429
|
+
response: {
|
|
430
|
+
clientDataJSON: str(r.clientDataJSON),
|
|
431
|
+
authenticatorData: str(r.authenticatorData),
|
|
432
|
+
signature: str(r.signature),
|
|
433
|
+
userHandle: str(r.userHandle),
|
|
434
|
+
},
|
|
435
|
+
authenticatorAttachment: c.authenticatorAttachment ?? undefined,
|
|
436
|
+
clientExtensionResults: {},
|
|
437
|
+
};
|
|
438
|
+
}
|