@happyvertical/smrt-social 0.61.5 → 0.61.6
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/AGENTS.md +1 -1
- package/README.md +43 -0
- package/dist/chunks/social-account-collection-B4PZKbUC.js +432 -0
- package/dist/chunks/social-account-collection-B4PZKbUC.js.map +1 -0
- package/dist/connect/flow.d.ts +62 -0
- package/dist/connect/flow.d.ts.map +1 -0
- package/dist/connect/index.d.ts +5 -0
- package/dist/connect/index.d.ts.map +1 -0
- package/dist/connect/registry.d.ts +6 -0
- package/dist/connect/registry.d.ts.map +1 -0
- package/dist/connect/types.d.ts +79 -0
- package/dist/connect/types.d.ts.map +1 -0
- package/dist/connect/x.d.ts +11 -0
- package/dist/connect/x.d.ts.map +1 -0
- package/dist/connect.d.ts +2 -0
- package/dist/connect.d.ts.map +1 -0
- package/dist/connect.js +250 -0
- package/dist/connect.js.map +1 -0
- package/dist/index.js +4 -425
- package/dist/index.js.map +1 -1
- package/dist/manifest.json +21 -6
- package/dist/oauth-state.d.ts +5 -0
- package/dist/oauth-state.d.ts.map +1 -1
- package/dist/smrt-knowledge.json +12 -5
- package/dist/smrt-knowledge.okf.md +3 -2
- package/package.json +13 -9
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Social account connect flow: provider contract.
|
|
3
|
+
*
|
|
4
|
+
* A provider knows one platform's OAuth dialect (authorize URL, scopes, PKCE,
|
|
5
|
+
* client authentication, token request, profile lookup). The flow in
|
|
6
|
+
* `./flow.ts` owns everything shared: state, tenancy, secret storage, account
|
|
7
|
+
* upsert. Hosts mount two routes and supply client credentials.
|
|
8
|
+
*/
|
|
9
|
+
import type { SocialPlatformType } from '../social-account.js';
|
|
10
|
+
/** Client credentials issued by the platform's developer console. */
|
|
11
|
+
export interface SocialClientCredentials {
|
|
12
|
+
clientId: string;
|
|
13
|
+
clientSecret: string;
|
|
14
|
+
}
|
|
15
|
+
/** Tokens returned by a platform token endpoint. */
|
|
16
|
+
export interface SocialTokenSet {
|
|
17
|
+
accessToken: string;
|
|
18
|
+
refreshToken?: string;
|
|
19
|
+
tokenType?: string;
|
|
20
|
+
/** Absolute expiry of the access token, when the platform reports one. */
|
|
21
|
+
expiresAt?: Date;
|
|
22
|
+
scopes: string[];
|
|
23
|
+
}
|
|
24
|
+
/** The authenticated platform account. */
|
|
25
|
+
export interface SocialProfile {
|
|
26
|
+
id: string;
|
|
27
|
+
username: string;
|
|
28
|
+
name?: string | null;
|
|
29
|
+
url?: string | null;
|
|
30
|
+
}
|
|
31
|
+
export interface SocialAuthorizeRequest {
|
|
32
|
+
client: SocialClientCredentials;
|
|
33
|
+
redirectUri: string;
|
|
34
|
+
state: string;
|
|
35
|
+
scopes: string[];
|
|
36
|
+
/** S256 challenge; present when the provider `usesPkce`. */
|
|
37
|
+
codeChallenge?: string;
|
|
38
|
+
}
|
|
39
|
+
export interface SocialCodeExchange {
|
|
40
|
+
client: SocialClientCredentials;
|
|
41
|
+
redirectUri: string;
|
|
42
|
+
code: string;
|
|
43
|
+
codeVerifier?: string | null;
|
|
44
|
+
fetch: typeof fetch;
|
|
45
|
+
}
|
|
46
|
+
export interface SocialConnectProvider {
|
|
47
|
+
platform: SocialPlatformType;
|
|
48
|
+
label: string;
|
|
49
|
+
/** Environment variables a host sets to supply client credentials. */
|
|
50
|
+
clientEnv: {
|
|
51
|
+
clientId: string;
|
|
52
|
+
clientSecret: string;
|
|
53
|
+
};
|
|
54
|
+
/** Legacy env names read when the primary pair is unset (compat with older hosts). */
|
|
55
|
+
clientEnvFallbacks?: Array<{
|
|
56
|
+
clientId: string;
|
|
57
|
+
clientSecret: string;
|
|
58
|
+
}>;
|
|
59
|
+
defaultScopes: string[];
|
|
60
|
+
usesPkce: boolean;
|
|
61
|
+
buildAuthorizeUrl(request: SocialAuthorizeRequest): string;
|
|
62
|
+
exchangeCode(request: SocialCodeExchange): Promise<SocialTokenSet>;
|
|
63
|
+
fetchProfile(accessToken: string, fetchImpl: typeof fetch): Promise<SocialProfile>;
|
|
64
|
+
/**
|
|
65
|
+
* The credential payload stored in smrt-secrets. Includes client id/secret
|
|
66
|
+
* so a publisher can refresh without extra configuration.
|
|
67
|
+
*/
|
|
68
|
+
toCredentials(tokens: SocialTokenSet, profile: SocialProfile, client: SocialClientCredentials): Record<string, unknown>;
|
|
69
|
+
}
|
|
70
|
+
export type SocialConnectErrorCode = 'unsupported_platform' | 'missing_client_credentials' | 'missing_tenant' | 'invalid_state' | 'state_expired' | 'access_denied' | 'provider_error' | 'token_exchange_failed' | 'profile_lookup_failed';
|
|
71
|
+
/**
|
|
72
|
+
* Raised for every connect failure. Messages are safe to show to a user and
|
|
73
|
+
* never contain tokens, codes, or client secrets.
|
|
74
|
+
*/
|
|
75
|
+
export declare class SocialConnectError extends Error {
|
|
76
|
+
readonly code: SocialConnectErrorCode;
|
|
77
|
+
constructor(code: SocialConnectErrorCode, message: string);
|
|
78
|
+
}
|
|
79
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/connect/types.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAE/D,qEAAqE;AACrE,MAAM,WAAW,uBAAuB;IACtC,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,MAAM,CAAC;CACtB;AAED,oDAAoD;AACpD,MAAM,WAAW,cAAc;IAC7B,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,0EAA0E;IAC1E,SAAS,CAAC,EAAE,IAAI,CAAC;IACjB,MAAM,EAAE,MAAM,EAAE,CAAC;CAClB;AAED,0CAA0C;AAC1C,MAAM,WAAW,aAAa;IAC5B,EAAE,EAAE,MAAM,CAA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,EACtB,OAAO,EAAE,aAAa,EACtB,MAAM,EAAE,uBAAuB,GAC9B,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAC5B;AAED,MAAM,MAAM,sBAAsB,GAC9B,sBAAsB,GACtB,4BAA4B,GAC5B,gBAAgB,GAChB,eAAe,GACf,eAAe,GACf,eAAe,GACf,gBAAgB,GAChB,uBAAuB,GACvB,uBAAuB,CAAC;AAE5B;;;GAGG;AACH,qBAAa,kBAAmB,SAAQ,KAAK;IAEzC,QAAQ,CAAC,IAAI,EAAE,sBAAsB;gBAA5B,IAAI,EAAE,sBAAsB,EACrC,OAAO,EAAE,MAAM;CAKlB"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* X (Twitter) connect provider: OAuth 2.0 authorization code with PKCE and a
|
|
3
|
+
* confidential client (HTTP Basic client authentication).
|
|
4
|
+
*/
|
|
5
|
+
import type { SocialConnectProvider } from './types.js';
|
|
6
|
+
export declare const X_AUTHORIZE_URL = "https://x.com/i/oauth2/authorize";
|
|
7
|
+
export declare const X_TOKEN_URL = "https://api.x.com/2/oauth2/token";
|
|
8
|
+
export declare const X_ME_URL = "https://api.x.com/2/users/me";
|
|
9
|
+
export declare const X_DEFAULT_SCOPES: string[];
|
|
10
|
+
export declare const xConnectProvider: SocialConnectProvider;
|
|
11
|
+
//# sourceMappingURL=x.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"x.d.ts","sourceRoot":"","sources":["../../src/connect/x.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAEV,qBAAqB,EAGtB,MAAM,YAAY,CAAC;AAGpB,eAAO,MAAM,eAAe,qCAAqC,CAAC;AAClE,eAAO,MAAM,WAAW,qCAAqC,CAAC;AAC9D,eAAO,MAAM,QAAQ,iCAAiC,CAAC;AAEvD,eAAO,MAAM,gBAAgB,UAM5B,CAAC;AAiBF,eAAO,MAAM,gBAAgB,EAAE,qBA0H9B,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connect.d.ts","sourceRoot":"","sources":["../src/connect.ts"],"names":[],"mappings":"AAAA,cAAc,oBAAoB,CAAC"}
|
package/dist/connect.js
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
import { i as OAuthState, r as OAuthStateCollection, t as SocialAccountCollection } from "./chunks/social-account-collection-B4PZKbUC.js";
|
|
2
|
+
import { getDefaultSocialAccountName } from "./server.js";
|
|
3
|
+
import { getCurrentTenant, withTenant } from "@happyvertical/smrt-tenancy";
|
|
4
|
+
//#region src/connect/types.ts
|
|
5
|
+
var SocialConnectError = class extends Error {
|
|
6
|
+
constructor(code, message) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.code = code;
|
|
9
|
+
this.name = "SocialConnectError";
|
|
10
|
+
}
|
|
11
|
+
code;
|
|
12
|
+
};
|
|
13
|
+
//#endregion
|
|
14
|
+
//#region src/connect/x.ts
|
|
15
|
+
var X_AUTHORIZE_URL = "https://x.com/i/oauth2/authorize";
|
|
16
|
+
var X_TOKEN_URL = "https://api.x.com/2/oauth2/token";
|
|
17
|
+
var X_ME_URL = "https://api.x.com/2/users/me";
|
|
18
|
+
var X_DEFAULT_SCOPES = [
|
|
19
|
+
"tweet.read",
|
|
20
|
+
"tweet.write",
|
|
21
|
+
"users.read",
|
|
22
|
+
"offline.access",
|
|
23
|
+
"media.write"
|
|
24
|
+
];
|
|
25
|
+
function basicAuth({ clientId, clientSecret }) {
|
|
26
|
+
return `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString("base64")}`;
|
|
27
|
+
}
|
|
28
|
+
var xConnectProvider = {
|
|
29
|
+
platform: "x",
|
|
30
|
+
label: "X",
|
|
31
|
+
clientEnv: {
|
|
32
|
+
clientId: "X_CLIENT_ID",
|
|
33
|
+
clientSecret: "X_CLIENT_SECRET"
|
|
34
|
+
},
|
|
35
|
+
clientEnvFallbacks: [{
|
|
36
|
+
clientId: "TWITTER_CLIENT_ID",
|
|
37
|
+
clientSecret: "TWITTER_CLIENT_SECRET"
|
|
38
|
+
}],
|
|
39
|
+
defaultScopes: X_DEFAULT_SCOPES,
|
|
40
|
+
usesPkce: true,
|
|
41
|
+
buildAuthorizeUrl({ client, redirectUri, state, scopes, codeChallenge }) {
|
|
42
|
+
const url = new URL(X_AUTHORIZE_URL);
|
|
43
|
+
url.searchParams.set("response_type", "code");
|
|
44
|
+
url.searchParams.set("client_id", client.clientId);
|
|
45
|
+
url.searchParams.set("redirect_uri", redirectUri);
|
|
46
|
+
url.searchParams.set("scope", scopes.join(" "));
|
|
47
|
+
url.searchParams.set("state", state);
|
|
48
|
+
if (codeChallenge) {
|
|
49
|
+
url.searchParams.set("code_challenge", codeChallenge);
|
|
50
|
+
url.searchParams.set("code_challenge_method", "S256");
|
|
51
|
+
}
|
|
52
|
+
return url.toString();
|
|
53
|
+
},
|
|
54
|
+
async exchangeCode({ client, redirectUri, code, codeVerifier, fetch: fetchImpl }) {
|
|
55
|
+
const body = new URLSearchParams({
|
|
56
|
+
grant_type: "authorization_code",
|
|
57
|
+
code,
|
|
58
|
+
redirect_uri: redirectUri,
|
|
59
|
+
client_id: client.clientId
|
|
60
|
+
});
|
|
61
|
+
if (codeVerifier) body.set("code_verifier", codeVerifier);
|
|
62
|
+
const response = await fetchImpl(X_TOKEN_URL, {
|
|
63
|
+
method: "POST",
|
|
64
|
+
headers: {
|
|
65
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
66
|
+
authorization: basicAuth(client)
|
|
67
|
+
},
|
|
68
|
+
body
|
|
69
|
+
});
|
|
70
|
+
const json = await response.json().catch(() => null);
|
|
71
|
+
if (!response.ok || typeof json?.access_token !== "string" || !json.access_token) throw new SocialConnectError("token_exchange_failed", `X rejected the authorization code (HTTP ${response.status}).`);
|
|
72
|
+
const tokens = {
|
|
73
|
+
accessToken: json.access_token,
|
|
74
|
+
tokenType: typeof json.token_type === "string" ? json.token_type : void 0,
|
|
75
|
+
scopes: typeof json.scope === "string" && json.scope ? json.scope.split(" ") : []
|
|
76
|
+
};
|
|
77
|
+
if (typeof json.refresh_token === "string" && json.refresh_token) tokens.refreshToken = json.refresh_token;
|
|
78
|
+
if (typeof json.expires_in === "number") tokens.expiresAt = new Date(Date.now() + json.expires_in * 1e3);
|
|
79
|
+
return tokens;
|
|
80
|
+
},
|
|
81
|
+
async fetchProfile(accessToken, fetchImpl) {
|
|
82
|
+
const response = await fetchImpl(X_ME_URL, { headers: { authorization: `Bearer ${accessToken}` } });
|
|
83
|
+
const data = (await response.json().catch(() => null))?.data;
|
|
84
|
+
if (!response.ok || typeof data?.id !== "string" || typeof data.username !== "string") throw new SocialConnectError("profile_lookup_failed", `Could not read the X profile after connecting (HTTP ${response.status}).`);
|
|
85
|
+
return {
|
|
86
|
+
id: data.id,
|
|
87
|
+
username: data.username,
|
|
88
|
+
name: typeof data.name === "string" ? data.name : null,
|
|
89
|
+
url: `https://x.com/${data.username}`
|
|
90
|
+
};
|
|
91
|
+
},
|
|
92
|
+
toCredentials(tokens, profile, client) {
|
|
93
|
+
const credentials = {
|
|
94
|
+
authType: "oauth2",
|
|
95
|
+
accessToken: tokens.accessToken,
|
|
96
|
+
clientId: client.clientId,
|
|
97
|
+
clientSecret: client.clientSecret,
|
|
98
|
+
userId: profile.id,
|
|
99
|
+
scopes: tokens.scopes
|
|
100
|
+
};
|
|
101
|
+
if (tokens.refreshToken) credentials.refreshToken = tokens.refreshToken;
|
|
102
|
+
if (tokens.tokenType) credentials.tokenType = tokens.tokenType;
|
|
103
|
+
if (tokens.expiresAt) {
|
|
104
|
+
credentials.expiresAt = tokens.expiresAt.toISOString();
|
|
105
|
+
credentials.tokenExpiresAt = credentials.expiresAt;
|
|
106
|
+
}
|
|
107
|
+
return credentials;
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
//#endregion
|
|
111
|
+
//#region src/connect/registry.ts
|
|
112
|
+
var providers = /* @__PURE__ */ new Map([[xConnectProvider.platform, xConnectProvider]]);
|
|
113
|
+
function registerSocialConnectProvider(provider) {
|
|
114
|
+
providers.set(provider.platform, provider);
|
|
115
|
+
}
|
|
116
|
+
function getSocialConnectProvider(platform) {
|
|
117
|
+
return providers.get(platform);
|
|
118
|
+
}
|
|
119
|
+
function listSocialConnectProviders() {
|
|
120
|
+
return [...providers.values()];
|
|
121
|
+
}
|
|
122
|
+
//#endregion
|
|
123
|
+
//#region src/connect/flow.ts
|
|
124
|
+
function resolveProvider(platform) {
|
|
125
|
+
const provider = getSocialConnectProvider(platform);
|
|
126
|
+
if (!provider) throw new SocialConnectError("unsupported_platform", `Connecting ${platform} is not supported.`);
|
|
127
|
+
return provider;
|
|
128
|
+
}
|
|
129
|
+
function resolveClient(provider, options) {
|
|
130
|
+
if (options.client?.clientId && options.client.clientSecret) return options.client;
|
|
131
|
+
const env = options.env ?? process.env;
|
|
132
|
+
for (const names of [provider.clientEnv, ...provider.clientEnvFallbacks ?? []]) {
|
|
133
|
+
const clientId = env[names.clientId];
|
|
134
|
+
const clientSecret = env[names.clientSecret];
|
|
135
|
+
if (clientId && clientSecret) return {
|
|
136
|
+
clientId,
|
|
137
|
+
clientSecret
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
throw new SocialConnectError("missing_client_credentials", `${provider.label} is not configured: set ${provider.clientEnv.clientId} and ${provider.clientEnv.clientSecret}.`);
|
|
141
|
+
}
|
|
142
|
+
function resolveTenantId(options) {
|
|
143
|
+
const tenantId = options.tenantId ?? getCurrentTenant()?.tenantId;
|
|
144
|
+
if (!tenantId) throw new SocialConnectError("missing_tenant", "A tenant is required to connect a social account.");
|
|
145
|
+
return tenantId;
|
|
146
|
+
}
|
|
147
|
+
function inTenant(tenantId, fn) {
|
|
148
|
+
return getCurrentTenant()?.tenantId === tenantId ? fn() : withTenant({ tenantId }, fn);
|
|
149
|
+
}
|
|
150
|
+
function isSocialConnectConfigured(platform, options = {}) {
|
|
151
|
+
const provider = getSocialConnectProvider(platform);
|
|
152
|
+
if (!provider) return false;
|
|
153
|
+
try {
|
|
154
|
+
resolveClient(provider, { ...options });
|
|
155
|
+
return true;
|
|
156
|
+
} catch {
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
async function startSocialConnect(options) {
|
|
161
|
+
const provider = resolveProvider(options.platform);
|
|
162
|
+
const client = resolveClient(provider, options);
|
|
163
|
+
const tenantId = resolveTenantId(options);
|
|
164
|
+
const scopes = options.scopes ?? provider.defaultScopes;
|
|
165
|
+
const state = OAuthState.generateState();
|
|
166
|
+
const codeVerifier = provider.usesPkce ? OAuthState.generateCodeVerifier() : null;
|
|
167
|
+
const codeChallenge = codeVerifier ? await OAuthState.generateCodeChallenge(codeVerifier) : void 0;
|
|
168
|
+
await inTenant(tenantId, async () => {
|
|
169
|
+
await (await OAuthStateCollection.create({ db: options.db })).create({
|
|
170
|
+
platform: provider.platform,
|
|
171
|
+
state,
|
|
172
|
+
codeVerifier,
|
|
173
|
+
redirectUri: options.redirectUri,
|
|
174
|
+
scopes,
|
|
175
|
+
tenantId,
|
|
176
|
+
initiatedByUserId: options.userId ?? null,
|
|
177
|
+
expiresAt: new Date(Date.now() + (options.ttlMs ?? 600 * 1e3))
|
|
178
|
+
});
|
|
179
|
+
});
|
|
180
|
+
return { authorizeUrl: provider.buildAuthorizeUrl({
|
|
181
|
+
client,
|
|
182
|
+
redirectUri: options.redirectUri,
|
|
183
|
+
state,
|
|
184
|
+
scopes,
|
|
185
|
+
codeChallenge
|
|
186
|
+
}) };
|
|
187
|
+
}
|
|
188
|
+
async function completeSocialConnect(options) {
|
|
189
|
+
const provider = resolveProvider(options.platform);
|
|
190
|
+
const client = resolveClient(provider, options);
|
|
191
|
+
const tenantId = resolveTenantId(options);
|
|
192
|
+
const fetchImpl = options.fetch ?? fetch;
|
|
193
|
+
const { code, state: stateToken, error } = options.query;
|
|
194
|
+
return inTenant(tenantId, async () => {
|
|
195
|
+
const states = await OAuthStateCollection.create({ db: options.db });
|
|
196
|
+
const stored = stateToken ? await states.findByState(stateToken) : null;
|
|
197
|
+
if (!stored || stored.platform !== provider.platform || stored.tenantId !== tenantId || stored.redirectUri !== options.redirectUri || stored.initiatedByUserId !== null && stored.initiatedByUserId !== (options.userId ?? null)) throw new SocialConnectError("invalid_state", "This connect link is not valid. Start the connection again.");
|
|
198
|
+
if (!await states.consume(stored)) throw new SocialConnectError("invalid_state", "This connect link was already used. Start the connection again.");
|
|
199
|
+
if (stored.isExpired) throw new SocialConnectError("state_expired", "This connect link expired. Start the connection again.");
|
|
200
|
+
if (error) throw new SocialConnectError(error === "access_denied" ? "access_denied" : "provider_error", error === "access_denied" ? `${provider.label} access was not granted.` : `${provider.label} returned an error (${error.slice(0, 64)}).`);
|
|
201
|
+
if (!code) throw new SocialConnectError("provider_error", `${provider.label} did not return an authorization code.`);
|
|
202
|
+
const tokens = await provider.exchangeCode({
|
|
203
|
+
client,
|
|
204
|
+
redirectUri: stored.redirectUri,
|
|
205
|
+
code,
|
|
206
|
+
codeVerifier: stored.codeVerifier,
|
|
207
|
+
fetch: fetchImpl
|
|
208
|
+
});
|
|
209
|
+
const profile = await provider.fetchProfile(tokens.accessToken, fetchImpl);
|
|
210
|
+
const accounts = await SocialAccountCollection.create({ db: options.db });
|
|
211
|
+
const [existing] = await accounts.list({
|
|
212
|
+
where: {
|
|
213
|
+
platform: provider.platform,
|
|
214
|
+
platformUserId: profile.id,
|
|
215
|
+
tenantId
|
|
216
|
+
},
|
|
217
|
+
limit: 1
|
|
218
|
+
});
|
|
219
|
+
const account = existing ?? await accounts.create({
|
|
220
|
+
name: options.accountName ?? getDefaultSocialAccountName(provider.platform, `@${profile.username}`),
|
|
221
|
+
platform: provider.platform,
|
|
222
|
+
tenantId
|
|
223
|
+
});
|
|
224
|
+
const created = !existing;
|
|
225
|
+
account.platformUserId = profile.id;
|
|
226
|
+
account.platformUsername = profile.username;
|
|
227
|
+
account.platformUrl = profile.url ?? null;
|
|
228
|
+
account.tokenExpiresAt = tokens.expiresAt ?? null;
|
|
229
|
+
account.scopes = tokens.scopes.length ? tokens.scopes : stored.scopes;
|
|
230
|
+
account.missingPermissions = [];
|
|
231
|
+
account.status = "connected";
|
|
232
|
+
account.errorMessage = null;
|
|
233
|
+
account.isActive = true;
|
|
234
|
+
await account.setCredentials(provider.toCredentials(tokens, profile, client), { description: `${provider.label} credentials for @${profile.username}` });
|
|
235
|
+
return {
|
|
236
|
+
account,
|
|
237
|
+
created
|
|
238
|
+
};
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
function socialConnectHrefs(basePath, platforms) {
|
|
242
|
+
const base = basePath.replace(/\/$/, "");
|
|
243
|
+
const hrefs = {};
|
|
244
|
+
for (const platform of platforms ?? ["x"]) if (getSocialConnectProvider(platform)) hrefs[platform] = `${base}/${platform}`;
|
|
245
|
+
return hrefs;
|
|
246
|
+
}
|
|
247
|
+
//#endregion
|
|
248
|
+
export { SocialConnectError, X_AUTHORIZE_URL, X_DEFAULT_SCOPES, X_ME_URL, X_TOKEN_URL, completeSocialConnect, getSocialConnectProvider, isSocialConnectConfigured, listSocialConnectProviders, registerSocialConnectProvider, socialConnectHrefs, startSocialConnect, xConnectProvider };
|
|
249
|
+
|
|
250
|
+
//# sourceMappingURL=connect.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connect.js","names":[],"sources":["../src/connect/types.ts","../src/connect/x.ts","../src/connect/registry.ts","../src/connect/flow.ts"],"sourcesContent":["/**\n * Social account connect flow: provider contract.\n *\n * A provider knows one platform's OAuth dialect (authorize URL, scopes, PKCE,\n * client authentication, token request, profile lookup). The flow in\n * `./flow.ts` owns everything shared: state, tenancy, secret storage, account\n * upsert. Hosts mount two routes and supply client credentials.\n */\n\nimport type { SocialPlatformType } from '../social-account.js';\n\n/** Client credentials issued by the platform's developer console. */\nexport interface SocialClientCredentials {\n clientId: string;\n clientSecret: string;\n}\n\n/** Tokens returned by a platform token endpoint. */\nexport interface SocialTokenSet {\n accessToken: string;\n refreshToken?: string;\n tokenType?: string;\n /** Absolute expiry of the access token, when the platform reports one. */\n expiresAt?: Date;\n scopes: string[];\n}\n\n/** The authenticated platform account. */\nexport interface SocialProfile {\n id: string;\n username: string;\n name?: string | null;\n url?: string | null;\n}\n\nexport interface SocialAuthorizeRequest {\n client: SocialClientCredentials;\n redirectUri: string;\n state: string;\n scopes: string[];\n /** S256 challenge; present when the provider `usesPkce`. */\n codeChallenge?: string;\n}\n\nexport interface SocialCodeExchange {\n client: SocialClientCredentials;\n redirectUri: string;\n code: string;\n codeVerifier?: string | null;\n fetch: typeof fetch;\n}\n\nexport interface SocialConnectProvider {\n platform: SocialPlatformType;\n label: string;\n /** Environment variables a host sets to supply client credentials. */\n clientEnv: { clientId: string; clientSecret: string };\n /** Legacy env names read when the primary pair is unset (compat with older hosts). */\n clientEnvFallbacks?: Array<{ clientId: string; clientSecret: string }>;\n defaultScopes: string[];\n usesPkce: boolean;\n buildAuthorizeUrl(request: SocialAuthorizeRequest): string;\n exchangeCode(request: SocialCodeExchange): Promise<SocialTokenSet>;\n fetchProfile(\n accessToken: string,\n fetchImpl: typeof fetch,\n ): Promise<SocialProfile>;\n /**\n * The credential payload stored in smrt-secrets. Includes client id/secret\n * so a publisher can refresh without extra configuration.\n */\n toCredentials(\n tokens: SocialTokenSet,\n profile: SocialProfile,\n client: SocialClientCredentials,\n ): Record<string, unknown>;\n}\n\nexport type SocialConnectErrorCode =\n | 'unsupported_platform'\n | 'missing_client_credentials'\n | 'missing_tenant'\n | 'invalid_state'\n | 'state_expired'\n | 'access_denied'\n | 'provider_error'\n | 'token_exchange_failed'\n | 'profile_lookup_failed';\n\n/**\n * Raised for every connect failure. Messages are safe to show to a user and\n * never contain tokens, codes, or client secrets.\n */\nexport class SocialConnectError extends Error {\n constructor(\n readonly code: SocialConnectErrorCode,\n message: string,\n ) {\n super(message);\n this.name = 'SocialConnectError';\n }\n}\n","/**\n * X (Twitter) connect provider: OAuth 2.0 authorization code with PKCE and a\n * confidential client (HTTP Basic client authentication).\n */\n\nimport type {\n SocialClientCredentials,\n SocialConnectProvider,\n SocialProfile,\n SocialTokenSet,\n} from './types.js';\nimport { SocialConnectError } from './types.js';\n\nexport const X_AUTHORIZE_URL = 'https://x.com/i/oauth2/authorize';\nexport const X_TOKEN_URL = 'https://api.x.com/2/oauth2/token';\nexport const X_ME_URL = 'https://api.x.com/2/users/me';\n\nexport const X_DEFAULT_SCOPES = [\n 'tweet.read',\n 'tweet.write',\n 'users.read',\n 'offline.access',\n 'media.write',\n];\n\nfunction basicAuth({\n clientId,\n clientSecret,\n}: SocialClientCredentials): string {\n return `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString('base64')}`;\n}\n\ninterface XTokenBody {\n access_token?: unknown;\n refresh_token?: unknown;\n token_type?: unknown;\n expires_in?: unknown;\n scope?: unknown;\n}\n\nexport const xConnectProvider: SocialConnectProvider = {\n platform: 'x',\n label: 'X',\n clientEnv: { clientId: 'X_CLIENT_ID', clientSecret: 'X_CLIENT_SECRET' },\n clientEnvFallbacks: [\n { clientId: 'TWITTER_CLIENT_ID', clientSecret: 'TWITTER_CLIENT_SECRET' },\n ],\n defaultScopes: X_DEFAULT_SCOPES,\n usesPkce: true,\n\n buildAuthorizeUrl({ client, redirectUri, state, scopes, codeChallenge }) {\n const url = new URL(X_AUTHORIZE_URL);\n url.searchParams.set('response_type', 'code');\n url.searchParams.set('client_id', client.clientId);\n url.searchParams.set('redirect_uri', redirectUri);\n url.searchParams.set('scope', scopes.join(' '));\n url.searchParams.set('state', state);\n if (codeChallenge) {\n url.searchParams.set('code_challenge', codeChallenge);\n url.searchParams.set('code_challenge_method', 'S256');\n }\n return url.toString();\n },\n\n async exchangeCode({\n client,\n redirectUri,\n code,\n codeVerifier,\n fetch: fetchImpl,\n }) {\n const body = new URLSearchParams({\n grant_type: 'authorization_code',\n code,\n redirect_uri: redirectUri,\n client_id: client.clientId,\n });\n if (codeVerifier) body.set('code_verifier', codeVerifier);\n\n const response = await fetchImpl(X_TOKEN_URL, {\n method: 'POST',\n headers: {\n 'content-type': 'application/x-www-form-urlencoded',\n authorization: basicAuth(client),\n },\n body,\n });\n const json = (await response.json().catch(() => null)) as XTokenBody | null;\n if (\n !response.ok ||\n typeof json?.access_token !== 'string' ||\n !json.access_token\n ) {\n // Never echo the response body: it can carry provider detail we do not\n // control. Status is enough to debug.\n throw new SocialConnectError(\n 'token_exchange_failed',\n `X rejected the authorization code (HTTP ${response.status}).`,\n );\n }\n const tokens: SocialTokenSet = {\n accessToken: json.access_token,\n tokenType:\n typeof json.token_type === 'string' ? json.token_type : undefined,\n scopes:\n typeof json.scope === 'string' && json.scope\n ? json.scope.split(' ')\n : [],\n };\n if (typeof json.refresh_token === 'string' && json.refresh_token) {\n tokens.refreshToken = json.refresh_token;\n }\n if (typeof json.expires_in === 'number') {\n tokens.expiresAt = new Date(Date.now() + json.expires_in * 1000);\n }\n return tokens;\n },\n\n async fetchProfile(accessToken, fetchImpl): Promise<SocialProfile> {\n const response = await fetchImpl(X_ME_URL, {\n headers: { authorization: `Bearer ${accessToken}` },\n });\n const json = (await response.json().catch(() => null)) as {\n data?: { id?: unknown; username?: unknown; name?: unknown };\n } | null;\n const data = json?.data;\n if (\n !response.ok ||\n typeof data?.id !== 'string' ||\n typeof data.username !== 'string'\n ) {\n throw new SocialConnectError(\n 'profile_lookup_failed',\n `Could not read the X profile after connecting (HTTP ${response.status}).`,\n );\n }\n return {\n id: data.id,\n username: data.username,\n name: typeof data.name === 'string' ? data.name : null,\n url: `https://x.com/${data.username}`,\n };\n },\n\n // The shape @happyvertical/garrula reads for X OAuth 2.0 user tokens.\n toCredentials(tokens, profile, client) {\n const credentials: Record<string, unknown> = {\n authType: 'oauth2',\n accessToken: tokens.accessToken,\n clientId: client.clientId,\n clientSecret: client.clientSecret,\n userId: profile.id,\n scopes: tokens.scopes,\n };\n if (tokens.refreshToken) credentials.refreshToken = tokens.refreshToken;\n if (tokens.tokenType) credentials.tokenType = tokens.tokenType;\n if (tokens.expiresAt) {\n credentials.expiresAt = tokens.expiresAt.toISOString();\n credentials.tokenExpiresAt = credentials.expiresAt;\n }\n return credentials;\n },\n};\n","import type { SocialPlatformType } from '../social-account.js';\nimport type { SocialConnectProvider } from './types.js';\nimport { xConnectProvider } from './x.js';\n\nconst providers = new Map<SocialPlatformType, SocialConnectProvider>([\n [xConnectProvider.platform, xConnectProvider],\n]);\n\n/** Register (or replace) a provider. Hosts can add platforms without a release. */\nexport function registerSocialConnectProvider(\n provider: SocialConnectProvider,\n): void {\n providers.set(provider.platform, provider);\n}\n\nexport function getSocialConnectProvider(\n platform: string,\n): SocialConnectProvider | undefined {\n return providers.get(platform as SocialPlatformType);\n}\n\nexport function listSocialConnectProviders(): SocialConnectProvider[] {\n return [...providers.values()];\n}\n","/**\n * Provider-agnostic social account connect flow.\n *\n * `startSocialConnect` builds the authorize URL and persists a single-use,\n * tenant-bound `OAuthState`. `completeSocialConnect` verifies the callback,\n * exchanges the code, reads the profile, stores the tokens in smrt-secrets\n * (via `SocialAccount.setCredentials`) and creates or updates the account in\n * `dry_run`. The host mounts two routes, supplies the tenant, and redirects.\n * No role checks live here; authorize before calling.\n */\n\nimport { getCurrentTenant, withTenant } from '@happyvertical/smrt-tenancy';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport { OAuthStateCollection } from '../collections/oauth-state-collection.js';\nimport { SocialAccountCollection } from '../collections/social-account-collection.js';\nimport { OAuthState } from '../oauth-state.js';\nimport { getDefaultSocialAccountName } from '../server.js';\nimport type { SocialAccount } from '../social-account.js';\nimport { getSocialConnectProvider } from './registry.js';\nimport {\n type SocialClientCredentials,\n SocialConnectError,\n type SocialConnectProvider,\n} from './types.js';\n\nexport interface SocialConnectContext {\n db: DatabaseInterface;\n /** Defaults to the current tenant context. */\n tenantId?: string;\n /**\n * The signed-in user making the request. When start supplies it, complete\n * must supply the same user or the callback is rejected before the state is\n * consumed. Hosts should always pass it.\n */\n userId?: string;\n /** Platform id from the route, e.g. `x`. */\n platform: string;\n /** The callback URL registered with the platform. */\n redirectUri: string;\n /** Explicit credentials; otherwise read from the provider's env names. */\n client?: SocialClientCredentials;\n env?: Record<string, string | undefined>;\n fetch?: typeof fetch;\n}\n\nexport interface StartSocialConnectOptions extends SocialConnectContext {\n scopes?: string[];\n /** State lifetime in ms. Default 10 minutes. */\n ttlMs?: number;\n}\n\nexport interface CompleteSocialConnectOptions extends SocialConnectContext {\n /** The callback's query parameters. */\n query: { code?: string | null; state?: string | null; error?: string | null };\n /** Display name for a newly created account. */\n accountName?: string;\n}\n\nexport interface CompletedSocialConnect {\n account: SocialAccount;\n created: boolean;\n}\n\nfunction resolveProvider(platform: string): SocialConnectProvider {\n const provider = getSocialConnectProvider(platform);\n if (!provider) {\n throw new SocialConnectError(\n 'unsupported_platform',\n `Connecting ${platform} is not supported.`,\n );\n }\n return provider;\n}\n\nfunction resolveClient(\n provider: SocialConnectProvider,\n options: SocialConnectContext,\n): SocialClientCredentials {\n if (options.client?.clientId && options.client.clientSecret) {\n return options.client;\n }\n const env = options.env ?? process.env;\n for (const names of [\n provider.clientEnv,\n ...(provider.clientEnvFallbacks ?? []),\n ]) {\n const clientId = env[names.clientId];\n const clientSecret = env[names.clientSecret];\n if (clientId && clientSecret) return { clientId, clientSecret };\n }\n throw new SocialConnectError(\n 'missing_client_credentials',\n `${provider.label} is not configured: set ${provider.clientEnv.clientId} and ${provider.clientEnv.clientSecret}.`,\n );\n}\n\nfunction resolveTenantId(options: SocialConnectContext): string {\n const tenantId = options.tenantId ?? getCurrentTenant()?.tenantId;\n if (!tenantId) {\n throw new SocialConnectError(\n 'missing_tenant',\n 'A tenant is required to connect a social account.',\n );\n }\n return tenantId;\n}\n\nfunction inTenant<T>(tenantId: string, fn: () => Promise<T>): Promise<T> {\n return getCurrentTenant()?.tenantId === tenantId\n ? fn()\n : withTenant({ tenantId }, fn);\n}\n\n/** Whether the provider's client credentials are available (for UI gating). */\nexport function isSocialConnectConfigured(\n platform: string,\n options: Pick<SocialConnectContext, 'client' | 'env'> = {},\n): boolean {\n const provider = getSocialConnectProvider(platform);\n if (!provider) return false;\n try {\n resolveClient(provider, { ...options } as SocialConnectContext);\n return true;\n } catch {\n return false;\n }\n}\n\n/** Begin a connect: returns the URL to redirect the user to. */\nexport async function startSocialConnect(\n options: StartSocialConnectOptions,\n): Promise<{ authorizeUrl: string }> {\n const provider = resolveProvider(options.platform);\n const client = resolveClient(provider, options);\n const tenantId = resolveTenantId(options);\n const scopes = options.scopes ?? provider.defaultScopes;\n\n const state = OAuthState.generateState();\n const codeVerifier = provider.usesPkce\n ? OAuthState.generateCodeVerifier()\n : null;\n const codeChallenge = codeVerifier\n ? await OAuthState.generateCodeChallenge(codeVerifier)\n : undefined;\n\n await inTenant(tenantId, async () => {\n const states = await OAuthStateCollection.create({ db: options.db });\n await states.create({\n platform: provider.platform,\n state,\n codeVerifier,\n redirectUri: options.redirectUri,\n scopes,\n tenantId,\n initiatedByUserId: options.userId ?? null,\n expiresAt: new Date(Date.now() + (options.ttlMs ?? 10 * 60 * 1000)),\n });\n });\n\n return {\n authorizeUrl: provider.buildAuthorizeUrl({\n client,\n redirectUri: options.redirectUri,\n state,\n scopes,\n codeChallenge,\n }),\n };\n}\n\n/** Finish a connect from the platform's callback. */\nexport async function completeSocialConnect(\n options: CompleteSocialConnectOptions,\n): Promise<CompletedSocialConnect> {\n const provider = resolveProvider(options.platform);\n const client = resolveClient(provider, options);\n const tenantId = resolveTenantId(options);\n const fetchImpl = options.fetch ?? fetch;\n const { code, state: stateToken, error } = options.query;\n\n return inTenant(tenantId, async () => {\n const states = await OAuthStateCollection.create({ db: options.db });\n\n // Always burn the state first when we can find it, including for a\n // refused grant, so a callback URL cannot be replayed.\n const stored = stateToken ? await states.findByState(stateToken) : null;\n if (\n !stored ||\n stored.platform !== provider.platform ||\n stored.tenantId !== tenantId ||\n stored.redirectUri !== options.redirectUri ||\n (stored.initiatedByUserId !== null &&\n stored.initiatedByUserId !== (options.userId ?? null))\n ) {\n throw new SocialConnectError(\n 'invalid_state',\n 'This connect link is not valid. Start the connection again.',\n );\n }\n const consumed = await states.consume(stored);\n if (!consumed) {\n throw new SocialConnectError(\n 'invalid_state',\n 'This connect link was already used. Start the connection again.',\n );\n }\n if (stored.isExpired) {\n throw new SocialConnectError(\n 'state_expired',\n 'This connect link expired. Start the connection again.',\n );\n }\n if (error) {\n throw new SocialConnectError(\n error === 'access_denied' ? 'access_denied' : 'provider_error',\n error === 'access_denied'\n ? `${provider.label} access was not granted.`\n : `${provider.label} returned an error (${error.slice(0, 64)}).`,\n );\n }\n if (!code) {\n throw new SocialConnectError(\n 'provider_error',\n `${provider.label} did not return an authorization code.`,\n );\n }\n\n const tokens = await provider.exchangeCode({\n client,\n redirectUri: stored.redirectUri,\n code,\n codeVerifier: stored.codeVerifier,\n fetch: fetchImpl,\n });\n const profile = await provider.fetchProfile(tokens.accessToken, fetchImpl);\n\n const accounts = await SocialAccountCollection.create({ db: options.db });\n const [existing] = await accounts.list({\n where: {\n platform: provider.platform,\n platformUserId: profile.id,\n tenantId,\n },\n limit: 1,\n });\n\n const account =\n existing ??\n (await accounts.create({\n name:\n options.accountName ??\n getDefaultSocialAccountName(\n provider.platform,\n `@${profile.username}`,\n ),\n platform: provider.platform,\n tenantId,\n }));\n const created = !existing;\n\n account.platformUserId = profile.id;\n account.platformUsername = profile.username;\n account.platformUrl = profile.url ?? null;\n account.tokenExpiresAt = tokens.expiresAt ?? null;\n account.scopes = tokens.scopes.length ? tokens.scopes : stored.scopes;\n account.missingPermissions = [];\n account.status = 'connected';\n account.errorMessage = null;\n account.isActive = true;\n // publishMode stays as-is: new accounts start in the platform default\n // (dry_run for X); a reconnect never widens an existing account.\n\n // setCredentials stores the payload in smrt-secrets and saves the account.\n await account.setCredentials(\n provider.toCredentials(tokens, profile, client),\n { description: `${provider.label} credentials for @${profile.username}` },\n );\n return { account, created };\n });\n}\n\n/** Hrefs for `SocialAccountSettings`: `<basePath>/<platform>` per provider. */\nexport function socialConnectHrefs(\n basePath: string,\n platforms?: string[],\n): Record<string, string> {\n const base = basePath.replace(/\\/$/, '');\n const hrefs: Record<string, string> = {};\n for (const platform of platforms ?? ['x']) {\n if (getSocialConnectProvider(platform))\n hrefs[platform] = `${base}/${platform}`;\n }\n return hrefs;\n}\n"],"mappings":";;;;AA6FO,IAAM,qBAAN,cAAiC,MAAM;CAC5C,YACW,MACT,SACA;EACA,MAAM,OAAO;EAHJ,KAAA,OAAA;EAIT,KAAK,OAAO;CACd;CALW;AAMb;;;ACxFO,IAAM,kBAAkB;AACxB,IAAM,cAAc;AACpB,IAAM,WAAW;AAEjB,IAAM,mBAAmB;CAC9B;CACA;CACA;CACA;CACA;AACF;AAEA,SAAS,UAAU,EACjB,UACA,gBACkC;CAClC,OAAO,SAAS,OAAO,KAAK,GAAG,SAAQ,GAAI,cAAc,CAAA,CAAE,SAAS,QAAQ;AAC9E;AAUO,IAAM,mBAA0C;CACrD,UAAU;CACV,OAAO;CACP,WAAW;EAAE,UAAU;EAAe,cAAc;CAAkB;CACtE,oBAAoB,CAClB;EAAE,UAAU;EAAqB,cAAc;CAAwB,CACzE;CACA,eAAe;CACf,UAAU;CAEV,kBAAkB,EAAE,QAAQ,aAAa,OAAO,QAAQ,iBAAiB;EACvE,MAAM,MAAM,IAAI,IAAI,eAAe;EACnC,IAAI,aAAa,IAAI,iBAAiB,MAAM;EAC5C,IAAI,aAAa,IAAI,aAAa,OAAO,QAAQ;EACjD,IAAI,aAAa,IAAI,gBAAgB,WAAW;EAChD,IAAI,aAAa,IAAI,SAAS,OAAO,KAAK,GAAG,CAAC;EAC9C,IAAI,aAAa,IAAI,SAAS,KAAK;EACnC,IAAI,eAAe;GACjB,IAAI,aAAa,IAAI,kBAAkB,aAAa;GACpD,IAAI,aAAa,IAAI,yBAAyB,MAAM;EACtD;EACA,OAAO,IAAI,SAAS;CACtB;CAEA,MAAM,aAAa,EACjB,QACA,aACA,MACA,cACA,OAAO,aACN;EACD,MAAM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