@tangle-network/sign-in 0.0.0-stage → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +11 -0
- package/README.md +96 -2
- package/dist/index.d.ts +65 -0
- package/dist/index.js +336 -0
- package/package.json +40 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
Copyright (c) 2025 Tangle Network
|
|
2
|
+
|
|
3
|
+
All rights reserved.
|
|
4
|
+
|
|
5
|
+
This software and associated documentation files (the "Software") are proprietary
|
|
6
|
+
and confidential. No part of this Software may be reproduced, distributed, or
|
|
7
|
+
transmitted in any form or by any means, including photocopying, recording, or
|
|
8
|
+
other electronic or mechanical methods, without the prior written permission of
|
|
9
|
+
Tangle Network.
|
|
10
|
+
|
|
11
|
+
For licensing inquiries, contact: hello@tangle.tools
|
package/README.md
CHANGED
|
@@ -1,3 +1,97 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @tangle-network/sign-in
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Small browser client for public Sign in with Tangle applications. It uses OpenID Connect Authorization Code + S256 PKCE. It never reads or forwards the Tangle session cookie.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { createTangleSignIn, mountTangleSignInButton } from "@tangle-network/sign-in";
|
|
7
|
+
|
|
8
|
+
const tangle = createTangleSignIn({
|
|
9
|
+
clientId: "YOUR_PUBLIC_CLIENT_ID",
|
|
10
|
+
redirectUri: "https://app.example.com/auth/tangle/callback",
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
mountTangleSignInButton(document.querySelector("#tangle")!, tangle);
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
On the registered callback:
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
const { user, tokens } = await tangle.handleRedirect();
|
|
20
|
+
console.log(user.sub);
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
The default issuer is `https://id.tangle.tools/api/auth`. Register an exact callback in Developer apps. Browser clients have no client secret. Keep tokens in memory or an application-specific secure session. Sign-in identifies a user. It does not authorize Tangle infrastructure spending.
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
## Validation and transaction lifetime
|
|
27
|
+
|
|
28
|
+
The client delegates OIDC/PKCE processing to `oauth4webapi`. Login requires a
|
|
29
|
+
signed ID token with valid issuer, audience, expiry and the original nonce.
|
|
30
|
+
UserInfo must name the same subject. Refresh is credential renewal, not a new
|
|
31
|
+
user login: any returned ID token must retain the original subject and audience,
|
|
32
|
+
and any returned nonce or authentication time must match the original values.
|
|
33
|
+
A missing refresh ID token, nonce, or authentication-time claim remains allowed.
|
|
34
|
+
UserInfo is checked against the original subject even when refresh omits an ID token.
|
|
35
|
+
|
|
36
|
+
The existing session-state owner retains only token fingerprints and validated
|
|
37
|
+
identity context, partitioned by issuer, client ID and exact callback. It does
|
|
38
|
+
not persist access, refresh or ID tokens. Renewed tokens are returned only if
|
|
39
|
+
the captured session state is still current. A replacement login or revocation
|
|
40
|
+
of a matching current credential invalidates an in-flight refresh.
|
|
41
|
+
Rotation preserves the sign-in generation while replacing token fingerprints.
|
|
42
|
+
Revocation captures that generation before hashing the supplied token, so a
|
|
43
|
+
concurrent rotation cannot escape local invalidation and an older credential
|
|
44
|
+
cannot clear a replacement authentication. This does not recall tokens already
|
|
45
|
+
returned to application code or replace the provider's revocation enforcement.
|
|
46
|
+
Malformed local metadata does not prevent attempting remote revocation.
|
|
47
|
+
Remote revocation is still attempted when browser storage fails. The call
|
|
48
|
+
rejects if local invalidation cannot be confirmed.
|
|
49
|
+
|
|
50
|
+
Reuse one client per configuration: simultaneous refreshes of the same token
|
|
51
|
+
on that client share one request. Applications using multiple instances, tabs,
|
|
52
|
+
or custom shared storage must coordinate their refreshes; this is not a
|
|
53
|
+
cross-process lock. Refresh tokens issued before identity-context storage, or
|
|
54
|
+
whose context was cleared, require a new sign-in. After rotation, replace the
|
|
55
|
+
application's refresh token with the returned token. A failed or ambiguous
|
|
56
|
+
refresh must not substitute another user's credentials.
|
|
57
|
+
|
|
58
|
+
Pending attempts are single-use, expire after ten minutes, and are partitioned
|
|
59
|
+
by issuer, client ID, exact callback and random state. Up to eight concurrent
|
|
60
|
+
attempts per configuration may exist. An unrelated or repeated callback cannot
|
|
61
|
+
consume another attempt. Old v1 pending state is discarded on upgrade; restart
|
|
62
|
+
that login. An interrupted code exchange also requires a new login rather than
|
|
63
|
+
blindly replaying a possibly consumed code.
|
|
64
|
+
|
|
65
|
+
`returnTo` accepts only a same-origin absolute path such as `/account`.
|
|
66
|
+
The library returns it; it does not navigate to it automatically. All protocol
|
|
67
|
+
requests omit cookies, reject redirects and have a bounded timeout. Only an
|
|
68
|
+
explicit loopback HTTP issuer enables local HTTP endpoints; production issuers
|
|
69
|
+
cannot downgrade discovery to loopback HTTP.
|
|
70
|
+
|
|
71
|
+
For a framework-controlled redirect, `await tangle.createAuthorizationURL()`
|
|
72
|
+
prepares the same transaction used by `authorize()` and returns the URL. Use
|
|
73
|
+
one of these methods per attempt, not both.
|
|
74
|
+
|
|
75
|
+
`handleRedirect()` consumes state before its first network request. Match users
|
|
76
|
+
by configured issuer and validated `user.sub`, never by email. Keep access and
|
|
77
|
+
refresh tokens out of shared caches, logs, URLs and browser-persistent storage.
|
|
78
|
+
The package never stores them. Clear callback query parameters after capturing
|
|
79
|
+
the callback URL, including when login fails; see the maintained example.
|
|
80
|
+
|
|
81
|
+
## Reproduce source verification
|
|
82
|
+
|
|
83
|
+
```sh
|
|
84
|
+
pnpm --filter @tangle-network/sign-in build
|
|
85
|
+
node packages/sign-in-with-tangle/test/prove-sign-in-client.mjs
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Run those commands from the repository root. The second command uses real
|
|
89
|
+
signatures and disposable loopback HTTP fixtures to check rejection boundaries;
|
|
90
|
+
it does not claim a live Tangle deployment. The revocation interleavings replay
|
|
91
|
+
actual login/rotation storage writes around the real WebCrypto digest; they do
|
|
92
|
+
not replace signatures or token validation with mocked success responses.
|
|
93
|
+
The Platform browser journey at
|
|
94
|
+
`products/platform/web/tests/browser/auth-tangle-provider.spec.ts` separately
|
|
95
|
+
builds, packs and installs this package, then drives its actual button, login,
|
|
96
|
+
refresh and disconnect against the real local provider and proxy. No token
|
|
97
|
+
response is stubbed in that journey.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
//#region src/index.d.ts
|
|
2
|
+
interface TangleSignInOptions {
|
|
3
|
+
clientId: string;
|
|
4
|
+
redirectUri: string;
|
|
5
|
+
issuer?: string;
|
|
6
|
+
scope?: string;
|
|
7
|
+
storage?: Storage;
|
|
8
|
+
fetch?: typeof globalThis.fetch;
|
|
9
|
+
}
|
|
10
|
+
interface TangleUser {
|
|
11
|
+
sub: string;
|
|
12
|
+
email?: string;
|
|
13
|
+
email_verified?: boolean;
|
|
14
|
+
name?: string;
|
|
15
|
+
picture?: string;
|
|
16
|
+
[claim: string]: unknown;
|
|
17
|
+
}
|
|
18
|
+
interface TangleTokenSet {
|
|
19
|
+
access_token: string;
|
|
20
|
+
token_type: string;
|
|
21
|
+
expires_in?: number;
|
|
22
|
+
refresh_token?: string;
|
|
23
|
+
id_token?: string;
|
|
24
|
+
scope?: string;
|
|
25
|
+
}
|
|
26
|
+
interface TangleSignInResult {
|
|
27
|
+
user: TangleUser;
|
|
28
|
+
tokens: TangleTokenSet;
|
|
29
|
+
}
|
|
30
|
+
declare class TangleSignIn {
|
|
31
|
+
readonly clientId: string;
|
|
32
|
+
readonly redirectUri: string;
|
|
33
|
+
readonly issuer: string;
|
|
34
|
+
readonly scope: string;
|
|
35
|
+
private readonly state;
|
|
36
|
+
private readonly client;
|
|
37
|
+
private readonly refreshing;
|
|
38
|
+
private readonly http;
|
|
39
|
+
constructor(options: TangleSignInOptions);
|
|
40
|
+
private discovery;
|
|
41
|
+
/** Prepare a login for a caller-controlled navigation; authorize() uses this too. */
|
|
42
|
+
createAuthorizationURL(options?: {
|
|
43
|
+
returnTo?: string;
|
|
44
|
+
prompt?: string;
|
|
45
|
+
}): Promise<URL>;
|
|
46
|
+
authorize(options?: {
|
|
47
|
+
returnTo?: string;
|
|
48
|
+
prompt?: string;
|
|
49
|
+
}): Promise<never>;
|
|
50
|
+
handleRedirect(url?: string): Promise<TangleSignInResult & {
|
|
51
|
+
returnTo?: string;
|
|
52
|
+
}>;
|
|
53
|
+
private userInfo;
|
|
54
|
+
/** Coalesce refreshes on this client; other instances must serialize theirs. */
|
|
55
|
+
refresh(refreshToken: string): Promise<TangleTokenSet>;
|
|
56
|
+
private refreshBound;
|
|
57
|
+
revoke(token: string, tokenTypeHint?: "access_token" | "refresh_token"): Promise<void>;
|
|
58
|
+
}
|
|
59
|
+
declare function createTangleSignIn(options: TangleSignInOptions): TangleSignIn;
|
|
60
|
+
declare function mountTangleSignInButton(target: HTMLElement, client: TangleSignIn, options?: {
|
|
61
|
+
label?: string;
|
|
62
|
+
returnTo?: string;
|
|
63
|
+
}): HTMLButtonElement;
|
|
64
|
+
//#endregion
|
|
65
|
+
export { TangleSignIn, TangleSignInOptions, TangleSignInResult, TangleTokenSet, TangleUser, createTangleSignIn, mountTangleSignInButton };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
import * as oauth from "oauth4webapi";
|
|
2
|
+
//#region src/login-state.ts
|
|
3
|
+
const MAX_AGE_MS = 600 * 1e3;
|
|
4
|
+
const MAX_PENDING = 8;
|
|
5
|
+
const RANDOM_VALUE = /^[A-Za-z0-9_-]{43}$/;
|
|
6
|
+
function parsePending(raw, now) {
|
|
7
|
+
const value = JSON.parse(raw);
|
|
8
|
+
if (!value || typeof value !== "object") throw new Error("Invalid login state");
|
|
9
|
+
const pending = value;
|
|
10
|
+
if (typeof pending.state !== "string" || !RANDOM_VALUE.test(pending.state) || typeof pending.nonce !== "string" || !RANDOM_VALUE.test(pending.nonce) || typeof pending.verifier !== "string" || !RANDOM_VALUE.test(pending.verifier) || typeof pending.createdAt !== "number" || !Number.isFinite(pending.createdAt) || pending.createdAt > now || now - pending.createdAt >= MAX_AGE_MS || pending.returnTo !== void 0 && typeof pending.returnTo !== "string") throw new Error("Invalid or expired login state; sign in again");
|
|
11
|
+
return pending;
|
|
12
|
+
}
|
|
13
|
+
const TOKEN_HASH = /^[0-9a-f]{64}$/;
|
|
14
|
+
function parseSession(raw) {
|
|
15
|
+
const value = JSON.parse(raw);
|
|
16
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid refresh identity; sign in again");
|
|
17
|
+
const session = value;
|
|
18
|
+
if (typeof session.subject !== "string" || !session.subject || typeof session.audience !== "string" || !session.audience || typeof session.nonce !== "string" || !RANDOM_VALUE.test(session.nonce) || typeof session.revision !== "string" || !session.revision || typeof session.refreshHash !== "string" || !TOKEN_HASH.test(session.refreshHash) || typeof session.accessHash !== "string" || !TOKEN_HASH.test(session.accessHash) || session.authTime !== void 0 && (typeof session.authTime !== "number" || !Number.isFinite(session.authTime))) throw new Error("Invalid refresh identity; sign in again");
|
|
19
|
+
return session;
|
|
20
|
+
}
|
|
21
|
+
async function tokenHash(token) {
|
|
22
|
+
if (!token) throw new Error("A nonempty token is required");
|
|
23
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token));
|
|
24
|
+
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
25
|
+
}
|
|
26
|
+
var LoginState = class {
|
|
27
|
+
prefix;
|
|
28
|
+
sessionKey;
|
|
29
|
+
constructor(storage, binding) {
|
|
30
|
+
this.storage = storage;
|
|
31
|
+
this.prefix = `tangle.signin.pending.v2:${JSON.stringify(binding)}:`;
|
|
32
|
+
this.sessionKey = `tangle.signin.session.v1:${JSON.stringify(binding)}`;
|
|
33
|
+
storage.removeItem("tangle.signin.pending.v1");
|
|
34
|
+
}
|
|
35
|
+
save(pending) {
|
|
36
|
+
let active = 0;
|
|
37
|
+
const now = Date.now();
|
|
38
|
+
const keys = Array.from({ length: this.storage.length }, (_, i) => this.storage.key(i));
|
|
39
|
+
for (const key of keys) {
|
|
40
|
+
if (!key?.startsWith(this.prefix)) continue;
|
|
41
|
+
try {
|
|
42
|
+
parsePending(this.storage.getItem(key) ?? "", now);
|
|
43
|
+
active++;
|
|
44
|
+
} catch {
|
|
45
|
+
this.storage.removeItem(key);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
if (active >= MAX_PENDING) throw new Error("Too many pending sign-ins; finish an existing login or wait for it to expire");
|
|
49
|
+
this.storage.setItem(this.prefix + pending.state, JSON.stringify(pending));
|
|
50
|
+
}
|
|
51
|
+
/** Consume synchronously, before discovery or token I/O. Other attempts survive. */
|
|
52
|
+
take(state) {
|
|
53
|
+
if (!RANDOM_VALUE.test(state)) throw new Error("Invalid authorization state");
|
|
54
|
+
const key = this.prefix + state;
|
|
55
|
+
const raw = this.storage.getItem(key);
|
|
56
|
+
if (raw === null) throw new Error("Missing login state; sign in again");
|
|
57
|
+
this.storage.removeItem(key);
|
|
58
|
+
const pending = parsePending(raw, Date.now());
|
|
59
|
+
if (pending.state !== state) throw new Error("Authorization state mismatch");
|
|
60
|
+
return pending;
|
|
61
|
+
}
|
|
62
|
+
/** Capture one session generation before any refresh network request. */
|
|
63
|
+
async refreshSession(token) {
|
|
64
|
+
const raw = this.storage.getItem(this.sessionKey);
|
|
65
|
+
if (raw === null) throw new Error("Refresh identity is unavailable; sign in again");
|
|
66
|
+
const session = parseSession(raw);
|
|
67
|
+
if (session.refreshHash !== await tokenHash(token)) throw new Error("Refresh token does not belong to the current sign-in");
|
|
68
|
+
this.assertSession(raw);
|
|
69
|
+
return {
|
|
70
|
+
...session,
|
|
71
|
+
raw
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
assertSession(raw) {
|
|
75
|
+
if (this.storage.getItem(this.sessionKey) !== raw) throw new Error("Tangle session changed while refreshing");
|
|
76
|
+
}
|
|
77
|
+
/** Only fingerprints and validated claims survive page reloads, never tokens. */
|
|
78
|
+
async rememberSession(refreshToken, accessToken, identity, expected) {
|
|
79
|
+
const session = refreshToken === void 0 ? void 0 : {
|
|
80
|
+
...identity,
|
|
81
|
+
revision: expected === void 0 ? crypto.randomUUID() : parseSession(expected).revision,
|
|
82
|
+
refreshHash: await tokenHash(refreshToken),
|
|
83
|
+
accessHash: await tokenHash(accessToken)
|
|
84
|
+
};
|
|
85
|
+
if (expected !== void 0) this.assertSession(expected);
|
|
86
|
+
if (session) this.storage.setItem(this.sessionKey, JSON.stringify(session));
|
|
87
|
+
else this.storage.removeItem(this.sessionKey);
|
|
88
|
+
}
|
|
89
|
+
/** Invalidate a matching local session before awaiting remote revocation. */
|
|
90
|
+
async forgetSession(token) {
|
|
91
|
+
const raw = this.storage.getItem(this.sessionKey);
|
|
92
|
+
if (raw === null) return;
|
|
93
|
+
let session;
|
|
94
|
+
try {
|
|
95
|
+
session = parseSession(raw);
|
|
96
|
+
} catch {
|
|
97
|
+
this.storage.removeItem(this.sessionKey);
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
const hash = await tokenHash(token);
|
|
101
|
+
if (hash !== session.refreshHash && hash !== session.accessHash) return;
|
|
102
|
+
const current = this.storage.getItem(this.sessionKey);
|
|
103
|
+
if (current === null) return;
|
|
104
|
+
try {
|
|
105
|
+
if (parseSession(current).revision !== session.revision) return;
|
|
106
|
+
} catch {}
|
|
107
|
+
this.storage.removeItem(this.sessionKey);
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
//#endregion
|
|
111
|
+
//#region src/index.ts
|
|
112
|
+
function audienceKey(aud) {
|
|
113
|
+
return JSON.stringify([...new Set(Array.isArray(aud) ? aud : [aud])].sort());
|
|
114
|
+
}
|
|
115
|
+
const DEFAULT_ISSUER = "https://id.tangle.tools/api/auth";
|
|
116
|
+
const RESPONSE_PARAMETERS = new Set([
|
|
117
|
+
"code",
|
|
118
|
+
"state",
|
|
119
|
+
"iss",
|
|
120
|
+
"error",
|
|
121
|
+
"error_description",
|
|
122
|
+
"error_uri",
|
|
123
|
+
"response",
|
|
124
|
+
"session_state"
|
|
125
|
+
]);
|
|
126
|
+
function secureUrl(value, allowLoopback) {
|
|
127
|
+
const url = new URL(value);
|
|
128
|
+
const loopback = [
|
|
129
|
+
"localhost",
|
|
130
|
+
"127.0.0.1",
|
|
131
|
+
"[::1]"
|
|
132
|
+
].includes(url.hostname);
|
|
133
|
+
if (/[\s\\]/.test(value) || url.username || url.password || value.includes("#") || url.protocol !== "https:" && !(allowLoopback && loopback && url.protocol === "http:")) throw new Error("OAuth URLs require HTTPS (or local development loopback HTTP), without credentials or fragments");
|
|
134
|
+
return url;
|
|
135
|
+
}
|
|
136
|
+
function localReturnTo(value, redirectUri) {
|
|
137
|
+
if (value === void 0) return void 0;
|
|
138
|
+
if (!value.startsWith("/") || value.startsWith("//") || /[\s\\]/.test(value) || [...value].some((character) => character.charCodeAt(0) < 32) || new URL(value, redirectUri).origin !== new URL(redirectUri).origin) throw new Error("returnTo must be a same-origin absolute path");
|
|
139
|
+
return value;
|
|
140
|
+
}
|
|
141
|
+
var TangleSignIn = class {
|
|
142
|
+
clientId;
|
|
143
|
+
redirectUri;
|
|
144
|
+
issuer;
|
|
145
|
+
scope;
|
|
146
|
+
state;
|
|
147
|
+
client;
|
|
148
|
+
refreshing = /* @__PURE__ */ new Map();
|
|
149
|
+
http;
|
|
150
|
+
constructor(options) {
|
|
151
|
+
if (!options.clientId.trim()) throw new Error("clientId is required");
|
|
152
|
+
this.clientId = options.clientId;
|
|
153
|
+
this.client = { client_id: this.clientId };
|
|
154
|
+
this.redirectUri = options.redirectUri;
|
|
155
|
+
if ([...secureUrl(this.redirectUri, true).searchParams.keys()].some((name) => RESPONSE_PARAMETERS.has(name))) throw new Error("Registered callbacks cannot contain OAuth response parameters");
|
|
156
|
+
this.issuer = options.issuer ?? DEFAULT_ISSUER;
|
|
157
|
+
const issuer = secureUrl(this.issuer, true);
|
|
158
|
+
if (issuer.search || this.issuer.includes("?")) throw new Error("Issuer cannot contain a query");
|
|
159
|
+
const localDevelopment = issuer.protocol === "http:";
|
|
160
|
+
this.scope = options.scope ?? "openid profile email offline_access";
|
|
161
|
+
if (!this.scope.split(/\s+/).includes("openid")) throw new Error("Sign in requires the openid scope");
|
|
162
|
+
this.state = new LoginState(options.storage ?? sessionStorage, [
|
|
163
|
+
this.issuer,
|
|
164
|
+
this.clientId,
|
|
165
|
+
this.redirectUri
|
|
166
|
+
]);
|
|
167
|
+
const transport = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
168
|
+
this.http = {
|
|
169
|
+
[oauth.allowInsecureRequests]: localDevelopment,
|
|
170
|
+
[oauth.customFetch]: (url, init) => {
|
|
171
|
+
secureUrl(url, localDevelopment);
|
|
172
|
+
return transport(url, {
|
|
173
|
+
...init,
|
|
174
|
+
credentials: "omit",
|
|
175
|
+
redirect: "error",
|
|
176
|
+
signal: init.signal ?? AbortSignal.timeout(15e3)
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
async discovery() {
|
|
182
|
+
const issuer = new URL(this.issuer);
|
|
183
|
+
const response = await oauth.discoveryRequest(issuer, this.http);
|
|
184
|
+
const server = await oauth.processDiscoveryResponse(issuer, response);
|
|
185
|
+
if (server.issuer !== this.issuer) throw new Error("Tangle discovery issuer mismatch");
|
|
186
|
+
for (const field of [
|
|
187
|
+
"authorization_endpoint",
|
|
188
|
+
"token_endpoint",
|
|
189
|
+
"userinfo_endpoint",
|
|
190
|
+
"jwks_uri"
|
|
191
|
+
]) {
|
|
192
|
+
if (typeof server[field] !== "string" || !server[field]) throw new Error(`Discovery is missing ${field}`);
|
|
193
|
+
secureUrl(server[field], issuer.protocol === "http:");
|
|
194
|
+
}
|
|
195
|
+
if (server.revocation_endpoint) secureUrl(server.revocation_endpoint, issuer.protocol === "http:");
|
|
196
|
+
return server;
|
|
197
|
+
}
|
|
198
|
+
/** Prepare a login for a caller-controlled navigation; authorize() uses this too. */
|
|
199
|
+
async createAuthorizationURL(options = {}) {
|
|
200
|
+
const returnTo = localReturnTo(options.returnTo, this.redirectUri);
|
|
201
|
+
const server = await this.discovery();
|
|
202
|
+
const pending = {
|
|
203
|
+
state: oauth.generateRandomState(),
|
|
204
|
+
nonce: oauth.generateRandomNonce(),
|
|
205
|
+
verifier: oauth.generateRandomCodeVerifier(),
|
|
206
|
+
createdAt: Date.now(),
|
|
207
|
+
returnTo
|
|
208
|
+
};
|
|
209
|
+
const url = new URL(server.authorization_endpoint);
|
|
210
|
+
for (const [key, value] of Object.entries({
|
|
211
|
+
client_id: this.clientId,
|
|
212
|
+
redirect_uri: this.redirectUri,
|
|
213
|
+
response_type: "code",
|
|
214
|
+
scope: this.scope,
|
|
215
|
+
state: pending.state,
|
|
216
|
+
nonce: pending.nonce,
|
|
217
|
+
code_challenge: await oauth.calculatePKCECodeChallenge(pending.verifier),
|
|
218
|
+
code_challenge_method: "S256"
|
|
219
|
+
})) url.searchParams.set(key, value);
|
|
220
|
+
if (options.prompt) url.searchParams.set("prompt", options.prompt);
|
|
221
|
+
this.state.save(pending);
|
|
222
|
+
return url;
|
|
223
|
+
}
|
|
224
|
+
async authorize(options = {}) {
|
|
225
|
+
location.assign((await this.createAuthorizationURL(options)).href);
|
|
226
|
+
return new Promise(() => void 0);
|
|
227
|
+
}
|
|
228
|
+
async handleRedirect(url = location.href) {
|
|
229
|
+
const callback = secureUrl(url, true);
|
|
230
|
+
const registered = new URL(this.redirectUri);
|
|
231
|
+
if (callback.origin !== registered.origin || callback.pathname !== registered.pathname) throw new Error("Authorization response arrived on a different callback");
|
|
232
|
+
for (const name of new Set(registered.searchParams.keys())) if (JSON.stringify(callback.searchParams.getAll(name)) !== JSON.stringify(registered.searchParams.getAll(name))) throw new Error("Authorization callback query mismatch");
|
|
233
|
+
const states = callback.searchParams.getAll("state");
|
|
234
|
+
if (states.length !== 1) throw new Error("Authorization response requires exactly one state");
|
|
235
|
+
const pending = this.state.take(states[0]);
|
|
236
|
+
const server = await this.discovery();
|
|
237
|
+
const parameters = oauth.validateAuthResponse(server, this.client, callback, pending.state);
|
|
238
|
+
const response = await oauth.authorizationCodeGrantRequest(server, this.client, oauth.None(), parameters, this.redirectUri, pending.verifier, this.http);
|
|
239
|
+
const tokens = await oauth.processAuthorizationCodeResponse(server, this.client, response, {
|
|
240
|
+
expectedNonce: pending.nonce,
|
|
241
|
+
requireIdToken: true
|
|
242
|
+
});
|
|
243
|
+
await oauth.validateApplicationLevelSignature(server, response, this.http);
|
|
244
|
+
const claims = oauth.getValidatedIdTokenClaims(tokens);
|
|
245
|
+
if (!claims) throw new Error("Validated ID token is required");
|
|
246
|
+
const user = await this.userInfo(server, tokens.access_token, claims.sub);
|
|
247
|
+
await this.state.rememberSession(tokens.refresh_token, tokens.access_token, {
|
|
248
|
+
subject: claims.sub,
|
|
249
|
+
audience: audienceKey(claims.aud),
|
|
250
|
+
nonce: pending.nonce,
|
|
251
|
+
authTime: claims.auth_time
|
|
252
|
+
});
|
|
253
|
+
return {
|
|
254
|
+
user,
|
|
255
|
+
tokens,
|
|
256
|
+
returnTo: localReturnTo(pending.returnTo, this.redirectUri)
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
async userInfo(server, accessToken, subject) {
|
|
260
|
+
const info = await oauth.userInfoRequest(server, this.client, accessToken, this.http);
|
|
261
|
+
const user = await oauth.processUserInfoResponse(server, this.client, subject, info);
|
|
262
|
+
if (info.headers.get("content-type")?.split(";")[0].trim() === "application/jwt") await oauth.validateApplicationLevelSignature(server, info, this.http);
|
|
263
|
+
return user;
|
|
264
|
+
}
|
|
265
|
+
/** Coalesce refreshes on this client; other instances must serialize theirs. */
|
|
266
|
+
refresh(refreshToken) {
|
|
267
|
+
const existing = this.refreshing.get(refreshToken);
|
|
268
|
+
if (existing) return existing;
|
|
269
|
+
const request = this.refreshBound(refreshToken).finally(() => {
|
|
270
|
+
this.refreshing.delete(refreshToken);
|
|
271
|
+
});
|
|
272
|
+
this.refreshing.set(refreshToken, request);
|
|
273
|
+
return request;
|
|
274
|
+
}
|
|
275
|
+
async refreshBound(refreshToken) {
|
|
276
|
+
const session = await this.state.refreshSession(refreshToken);
|
|
277
|
+
const server = await this.discovery();
|
|
278
|
+
this.state.assertSession(session.raw);
|
|
279
|
+
const response = await oauth.refreshTokenGrantRequest(server, this.client, oauth.None(), refreshToken, this.http);
|
|
280
|
+
const tokens = await oauth.processRefreshTokenResponse(server, this.client, response);
|
|
281
|
+
const claims = oauth.getValidatedIdTokenClaims(tokens);
|
|
282
|
+
if (claims) {
|
|
283
|
+
await oauth.validateApplicationLevelSignature(server, response, this.http);
|
|
284
|
+
if (claims.sub !== session.subject || audienceKey(claims.aud) !== session.audience || claims.nonce !== void 0 && claims.nonce !== session.nonce || claims.auth_time !== void 0 && claims.auth_time !== session.authTime) throw new Error("Refreshed identity does not match the original sign-in");
|
|
285
|
+
}
|
|
286
|
+
await this.userInfo(server, tokens.access_token, session.subject);
|
|
287
|
+
await this.state.rememberSession(tokens.refresh_token ?? refreshToken, tokens.access_token, {
|
|
288
|
+
subject: session.subject,
|
|
289
|
+
audience: session.audience,
|
|
290
|
+
nonce: session.nonce,
|
|
291
|
+
authTime: session.authTime
|
|
292
|
+
}, session.raw);
|
|
293
|
+
return tokens;
|
|
294
|
+
}
|
|
295
|
+
async revoke(token, tokenTypeHint) {
|
|
296
|
+
let localFailure;
|
|
297
|
+
let localFailed = false;
|
|
298
|
+
try {
|
|
299
|
+
await this.state.forgetSession(token);
|
|
300
|
+
} catch (error) {
|
|
301
|
+
localFailure = error;
|
|
302
|
+
localFailed = true;
|
|
303
|
+
}
|
|
304
|
+
try {
|
|
305
|
+
const server = await this.discovery();
|
|
306
|
+
const response = await oauth.revocationRequest(server, this.client, oauth.None(), token, {
|
|
307
|
+
...this.http,
|
|
308
|
+
...tokenTypeHint ? { additionalParameters: { token_type_hint: tokenTypeHint } } : {}
|
|
309
|
+
});
|
|
310
|
+
await oauth.processRevocationResponse(response);
|
|
311
|
+
} catch (remoteFailure) {
|
|
312
|
+
if (localFailed) throw new AggregateError([localFailure, remoteFailure], "Local and remote token revocation failed");
|
|
313
|
+
throw remoteFailure;
|
|
314
|
+
}
|
|
315
|
+
if (localFailed) throw localFailure;
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
function createTangleSignIn(options) {
|
|
319
|
+
return new TangleSignIn(options);
|
|
320
|
+
}
|
|
321
|
+
function mountTangleSignInButton(target, client, options = {}) {
|
|
322
|
+
const button = document.createElement("button");
|
|
323
|
+
button.type = "button";
|
|
324
|
+
button.textContent = options.label ?? "Sign in with Tangle";
|
|
325
|
+
button.addEventListener("click", () => {
|
|
326
|
+
button.disabled = true;
|
|
327
|
+
client.authorize({ returnTo: options.returnTo }).catch((error) => {
|
|
328
|
+
button.disabled = false;
|
|
329
|
+
target.dispatchEvent(new CustomEvent("tangle-signin-error", { detail: error }));
|
|
330
|
+
});
|
|
331
|
+
});
|
|
332
|
+
target.replaceChildren(button);
|
|
333
|
+
return button;
|
|
334
|
+
}
|
|
335
|
+
//#endregion
|
|
336
|
+
export { TangleSignIn, createTangleSignIn, mountTangleSignInButton };
|
package/package.json
CHANGED
|
@@ -1,6 +1,43 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tangle-network/sign-in",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.2.1",
|
|
4
|
+
"description": "Drop-in Sign in with Tangle browser client",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"import": "./dist/index.js",
|
|
11
|
+
"types": "./dist/index.d.ts"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "https://github.com/tangle-network/agent-container",
|
|
17
|
+
"directory": "packages/sign-in-with-tangle"
|
|
18
|
+
},
|
|
19
|
+
"publishConfig": {
|
|
20
|
+
"access": "public",
|
|
21
|
+
"registry": "https://registry.npmjs.org"
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"dist",
|
|
25
|
+
"README.md"
|
|
26
|
+
],
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"tsdown": "0.21.10",
|
|
29
|
+
"typescript": "^6.0.3"
|
|
30
|
+
},
|
|
31
|
+
"dependencies": {
|
|
32
|
+
"oauth4webapi": "3.8.8"
|
|
33
|
+
},
|
|
34
|
+
"tangleRelease": {
|
|
35
|
+
"sourceSha": "ee7221645e1dd25f4bc3ebe69286b336ce92eda2",
|
|
36
|
+
"mergedAt": "2026-10-27T01:07:43-06:00"
|
|
37
|
+
},
|
|
38
|
+
"scripts": {
|
|
39
|
+
"build": "tsdown",
|
|
40
|
+
"check-types": "node ../../scripts/tsc-native.mjs --noEmit",
|
|
41
|
+
"test": "pnpm build && node test/prove-sign-in-client.mjs"
|
|
42
|
+
}
|
|
6
43
|
}
|