@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
package/AGENTS.md
CHANGED
|
@@ -12,7 +12,7 @@ Social media account management with OAuth and post scheduling. Supports YouTube
|
|
|
12
12
|
|
|
13
13
|
## Gotchas
|
|
14
14
|
|
|
15
|
-
- **Tokens
|
|
15
|
+
- **Tokens**: raw `accessToken`/`refreshToken` columns are deprecated plaintext. The connect flow (`@happyvertical/smrt-social/connect`, X provider; state single-use + tenant-bound) stores credentials in smrt-secrets via `setCredentials`, never in those columns.
|
|
16
16
|
- **No auto-publishing**: `scheduledAt` is metadata only — app must implement job runner to trigger publishing
|
|
17
17
|
- **Analytics manual**: `analytics` field must be updated by platform sync, not auto-populated
|
|
18
18
|
- **Platform enum hardcoded**: youtube/threads/x/bluesky — extending requires code changes
|
package/README.md
CHANGED
|
@@ -55,6 +55,49 @@ await state.save();
|
|
|
55
55
|
// `await states.consume(state)` (false = already used) before exchanging the code
|
|
56
56
|
```
|
|
57
57
|
|
|
58
|
+
## Connecting accounts (OAuth)
|
|
59
|
+
|
|
60
|
+
`@happyvertical/smrt-social/connect` owns the connect flow so hosts mount two
|
|
61
|
+
routes and write no platform code. X is the first provider (OAuth 2.0
|
|
62
|
+
authorization code with PKCE, confidential client); register more with
|
|
63
|
+
`registerSocialConnectProvider`.
|
|
64
|
+
|
|
65
|
+
```typescript
|
|
66
|
+
import {
|
|
67
|
+
completeSocialConnect,
|
|
68
|
+
startSocialConnect,
|
|
69
|
+
} from '@happyvertical/smrt-social/connect';
|
|
70
|
+
|
|
71
|
+
// GET /connect/x (host has authorized the caller and set the tenant)
|
|
72
|
+
const { authorizeUrl } = await startSocialConnect({
|
|
73
|
+
db,
|
|
74
|
+
platform: 'x',
|
|
75
|
+
tenantId,
|
|
76
|
+
redirectUri: 'https://app.example.com/social/callback/x',
|
|
77
|
+
});
|
|
78
|
+
// redirect to authorizeUrl
|
|
79
|
+
|
|
80
|
+
// GET /callback/x
|
|
81
|
+
const { account } = await completeSocialConnect({
|
|
82
|
+
db,
|
|
83
|
+
platform: 'x',
|
|
84
|
+
tenantId,
|
|
85
|
+
redirectUri: 'https://app.example.com/social/callback/x',
|
|
86
|
+
query: { code, state, error },
|
|
87
|
+
});
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Client credentials come from the provider's env names (X: `X_CLIENT_ID`,
|
|
91
|
+
`X_CLIENT_SECRET`, falling back to `TWITTER_CLIENT_ID`/`TWITTER_CLIENT_SECRET`) or the `client` option. Tokens are stored through
|
|
92
|
+
`SocialAccount.setCredentials` (smrt-secrets, per tenant) as a JSON payload
|
|
93
|
+
including `expiresAt`; nothing is written to the plain token columns or logs.
|
|
94
|
+
The state is single-use, tenant-bound, and checked against the registered
|
|
95
|
+
redirect URI. New accounts start in the platform's default publish mode
|
|
96
|
+
(`dry_run` for X); a reconnect updates the same account and never widens its
|
|
97
|
+
mode. Failures throw `SocialConnectError` with a safe, user-showable message.
|
|
98
|
+
Pass `userId` to both calls: the state is bound to the initiating user, so a forwarded authorization link is rejected for anyone else. No role checks live in the package. Register the same `redirectUri` with the
|
|
99
|
+
platform. YouTube, Facebook Pages and Threads providers are not built yet.
|
|
100
|
+
|
|
58
101
|
## API
|
|
59
102
|
|
|
60
103
|
### Models
|
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
import { getSocialPlatformSetup } from "../server.js";
|
|
2
|
+
import { RuntimeError, SmrtCollection, SmrtObject, crossPackageRef, field, smrt } from "@happyvertical/smrt-core";
|
|
3
|
+
import { TenantScoped, getCurrentTenant, tenantId, withTenant } from "@happyvertical/smrt-tenancy";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import { SecretService } from "@happyvertical/smrt-secrets";
|
|
6
|
+
//#region src/oauth-state.ts
|
|
7
|
+
var __defProp$1 = Object.defineProperty;
|
|
8
|
+
var __getOwnPropDesc$1 = Object.getOwnPropertyDescriptor;
|
|
9
|
+
var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, {
|
|
10
|
+
enumerable: true,
|
|
11
|
+
configurable: true,
|
|
12
|
+
writable: true,
|
|
13
|
+
value
|
|
14
|
+
}) : obj[key] = value;
|
|
15
|
+
var __decorateClass$1 = (decorators, target, key, kind) => {
|
|
16
|
+
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$1(target, key) : target;
|
|
17
|
+
for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
18
|
+
if (kind && result) __defProp$1(target, key, result);
|
|
19
|
+
return result;
|
|
20
|
+
};
|
|
21
|
+
var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
22
|
+
var OAuthState = class extends SmrtObject {
|
|
23
|
+
tenantId = null;
|
|
24
|
+
/**
|
|
25
|
+
* User who started the connect. When set, the callback must be made by the
|
|
26
|
+
* same user, so an authorization link cannot be forwarded to someone else.
|
|
27
|
+
*/
|
|
28
|
+
initiatedByUserId = null;
|
|
29
|
+
/**
|
|
30
|
+
* Platform being connected
|
|
31
|
+
*/
|
|
32
|
+
platform = "youtube";
|
|
33
|
+
/**
|
|
34
|
+
* CSRF state token
|
|
35
|
+
* This is sent to the OAuth provider and verified on callback
|
|
36
|
+
*/
|
|
37
|
+
state = "";
|
|
38
|
+
/**
|
|
39
|
+
* PKCE code verifier
|
|
40
|
+
* Required for platforms using PKCE (YouTube, etc.)
|
|
41
|
+
*/
|
|
42
|
+
codeVerifier = null;
|
|
43
|
+
/**
|
|
44
|
+
* Redirect URI used in the OAuth request
|
|
45
|
+
* Must match on callback for verification
|
|
46
|
+
*/
|
|
47
|
+
redirectUri = "";
|
|
48
|
+
/**
|
|
49
|
+
* Requested OAuth scopes
|
|
50
|
+
*/
|
|
51
|
+
scopes = [];
|
|
52
|
+
/**
|
|
53
|
+
* When this state expires
|
|
54
|
+
* States should be short-lived (10 minutes typical)
|
|
55
|
+
*/
|
|
56
|
+
expiresAt = new Date(Date.now() + 600 * 1e3);
|
|
57
|
+
createdByUserId = null;
|
|
58
|
+
/**
|
|
59
|
+
* Application-defined path to return to after the callback, for example the
|
|
60
|
+
* settings page that started the flow. Opaque to the framework: the host
|
|
61
|
+
* that reads it must validate it as a same-origin path before redirecting.
|
|
62
|
+
*/
|
|
63
|
+
returnTo = null;
|
|
64
|
+
constructor(options = {}) {
|
|
65
|
+
super(options);
|
|
66
|
+
if (options.platform !== void 0) this.platform = options.platform;
|
|
67
|
+
if (options.state !== void 0) this.state = options.state;
|
|
68
|
+
if (options.codeVerifier !== void 0) this.codeVerifier = options.codeVerifier;
|
|
69
|
+
if (options.redirectUri !== void 0) this.redirectUri = options.redirectUri;
|
|
70
|
+
if (options.scopes !== void 0) this.scopes = options.scopes;
|
|
71
|
+
if (options.expiresAt !== void 0) this.expiresAt = options.expiresAt;
|
|
72
|
+
if (options.tenantId !== void 0) this.tenantId = options.tenantId;
|
|
73
|
+
if (options.createdByUserId !== void 0) this.createdByUserId = options.createdByUserId;
|
|
74
|
+
if (options.returnTo !== void 0) this.returnTo = options.returnTo;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Check if the state has expired
|
|
78
|
+
*/
|
|
79
|
+
get isExpired() {
|
|
80
|
+
return Date.now() >= this.expiresAt.getTime();
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Check if the state is still valid
|
|
84
|
+
*/
|
|
85
|
+
get isValid() {
|
|
86
|
+
return !this.isExpired && this.state.length > 0;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Verify a callback state matches this record
|
|
90
|
+
*/
|
|
91
|
+
verifyState(callbackState) {
|
|
92
|
+
return this.isValid && this.state === callbackState;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Generate a new random state token
|
|
96
|
+
*/
|
|
97
|
+
static generateState() {
|
|
98
|
+
return crypto.randomUUID();
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Generate a PKCE code verifier
|
|
102
|
+
* Returns a 43-128 character random string
|
|
103
|
+
*/
|
|
104
|
+
static generateCodeVerifier() {
|
|
105
|
+
const array = /* @__PURE__ */ new Uint8Array(32);
|
|
106
|
+
crypto.getRandomValues(array);
|
|
107
|
+
return Array.from(array, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Generate PKCE code challenge from verifier (S256 method)
|
|
111
|
+
* Note: This requires async crypto operations
|
|
112
|
+
*/
|
|
113
|
+
static async generateCodeChallenge(verifier) {
|
|
114
|
+
const data = new TextEncoder().encode(verifier);
|
|
115
|
+
const digest = await crypto.subtle.digest("SHA-256", data);
|
|
116
|
+
return btoa(String.fromCharCode(...new Uint8Array(digest))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
__publicField$1(OAuthState, "__smrtPackage__", "@happyvertical/smrt-social");
|
|
120
|
+
__decorateClass$1([tenantId({ nullable: true })], OAuthState.prototype, "tenantId", 2);
|
|
121
|
+
__decorateClass$1([crossPackageRef("@happyvertical/smrt-users:User")], OAuthState.prototype, "createdByUserId", 2);
|
|
122
|
+
OAuthState = __decorateClass$1([TenantScoped({ mode: "optional" }), smrt({
|
|
123
|
+
tableStrategy: "sti",
|
|
124
|
+
api: { include: [
|
|
125
|
+
"list",
|
|
126
|
+
"get",
|
|
127
|
+
"create",
|
|
128
|
+
"delete"
|
|
129
|
+
] },
|
|
130
|
+
mcp: false,
|
|
131
|
+
cli: { skipApiCheck: true }
|
|
132
|
+
})], OAuthState);
|
|
133
|
+
//#endregion
|
|
134
|
+
//#region src/collections/oauth-state-collection.ts
|
|
135
|
+
var OAuthStateCollection = class extends SmrtCollection {
|
|
136
|
+
static _itemClass = OAuthState;
|
|
137
|
+
async findByState(state) {
|
|
138
|
+
return this.get({ state });
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Consume a loaded state exactly once.
|
|
142
|
+
*
|
|
143
|
+
* Deletes the record with a revision-guarded delete, so when two callbacks
|
|
144
|
+
* race on the same state only one delete removes the row. Returns `true`
|
|
145
|
+
* for that caller and `false` for every caller whose row was already gone
|
|
146
|
+
* or changed; any other failure propagates. Call it before acting on the
|
|
147
|
+
* state (exchanging the code), and stop when it returns `false`.
|
|
148
|
+
*/
|
|
149
|
+
async consume(state) {
|
|
150
|
+
if (!state.id || !state.updated_at) return false;
|
|
151
|
+
try {
|
|
152
|
+
await state.delete({ expectedUpdatedAt: state.updated_at });
|
|
153
|
+
return true;
|
|
154
|
+
} catch (error) {
|
|
155
|
+
if (error instanceof RuntimeError && error.code === "RUNTIME_REVISION_CONFLICT") return false;
|
|
156
|
+
throw error;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
async findExpired(now = /* @__PURE__ */ new Date()) {
|
|
160
|
+
return this.list({
|
|
161
|
+
where: { "expiresAt <=": now },
|
|
162
|
+
orderBy: "expiresAt ASC"
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
async deleteExpired(now = /* @__PURE__ */ new Date()) {
|
|
166
|
+
const expired = await this.findExpired(now);
|
|
167
|
+
await Promise.all(expired.map((state) => state.delete()));
|
|
168
|
+
return expired.length;
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
//#endregion
|
|
172
|
+
//#region src/social-account.ts
|
|
173
|
+
var __defProp = Object.defineProperty;
|
|
174
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
175
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
|
|
176
|
+
enumerable: true,
|
|
177
|
+
configurable: true,
|
|
178
|
+
writable: true,
|
|
179
|
+
value
|
|
180
|
+
}) : obj[key] = value;
|
|
181
|
+
var __decorateClass = (decorators, target, key, kind) => {
|
|
182
|
+
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
|
|
183
|
+
for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
184
|
+
if (kind && result) __defProp(target, key, result);
|
|
185
|
+
return result;
|
|
186
|
+
};
|
|
187
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
188
|
+
var SocialAccount = class extends SmrtObject {
|
|
189
|
+
tenantId = null;
|
|
190
|
+
name = "";
|
|
191
|
+
platform = "youtube";
|
|
192
|
+
/**
|
|
193
|
+
* Platform-specific user ID
|
|
194
|
+
*/
|
|
195
|
+
platformUserId = null;
|
|
196
|
+
platformUsername = null;
|
|
197
|
+
platformUrl = null;
|
|
198
|
+
/**
|
|
199
|
+
* Deprecated raw OAuth access token.
|
|
200
|
+
* Prefer credentialSecretId/accessTokenSecretName.
|
|
201
|
+
*/
|
|
202
|
+
accessToken = null;
|
|
203
|
+
/**
|
|
204
|
+
* Deprecated raw OAuth refresh token.
|
|
205
|
+
* Prefer credentialSecretId/refreshTokenSecretName.
|
|
206
|
+
*/
|
|
207
|
+
refreshToken = null;
|
|
208
|
+
/**
|
|
209
|
+
* Secret name containing the complete platform credential payload.
|
|
210
|
+
*/
|
|
211
|
+
credentialSecretId = null;
|
|
212
|
+
/**
|
|
213
|
+
* Secret name containing only the access token.
|
|
214
|
+
*/
|
|
215
|
+
accessTokenSecretName = null;
|
|
216
|
+
/**
|
|
217
|
+
* Secret name containing only the refresh token.
|
|
218
|
+
*/
|
|
219
|
+
refreshTokenSecretName = null;
|
|
220
|
+
/**
|
|
221
|
+
* Token expiration time
|
|
222
|
+
*/
|
|
223
|
+
tokenExpiresAt = null;
|
|
224
|
+
isActive = true;
|
|
225
|
+
defaultHashtags = [];
|
|
226
|
+
/**
|
|
227
|
+
* Granted OAuth scopes or platform permissions.
|
|
228
|
+
*/
|
|
229
|
+
scopes = [];
|
|
230
|
+
/**
|
|
231
|
+
* Required permissions that still need app review or user grant.
|
|
232
|
+
*/
|
|
233
|
+
missingPermissions = [];
|
|
234
|
+
linkBehavior = "description";
|
|
235
|
+
/**
|
|
236
|
+
* Safety mode for publish operations.
|
|
237
|
+
*/
|
|
238
|
+
publishMode = "dry_run";
|
|
239
|
+
/**
|
|
240
|
+
* Separate latch required before public publishing is allowed.
|
|
241
|
+
*/
|
|
242
|
+
publicPublishingAllowed = false;
|
|
243
|
+
status = "connected";
|
|
244
|
+
/**
|
|
245
|
+
* Error message if status is 'error'
|
|
246
|
+
*/
|
|
247
|
+
errorMessage = null;
|
|
248
|
+
constructor(options = {}) {
|
|
249
|
+
super(options);
|
|
250
|
+
if (options.name !== void 0) this.name = options.name;
|
|
251
|
+
if (options.platform !== void 0) this.platform = options.platform;
|
|
252
|
+
if (options.platformUserId !== void 0) this.platformUserId = options.platformUserId;
|
|
253
|
+
if (options.platformUsername !== void 0) this.platformUsername = options.platformUsername;
|
|
254
|
+
if (options.platformUrl !== void 0) this.platformUrl = options.platformUrl;
|
|
255
|
+
if (options.accessToken !== void 0) this.accessToken = options.accessToken;
|
|
256
|
+
if (options.refreshToken !== void 0) this.refreshToken = options.refreshToken;
|
|
257
|
+
if (options.credentialSecretId !== void 0) this.credentialSecretId = options.credentialSecretId;
|
|
258
|
+
if (options.accessTokenSecretName !== void 0) this.accessTokenSecretName = options.accessTokenSecretName;
|
|
259
|
+
if (options.refreshTokenSecretName !== void 0) this.refreshTokenSecretName = options.refreshTokenSecretName;
|
|
260
|
+
if (options.tokenExpiresAt !== void 0) this.tokenExpiresAt = options.tokenExpiresAt;
|
|
261
|
+
if (options.isActive !== void 0) this.isActive = options.isActive;
|
|
262
|
+
if (options.defaultHashtags !== void 0) this.defaultHashtags = options.defaultHashtags;
|
|
263
|
+
if (options.scopes !== void 0) this.scopes = options.scopes;
|
|
264
|
+
if (options.missingPermissions !== void 0) this.missingPermissions = options.missingPermissions;
|
|
265
|
+
if (options.linkBehavior !== void 0) this.linkBehavior = options.linkBehavior;
|
|
266
|
+
if (options.publishMode !== void 0) this.publishMode = options.publishMode;
|
|
267
|
+
if (options.publicPublishingAllowed !== void 0) this.publicPublishingAllowed = options.publicPublishingAllowed;
|
|
268
|
+
if (options.status !== void 0) this.status = options.status;
|
|
269
|
+
if (options.errorMessage !== void 0) this.errorMessage = options.errorMessage;
|
|
270
|
+
if (options.tenantId !== void 0) this.tenantId = options.tenantId;
|
|
271
|
+
if (options.platform !== void 0) {
|
|
272
|
+
const setup = getSocialPlatformSetup(this.platform);
|
|
273
|
+
if (options.linkBehavior === void 0) this.linkBehavior = setup.defaultLinkBehavior;
|
|
274
|
+
if (options.publishMode === void 0) this.publishMode = setup.defaultPublishMode;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Social accounts need a slug identity that is scoped by tenant and platform.
|
|
279
|
+
* A newsroom may connect `@localnews` on X, YouTube, Threads, and Facebook;
|
|
280
|
+
* the generic name-derived slug would make those accounts overwrite each
|
|
281
|
+
* other through SMRT's slug/context upsert identity.
|
|
282
|
+
*/
|
|
283
|
+
async getSlug() {
|
|
284
|
+
if (!this.slug) {
|
|
285
|
+
const identity = this.platformUserId || this.platformUsername || this.name || this.id;
|
|
286
|
+
if (!identity) return this.slug;
|
|
287
|
+
const source = [
|
|
288
|
+
this.tenantId ? `tenant-${this.tenantId}` : "no-tenant",
|
|
289
|
+
this.platform,
|
|
290
|
+
identity
|
|
291
|
+
].filter(Boolean).join("-");
|
|
292
|
+
this.slug = source.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
|
|
293
|
+
}
|
|
294
|
+
return this.slug;
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* Check if the token is expired or will expire soon
|
|
298
|
+
*/
|
|
299
|
+
get isTokenExpired() {
|
|
300
|
+
if (!this.tokenExpiresAt) return false;
|
|
301
|
+
return Date.now() >= this.tokenExpiresAt.getTime() - 300 * 1e3;
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Check if the account needs attention (expired or error)
|
|
305
|
+
*/
|
|
306
|
+
get needsAttention() {
|
|
307
|
+
return this.status !== "connected" || this.isTokenExpired || this.missingPermissions.length > 0 || this.publishMode === "public" && !this.publicPublishingAllowed;
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* Check if the account is ready for publishing
|
|
311
|
+
*/
|
|
312
|
+
get isReady() {
|
|
313
|
+
return this.isActive && this.status === "connected" && this.hasCredentials && this.missingPermissions.length === 0 && !this.isTokenExpired && (this.publishMode !== "public" || this.publicPublishingAllowed);
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Effective publish mode after applying the public-publishing latch.
|
|
317
|
+
*/
|
|
318
|
+
get effectivePublishMode() {
|
|
319
|
+
if (this.publishMode === "public" && !this.publicPublishingAllowed) return "dry_run";
|
|
320
|
+
return this.publishMode;
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Check whether any usable credential reference exists.
|
|
324
|
+
*/
|
|
325
|
+
get hasCredentials() {
|
|
326
|
+
return Boolean(this.credentialSecretId || this.accessTokenSecretName || this.accessToken);
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* Store all platform credentials in smrt-secrets as a single JSON payload.
|
|
330
|
+
*/
|
|
331
|
+
async setCredentials(credentials, options = {}) {
|
|
332
|
+
if (!this.id) this.id = randomUUID();
|
|
333
|
+
const secretName = this.credentialSecretId ?? `social-account-${this.id}`;
|
|
334
|
+
const tenantId2 = this.requireCredentialTenantId("store social account credentials");
|
|
335
|
+
await (await SecretService.create({ db: this.db })).storeForTenant(tenantId2, secretName, JSON.stringify(credentials), {
|
|
336
|
+
description: options.description ?? `Credentials for ${this.name}`,
|
|
337
|
+
category: options.category ?? "social"
|
|
338
|
+
});
|
|
339
|
+
this.credentialSecretId = secretName;
|
|
340
|
+
await this.withCredentialTenantContext(async () => {
|
|
341
|
+
await this.save();
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* Retrieve platform credentials from smrt-secrets, falling back to deprecated fields.
|
|
346
|
+
*/
|
|
347
|
+
async getCredentials() {
|
|
348
|
+
if (!this.credentialSecretId) {
|
|
349
|
+
if (this.accessTokenSecretName || this.refreshTokenSecretName) {
|
|
350
|
+
const tenantId3 = this.requireCredentialTenantId("retrieve social account credentials");
|
|
351
|
+
const secretService2 = await SecretService.create({ db: this.db });
|
|
352
|
+
const credentials = {};
|
|
353
|
+
if (this.accessTokenSecretName) credentials.accessToken = (await secretService2.retrieveForTenant(tenantId3, this.accessTokenSecretName)).value;
|
|
354
|
+
if (this.refreshTokenSecretName) credentials.refreshToken = (await secretService2.retrieveForTenant(tenantId3, this.refreshTokenSecretName)).value;
|
|
355
|
+
return credentials;
|
|
356
|
+
}
|
|
357
|
+
if (!this.accessToken && !this.refreshToken) return null;
|
|
358
|
+
return {
|
|
359
|
+
accessToken: this.accessToken,
|
|
360
|
+
refreshToken: this.refreshToken
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
const credentialSecretId = this.credentialSecretId;
|
|
364
|
+
const tenantId2 = this.requireCredentialTenantId("retrieve social account credentials");
|
|
365
|
+
const secret = await (await SecretService.create({ db: this.db })).retrieveForTenant(tenantId2, credentialSecretId);
|
|
366
|
+
return JSON.parse(secret.value);
|
|
367
|
+
}
|
|
368
|
+
async withCredentialTenantContext(fn) {
|
|
369
|
+
const tenantId2 = this.getCredentialTenantId();
|
|
370
|
+
const currentTenantId = getCurrentTenant()?.tenantId;
|
|
371
|
+
if (!tenantId2 || currentTenantId === tenantId2) return fn();
|
|
372
|
+
return withTenant({ tenantId: tenantId2 }, fn);
|
|
373
|
+
}
|
|
374
|
+
getCredentialTenantId() {
|
|
375
|
+
if (this.tenantId) return this.tenantId;
|
|
376
|
+
return getCurrentTenant()?.tenantId ?? null;
|
|
377
|
+
}
|
|
378
|
+
requireCredentialTenantId(action) {
|
|
379
|
+
const tenantId2 = this.getCredentialTenantId();
|
|
380
|
+
if (!tenantId2) throw new Error(`Tenant context required to ${action}.`);
|
|
381
|
+
return tenantId2;
|
|
382
|
+
}
|
|
383
|
+
};
|
|
384
|
+
__publicField(SocialAccount, "__smrtPackage__", "@happyvertical/smrt-social");
|
|
385
|
+
__decorateClass([tenantId({ nullable: true })], SocialAccount.prototype, "tenantId", 2);
|
|
386
|
+
__decorateClass([field({ description: "A name you will recognise this account by." })], SocialAccount.prototype, "name", 2);
|
|
387
|
+
__decorateClass([field({ description: "Which platform it is on: YouTube, X, Threads or Bluesky." })], SocialAccount.prototype, "platform", 2);
|
|
388
|
+
__decorateClass([field({ description: "The username or handle you post under." })], SocialAccount.prototype, "platformUsername", 2);
|
|
389
|
+
__decorateClass([field({ description: "The web address of your profile on the platform." })], SocialAccount.prototype, "platformUrl", 2);
|
|
390
|
+
__decorateClass([field({ description: "Whether posts can still go out from this account." })], SocialAccount.prototype, "isActive", 2);
|
|
391
|
+
__decorateClass([field({ description: "Hashtags added to every post from this account." })], SocialAccount.prototype, "defaultHashtags", 2);
|
|
392
|
+
__decorateClass([field({ description: "Where a shared link goes: in the text, as a reply, or left out." })], SocialAccount.prototype, "linkBehavior", 2);
|
|
393
|
+
__decorateClass([field({ description: "Whether the account is connected, or needs signing in again." })], SocialAccount.prototype, "status", 2);
|
|
394
|
+
SocialAccount = __decorateClass([TenantScoped({ mode: "optional" }), smrt({
|
|
395
|
+
tableStrategy: "sti",
|
|
396
|
+
api: { include: [
|
|
397
|
+
"list",
|
|
398
|
+
"get",
|
|
399
|
+
"create",
|
|
400
|
+
"update",
|
|
401
|
+
"delete"
|
|
402
|
+
] },
|
|
403
|
+
mcp: { include: ["list", "get"] },
|
|
404
|
+
cli: { skipApiCheck: true }
|
|
405
|
+
})], SocialAccount);
|
|
406
|
+
//#endregion
|
|
407
|
+
//#region src/collections/social-account-collection.ts
|
|
408
|
+
var SocialAccountCollection = class extends SmrtCollection {
|
|
409
|
+
static _itemClass = SocialAccount;
|
|
410
|
+
async findActive(platform) {
|
|
411
|
+
return await this.list({
|
|
412
|
+
where: {
|
|
413
|
+
isActive: true,
|
|
414
|
+
...platform ? { platform } : {}
|
|
415
|
+
},
|
|
416
|
+
orderBy: "name ASC"
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
async findReady(platform) {
|
|
420
|
+
return (await this.findActive(platform)).filter((account) => account.isReady);
|
|
421
|
+
}
|
|
422
|
+
async findNeedsAttention() {
|
|
423
|
+
return (await this.list({
|
|
424
|
+
where: { isActive: true },
|
|
425
|
+
orderBy: "name ASC"
|
|
426
|
+
})).filter((account) => account.needsAttention);
|
|
427
|
+
}
|
|
428
|
+
};
|
|
429
|
+
//#endregion
|
|
430
|
+
export { OAuthState as i, SocialAccount as n, OAuthStateCollection as r, SocialAccountCollection as t };
|
|
431
|
+
|
|
432
|
+
//# sourceMappingURL=social-account-collection-B4PZKbUC.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"social-account-collection-B4PZKbUC.js","names":["tenantId","secretService","secret"],"sources":["../../src/oauth-state.ts","../../src/collections/oauth-state-collection.ts","../../src/social-account.ts","../../src/collections/social-account-collection.ts"],"sourcesContent":["/**\n * OAuth State Model\n *\n * Manages temporary OAuth state for connecting social accounts.\n * Used to verify callback requests and prevent CSRF attacks.\n */\n\nimport type { SmrtObjectOptions } from '@happyvertical/smrt-core';\nimport { crossPackageRef, SmrtObject, smrt } from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy';\nimport type { SocialPlatformType } from './social-account.js';\n\n/**\n * OAuth state creation options\n */\nexport interface OAuthStateOptions extends SmrtObjectOptions {\n /**\n * Platform being connected\n */\n platform?: SocialPlatformType;\n\n /**\n * CSRF state token\n */\n state?: string;\n\n /**\n * PKCE code verifier (for platforms that require it)\n */\n codeVerifier?: string | null;\n\n /**\n * Redirect URI used in the OAuth request\n */\n redirectUri?: string;\n\n /**\n * Requested OAuth scopes\n */\n scopes?: string[];\n\n /**\n * When this state expires\n */\n expiresAt?: Date;\n\n /**\n * Tenant ID for multi-tenant isolation\n */\n tenantId?: string | null;\n\n /**\n * User who started the OAuth flow\n */\n createdByUserId?: string | null;\n\n /**\n * Application-defined path to return to after the callback\n */\n returnTo?: string | null;\n}\n\n/**\n * Temporary OAuth state for social account connection\n *\n * OAuthState stores temporary data during the OAuth flow to:\n * - Verify callback requests match initiated requests (CSRF protection)\n * - Store PKCE code verifier for code exchange\n * - Track redirect URI and scopes for verification\n * - Bind the flow to the user who started it (`createdByUserId`) and record\n * where the host returns afterwards (`returnTo`), so one fixed callback\n * can serve every tenant\n *\n * These records should be cleaned up after successful connection\n * or after expiration.\n *\n * @example\n * ```typescript\n * import { OAuthState } from '@happyvertical/smrt-social';\n *\n * // Create state when initiating OAuth\n * const state = new OAuthState({\n * platform: 'youtube',\n * state: crypto.randomUUID(),\n * codeVerifier: generatePKCEVerifier(),\n * redirectUri: 'https://app.example.com/oauth/callback',\n * scopes: ['youtube.upload', 'youtube.readonly'],\n * expiresAt: new Date(Date.now() + 10 * 60 * 1000), // 10 minutes\n * });\n * await state.save();\n *\n * // After successful callback, delete the state\n * await state.delete();\n * ```\n */\n@TenantScoped({ mode: 'optional' })\n@smrt({\n tableStrategy: 'sti',\n api: {\n include: ['list', 'get', 'create', 'delete'],\n },\n mcp: false,\n cli: { skipApiCheck: true },\n})\nexport class OAuthState extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-social\";\n /**\n * Tenant ID for multi-tenant isolation\n */\n @tenantId({ nullable: true })\n tenantId: string | null = null;\n\n /**\n * User who started the connect. When set, the callback must be made by the\n * same user, so an authorization link cannot be forwarded to someone else.\n */\n initiatedByUserId: string | null = null;\n\n /**\n * Platform being connected\n */\n platform: SocialPlatformType = 'youtube';\n\n /**\n * CSRF state token\n * This is sent to the OAuth provider and verified on callback\n */\n state: string = '';\n\n /**\n * PKCE code verifier\n * Required for platforms using PKCE (YouTube, etc.)\n */\n codeVerifier: string | null = null;\n\n /**\n * Redirect URI used in the OAuth request\n * Must match on callback for verification\n */\n redirectUri: string = '';\n\n /**\n * Requested OAuth scopes\n */\n scopes: string[] = [];\n\n /**\n * When this state expires\n * States should be short-lived (10 minutes typical)\n */\n expiresAt: Date = new Date(Date.now() + 10 * 60 * 1000);\n\n /**\n * User who started the OAuth flow.\n *\n * A host with one fixed callback for every tenant compares this to the\n * signed-in user on callback and rejects a mismatch, so a forwarded or\n * leaked state cannot be completed by someone else. A `@crossPackageRef` to\n * `@happyvertical/smrt-users:User` (native uuid on PostgreSQL, no DDL FK).\n * Null for states created before the column existed.\n */\n @crossPackageRef('@happyvertical/smrt-users:User')\n createdByUserId: string | null = null;\n\n /**\n * Application-defined path to return to after the callback, for example the\n * settings page that started the flow. Opaque to the framework: the host\n * that reads it must validate it as a same-origin path before redirecting.\n */\n returnTo: string | null = null;\n\n constructor(options: OAuthStateOptions = {}) {\n super(options);\n\n if (options.platform !== undefined) this.platform = options.platform;\n if (options.state !== undefined) this.state = options.state;\n if (options.codeVerifier !== undefined)\n this.codeVerifier = options.codeVerifier;\n if (options.redirectUri !== undefined)\n this.redirectUri = options.redirectUri;\n if (options.scopes !== undefined) this.scopes = options.scopes;\n if (options.expiresAt !== undefined) this.expiresAt = options.expiresAt;\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.createdByUserId !== undefined)\n this.createdByUserId = options.createdByUserId;\n if (options.returnTo !== undefined) this.returnTo = options.returnTo;\n }\n\n /**\n * Check if the state has expired\n */\n get isExpired(): boolean {\n return Date.now() >= this.expiresAt.getTime();\n }\n\n /**\n * Check if the state is still valid\n */\n get isValid(): boolean {\n return !this.isExpired && this.state.length > 0;\n }\n\n /**\n * Verify a callback state matches this record\n */\n verifyState(callbackState: string): boolean {\n return this.isValid && this.state === callbackState;\n }\n\n /**\n * Generate a new random state token\n */\n static generateState(): string {\n return crypto.randomUUID();\n }\n\n /**\n * Generate a PKCE code verifier\n * Returns a 43-128 character random string\n */\n static generateCodeVerifier(): string {\n const array = new Uint8Array(32);\n crypto.getRandomValues(array);\n return Array.from(array, (byte) => byte.toString(16).padStart(2, '0')).join(\n '',\n );\n }\n\n /**\n * Generate PKCE code challenge from verifier (S256 method)\n * Note: This requires async crypto operations\n */\n static async generateCodeChallenge(verifier: string): Promise<string> {\n const encoder = new TextEncoder();\n const data = encoder.encode(verifier);\n const digest = await crypto.subtle.digest('SHA-256', data);\n const base64 = btoa(String.fromCharCode(...new Uint8Array(digest)));\n return base64.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=/g, '');\n }\n}\n","import { RuntimeError, SmrtCollection } from '@happyvertical/smrt-core';\nimport { OAuthState } from '../oauth-state.js';\n\nexport class OAuthStateCollection extends SmrtCollection<OAuthState> {\n static readonly _itemClass = OAuthState;\n\n async findByState(state: string): Promise<OAuthState | null> {\n return this.get({ state });\n }\n\n /**\n * Consume a loaded state exactly once.\n *\n * Deletes the record with a revision-guarded delete, so when two callbacks\n * race on the same state only one delete removes the row. Returns `true`\n * for that caller and `false` for every caller whose row was already gone\n * or changed; any other failure propagates. Call it before acting on the\n * state (exchanging the code), and stop when it returns `false`.\n */\n async consume(state: OAuthState): Promise<boolean> {\n if (!state.id || !state.updated_at) return false;\n try {\n await state.delete({ expectedUpdatedAt: state.updated_at });\n return true;\n } catch (error) {\n if (\n error instanceof RuntimeError &&\n error.code === 'RUNTIME_REVISION_CONFLICT'\n ) {\n return false;\n }\n throw error;\n }\n }\n\n async findExpired(now: Date = new Date()): Promise<OAuthState[]> {\n return this.list({\n where: { 'expiresAt <=': now },\n orderBy: 'expiresAt ASC',\n });\n }\n\n async deleteExpired(now: Date = new Date()): Promise<number> {\n const expired = await this.findExpired(now);\n await Promise.all(expired.map((state) => state.delete()));\n return expired.length;\n }\n}\n","/**\n * Social Account Model\n *\n * Manages connected social media platform accounts for publishing.\n * Stores OAuth credentials and account settings.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport type { SmrtObjectOptions } from '@happyvertical/smrt-core';\nimport { field, SmrtObject, smrt } from '@happyvertical/smrt-core';\nimport { SecretService } from '@happyvertical/smrt-secrets';\nimport {\n getCurrentTenant,\n TenantScoped,\n tenantId,\n withTenant,\n} from '@happyvertical/smrt-tenancy';\nimport { getSocialPlatformSetup } from './server.js';\n\n/**\n * Supported social platforms\n */\nexport type SocialPlatformType =\n | 'youtube'\n | 'threads'\n | 'x'\n | 'bluesky'\n | 'facebook';\n\n/**\n * Account connection status\n */\nexport type AccountStatus =\n | 'connected'\n | 'disconnected'\n | 'expired'\n | 'missing_permissions'\n | 'error';\n\n/**\n * Link behavior for posts with links\n */\nexport type LinkBehavior =\n | 'description'\n | 'inline'\n | 'attachment'\n | 'reply'\n | 'none';\n\n/**\n * Controls how far publish operations are allowed to go.\n */\nexport type PublishMode =\n | 'dry_run'\n | 'stage_remote'\n | 'private_or_scheduled'\n | 'public';\n\n/**\n * Social account creation options\n */\nexport interface SocialAccountOptions extends SmrtObjectOptions {\n /**\n * Human-readable name for the account\n */\n name?: string;\n\n /**\n * Social platform type\n */\n platform?: SocialPlatformType;\n\n /**\n * Platform-specific user ID\n */\n platformUserId?: string | null;\n\n /**\n * Platform username/handle\n */\n platformUsername?: string | null;\n\n /**\n * Profile URL on the platform\n */\n platformUrl?: string | null;\n\n /**\n * Deprecated raw OAuth access token\n */\n accessToken?: string | null;\n\n /**\n * Deprecated raw OAuth refresh token\n */\n refreshToken?: string | null;\n\n /**\n * Secret name containing the full platform credential payload\n */\n credentialSecretId?: string | null;\n\n /**\n * Secret name containing the OAuth access token\n */\n accessTokenSecretName?: string | null;\n\n /**\n * Secret name containing the OAuth refresh token\n */\n refreshTokenSecretName?: string | null;\n\n /**\n * Token expiration time\n */\n tokenExpiresAt?: Date | null;\n\n /**\n * Whether the account is active\n * @default true\n */\n isActive?: boolean;\n\n /**\n * Default hashtags to add to posts\n */\n defaultHashtags?: string[];\n\n /**\n * Granted OAuth scopes or platform permissions\n */\n scopes?: string[];\n\n /**\n * Required permissions that still need approval/granting\n */\n missingPermissions?: string[];\n\n /**\n * How to handle links in posts\n * @default 'description'\n */\n linkBehavior?: LinkBehavior;\n\n /**\n * Safety mode for publish operations.\n * @default 'dry_run'\n */\n publishMode?: PublishMode;\n\n /**\n * Separate latch required before public publishing can happen.\n * @default false\n */\n publicPublishingAllowed?: boolean;\n\n /**\n * Account connection status\n * @default 'connected'\n */\n status?: AccountStatus;\n\n /**\n * Error message if status is 'error'\n */\n errorMessage?: string | null;\n\n /**\n * Tenant ID for multi-tenant isolation\n */\n tenantId?: string | null;\n}\n\n/**\n * Connected social media account for publishing\n *\n * SocialAccount represents a connected social platform account\n * with OAuth credentials and publishing settings. Accounts can\n * be used to publish content to multiple platforms.\n *\n * @example\n * ```typescript\n * import { SocialAccount } from '@happyvertical/smrt-social';\n *\n * const account = new SocialAccount({\n * name: 'Bentley News YouTube',\n * platform: 'youtube',\n * platformUserId: 'UC...',\n * platformUsername: 'Bentley News',\n * accessToken: '...encrypted...',\n * refreshToken: '...encrypted...',\n * tokenExpiresAt: new Date('2026-02-25'),\n * defaultHashtags: ['news', 'local', 'bentley'],\n * linkBehavior: 'description',\n * });\n * await account.save();\n * ```\n */\n@TenantScoped({ mode: 'optional' })\n@smrt({\n tableStrategy: 'sti',\n api: {\n include: ['list', 'get', 'create', 'update', 'delete'],\n },\n mcp: {\n include: ['list', 'get'],\n },\n cli: { skipApiCheck: true },\n})\nexport class SocialAccount extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-social\";\n /**\n * Tenant ID for multi-tenant isolation\n */\n @tenantId({ nullable: true })\n tenantId: string | null = null;\n\n /**\n * Human-readable name for the account\n */\n @field({ description: 'A name you will recognise this account by.' })\n name: string = '';\n\n /**\n * Social platform type\n */\n @field({\n description: 'Which platform it is on: YouTube, X, Threads or Bluesky.',\n })\n platform: SocialPlatformType = 'youtube';\n\n /**\n * Platform-specific user ID\n */\n platformUserId: string | null = null;\n\n /**\n * Platform username/handle\n */\n @field({ description: 'The username or handle you post under.' })\n platformUsername: string | null = null;\n\n /**\n * Profile URL on the platform\n */\n @field({ description: 'The web address of your profile on the platform.' })\n platformUrl: string | null = null;\n\n /**\n * Deprecated raw OAuth access token.\n * Prefer credentialSecretId/accessTokenSecretName.\n */\n accessToken: string | null = null;\n\n /**\n * Deprecated raw OAuth refresh token.\n * Prefer credentialSecretId/refreshTokenSecretName.\n */\n refreshToken: string | null = null;\n\n /**\n * Secret name containing the complete platform credential payload.\n */\n credentialSecretId: string | null = null;\n\n /**\n * Secret name containing only the access token.\n */\n accessTokenSecretName: string | null = null;\n\n /**\n * Secret name containing only the refresh token.\n */\n refreshTokenSecretName: string | null = null;\n\n /**\n * Token expiration time\n */\n tokenExpiresAt: Date | null = null;\n\n /**\n * Whether the account is active\n */\n @field({\n description: 'Whether posts can still go out from this account.',\n })\n isActive: boolean = true;\n\n /**\n * Default hashtags to add to posts\n */\n @field({ description: 'Hashtags added to every post from this account.' })\n defaultHashtags: string[] = [];\n\n /**\n * Granted OAuth scopes or platform permissions.\n */\n scopes: string[] = [];\n\n /**\n * Required permissions that still need app review or user grant.\n */\n missingPermissions: string[] = [];\n\n /**\n * How to handle links in posts\n * - description: Include link in post body/description\n * - reply: Post link as a reply (better for X algorithm)\n * - none: Don't include link\n */\n @field({\n description:\n 'Where a shared link goes: in the text, as a reply, or left out.',\n })\n linkBehavior: LinkBehavior = 'description';\n\n /**\n * Safety mode for publish operations.\n */\n publishMode: PublishMode = 'dry_run';\n\n /**\n * Separate latch required before public publishing is allowed.\n */\n publicPublishingAllowed: boolean = false;\n\n /**\n * Account connection status\n */\n @field({\n description: 'Whether the account is connected, or needs signing in again.',\n })\n status: AccountStatus = 'connected';\n\n /**\n * Error message if status is 'error'\n */\n errorMessage: string | null = null;\n\n constructor(options: SocialAccountOptions = {}) {\n super(options);\n\n if (options.name !== undefined) this.name = options.name;\n if (options.platform !== undefined) this.platform = options.platform;\n if (options.platformUserId !== undefined)\n this.platformUserId = options.platformUserId;\n if (options.platformUsername !== undefined)\n this.platformUsername = options.platformUsername;\n if (options.platformUrl !== undefined)\n this.platformUrl = options.platformUrl;\n if (options.accessToken !== undefined)\n this.accessToken = options.accessToken;\n if (options.refreshToken !== undefined)\n this.refreshToken = options.refreshToken;\n if (options.credentialSecretId !== undefined)\n this.credentialSecretId = options.credentialSecretId;\n if (options.accessTokenSecretName !== undefined)\n this.accessTokenSecretName = options.accessTokenSecretName;\n if (options.refreshTokenSecretName !== undefined)\n this.refreshTokenSecretName = options.refreshTokenSecretName;\n if (options.tokenExpiresAt !== undefined)\n this.tokenExpiresAt = options.tokenExpiresAt;\n if (options.isActive !== undefined) this.isActive = options.isActive;\n if (options.defaultHashtags !== undefined)\n this.defaultHashtags = options.defaultHashtags;\n if (options.scopes !== undefined) this.scopes = options.scopes;\n if (options.missingPermissions !== undefined)\n this.missingPermissions = options.missingPermissions;\n if (options.linkBehavior !== undefined)\n this.linkBehavior = options.linkBehavior;\n if (options.publishMode !== undefined)\n this.publishMode = options.publishMode;\n if (options.publicPublishingAllowed !== undefined)\n this.publicPublishingAllowed = options.publicPublishingAllowed;\n if (options.status !== undefined) this.status = options.status;\n if (options.errorMessage !== undefined)\n this.errorMessage = options.errorMessage;\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n\n if (options.platform !== undefined) {\n const setup = getSocialPlatformSetup(this.platform);\n if (options.linkBehavior === undefined) {\n this.linkBehavior = setup.defaultLinkBehavior;\n }\n if (options.publishMode === undefined) {\n this.publishMode = setup.defaultPublishMode;\n }\n }\n }\n\n /**\n * Social accounts need a slug identity that is scoped by tenant and platform.\n * A newsroom may connect `@localnews` on X, YouTube, Threads, and Facebook;\n * the generic name-derived slug would make those accounts overwrite each\n * other through SMRT's slug/context upsert identity.\n */\n async getSlug(): Promise<string | null | undefined> {\n if (!this.slug) {\n const identity =\n this.platformUserId || this.platformUsername || this.name || this.id;\n if (!identity) {\n return this.slug;\n }\n\n const source = [\n this.tenantId ? `tenant-${this.tenantId}` : 'no-tenant',\n this.platform,\n identity,\n ]\n .filter(Boolean)\n .join('-');\n\n this.slug = source\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/(^-|-$)/g, '');\n }\n\n return this.slug;\n }\n\n /**\n * Check if the token is expired or will expire soon\n */\n get isTokenExpired(): boolean {\n if (!this.tokenExpiresAt) return false;\n // Expire 5 minutes early to allow for refresh\n const expiryBuffer = 5 * 60 * 1000;\n return Date.now() >= this.tokenExpiresAt.getTime() - expiryBuffer;\n }\n\n /**\n * Check if the account needs attention (expired or error)\n */\n get needsAttention(): boolean {\n return (\n this.status !== 'connected' ||\n this.isTokenExpired ||\n this.missingPermissions.length > 0 ||\n (this.publishMode === 'public' && !this.publicPublishingAllowed)\n );\n }\n\n /**\n * Check if the account is ready for publishing\n */\n get isReady(): boolean {\n return (\n this.isActive &&\n this.status === 'connected' &&\n this.hasCredentials &&\n this.missingPermissions.length === 0 &&\n !this.isTokenExpired &&\n (this.publishMode !== 'public' || this.publicPublishingAllowed)\n );\n }\n\n /**\n * Effective publish mode after applying the public-publishing latch.\n */\n get effectivePublishMode(): PublishMode {\n if (this.publishMode === 'public' && !this.publicPublishingAllowed) {\n return 'dry_run';\n }\n return this.publishMode;\n }\n\n /**\n * Check whether any usable credential reference exists.\n */\n get hasCredentials(): boolean {\n return Boolean(\n this.credentialSecretId || this.accessTokenSecretName || this.accessToken,\n );\n }\n\n /**\n * Store all platform credentials in smrt-secrets as a single JSON payload.\n */\n async setCredentials(\n credentials: Record<string, unknown>,\n options: {\n description?: string;\n category?: string;\n } = {},\n ): Promise<void> {\n if (!this.id) {\n this.id = randomUUID();\n }\n\n const secretName = this.credentialSecretId ?? `social-account-${this.id}`;\n const tenantId = this.requireCredentialTenantId(\n 'store social account credentials',\n );\n const secretService = await SecretService.create({ db: this.db });\n\n await secretService.storeForTenant(\n tenantId,\n secretName,\n JSON.stringify(credentials),\n {\n description: options.description ?? `Credentials for ${this.name}`,\n category: options.category ?? 'social',\n },\n );\n\n this.credentialSecretId = secretName;\n\n await this.withCredentialTenantContext(async () => {\n await this.save();\n });\n }\n\n /**\n * Retrieve platform credentials from smrt-secrets, falling back to deprecated fields.\n */\n async getCredentials(): Promise<Record<string, unknown> | null> {\n if (!this.credentialSecretId) {\n if (this.accessTokenSecretName || this.refreshTokenSecretName) {\n const tenantId = this.requireCredentialTenantId(\n 'retrieve social account credentials',\n );\n const secretService = await SecretService.create({ db: this.db });\n const credentials: Record<string, unknown> = {};\n\n if (this.accessTokenSecretName) {\n const secret = await secretService.retrieveForTenant(\n tenantId,\n this.accessTokenSecretName,\n );\n credentials.accessToken = secret.value;\n }\n\n if (this.refreshTokenSecretName) {\n const secret = await secretService.retrieveForTenant(\n tenantId,\n this.refreshTokenSecretName,\n );\n credentials.refreshToken = secret.value;\n }\n\n return credentials;\n }\n\n if (!this.accessToken && !this.refreshToken) return null;\n return {\n accessToken: this.accessToken,\n refreshToken: this.refreshToken,\n };\n }\n\n const credentialSecretId = this.credentialSecretId;\n const tenantId = this.requireCredentialTenantId(\n 'retrieve social account credentials',\n );\n const secretService = await SecretService.create({ db: this.db });\n const secret = await secretService.retrieveForTenant(\n tenantId,\n credentialSecretId,\n );\n return JSON.parse(secret.value);\n }\n\n private async withCredentialTenantContext<T>(\n fn: () => Promise<T>,\n ): Promise<T> {\n const tenantId = this.getCredentialTenantId();\n const currentTenantId = getCurrentTenant()?.tenantId;\n\n if (!tenantId || currentTenantId === tenantId) {\n return fn();\n }\n\n return withTenant({ tenantId }, fn);\n }\n\n private getCredentialTenantId(): string | null {\n if (this.tenantId) {\n return this.tenantId;\n }\n\n return getCurrentTenant()?.tenantId ?? null;\n }\n\n private requireCredentialTenantId(action: string): string {\n const tenantId = this.getCredentialTenantId();\n if (!tenantId) {\n throw new Error(`Tenant context required to ${action}.`);\n }\n return tenantId;\n }\n}\n","import { SmrtCollection } from '@happyvertical/smrt-core';\nimport { SocialAccount, type SocialPlatformType } from '../social-account.js';\n\nexport class SocialAccountCollection extends SmrtCollection<SocialAccount> {\n static readonly _itemClass = SocialAccount;\n\n async findActive(platform?: SocialPlatformType): Promise<SocialAccount[]> {\n const accounts = await this.list({\n where: {\n isActive: true,\n ...(platform ? { platform } : {}),\n },\n orderBy: 'name ASC',\n });\n\n return accounts;\n }\n\n async findReady(platform?: SocialPlatformType): Promise<SocialAccount[]> {\n const accounts = await this.findActive(platform);\n return accounts.filter((account) => account.isReady);\n }\n\n async findNeedsAttention(): Promise<SocialAccount[]> {\n const accounts = await this.list({\n where: { isActive: true },\n orderBy: 'name ASC',\n });\n return accounts.filter((account) => account.needsAttention);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAwGO,IAAM,aAAN,cAAyB,WAAW;CAKzC,WAA0B;;;;;CAM1B,oBAAmC;;;;CAKnC,WAA+B;;;;;CAM/B,QAAgB;;;;;CAMhB,eAA8B;;;;;CAM9B,cAAsB;;;;CAKtB,SAAmB,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,EAAA,CAC/B,QAAQ,YAAY,QAAQ,OAAO;CACrD;CAEA,MAAM,qBAA+C;EAKnD,QAAO,MAJgB,KAAK,KAAK;GAC/B,OAAO,EAAE,UAAU,KAAK;GACxB,SAAS;EACX,CAAC,EAAA,CACe,QAAQ,YAAY,QAAQ,cAAc;CAC5D;AACF"}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Provider-agnostic social account connect flow.
|
|
3
|
+
*
|
|
4
|
+
* `startSocialConnect` builds the authorize URL and persists a single-use,
|
|
5
|
+
* tenant-bound `OAuthState`. `completeSocialConnect` verifies the callback,
|
|
6
|
+
* exchanges the code, reads the profile, stores the tokens in smrt-secrets
|
|
7
|
+
* (via `SocialAccount.setCredentials`) and creates or updates the account in
|
|
8
|
+
* `dry_run`. The host mounts two routes, supplies the tenant, and redirects.
|
|
9
|
+
* No role checks live here; authorize before calling.
|
|
10
|
+
*/
|
|
11
|
+
import type { DatabaseInterface } from '@happyvertical/sql';
|
|
12
|
+
import type { SocialAccount } from '../social-account.js';
|
|
13
|
+
import { type SocialClientCredentials } from './types.js';
|
|
14
|
+
export interface SocialConnectContext {
|
|
15
|
+
db: DatabaseInterface;
|
|
16
|
+
/** Defaults to the current tenant context. */
|
|
17
|
+
tenantId?: string;
|
|
18
|
+
/**
|
|
19
|
+
* The signed-in user making the request. When start supplies it, complete
|
|
20
|
+
* must supply the same user or the callback is rejected before the state is
|
|
21
|
+
* consumed. Hosts should always pass it.
|
|
22
|
+
*/
|
|
23
|
+
userId?: string;
|
|
24
|
+
/** Platform id from the route, e.g. `x`. */
|
|
25
|
+
platform: string;
|
|
26
|
+
/** The callback URL registered with the platform. */
|
|
27
|
+
redirectUri: string;
|
|
28
|
+
/** Explicit credentials; otherwise read from the provider's env names. */
|
|
29
|
+
client?: SocialClientCredentials;
|
|
30
|
+
env?: Record<string, string | undefined>;
|
|
31
|
+
fetch?: typeof fetch;
|
|
32
|
+
}
|
|
33
|
+
export interface StartSocialConnectOptions extends SocialConnectContext {
|
|
34
|
+
scopes?: string[];
|
|
35
|
+
/** State lifetime in ms. Default 10 minutes. */
|
|
36
|
+
ttlMs?: number;
|
|
37
|
+
}
|
|
38
|
+
export interface CompleteSocialConnectOptions extends SocialConnectContext {
|
|
39
|
+
/** The callback's query parameters. */
|
|
40
|
+
query: {
|
|
41
|
+
code?: string | null;
|
|
42
|
+
state?: string | null;
|
|
43
|
+
error?: string | null;
|
|
44
|
+
};
|
|
45
|
+
/** Display name for a newly created account. */
|
|
46
|
+
accountName?: string;
|
|
47
|
+
}
|
|
48
|
+
export interface CompletedSocialConnect {
|
|
49
|
+
account: SocialAccount;
|
|
50
|
+
created: boolean;
|
|
51
|
+
}
|
|
52
|
+
/** Whether the provider's client credentials are available (for UI gating). */
|
|
53
|
+
export declare function isSocialConnectConfigured(platform: string, options?: Pick<SocialConnectContext, 'client' | 'env'>): boolean;
|
|
54
|
+
/** Begin a connect: returns the URL to redirect the user to. */
|
|
55
|
+
export declare function startSocialConnect(options: StartSocialConnectOptions): Promise<{
|
|
56
|
+
authorizeUrl: string;
|
|
57
|
+
}>;
|
|
58
|
+
/** Finish a connect from the platform's callback. */
|
|
59
|
+
export declare function completeSocialConnect(options: CompleteSocialConnectOptions): Promise<CompletedSocialConnect>;
|
|
60
|
+
/** Hrefs for `SocialAccountSettings`: `<basePath>/<platform>` per provider. */
|
|
61
|
+
export declare function socialConnectHrefs(basePath: string, platforms?: string[]): Record<string, string>;
|
|
62
|
+
//# sourceMappingURL=flow.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"flow.d.ts","sourceRoot":"","sources":["../../src/connect/flow.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAGH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAK5D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAE1D,OAAO,EACL,KAAK,uBAAuB,EAG7B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AA;CAAE,CAAC,CAqCnC;AAED,qDAAqD;AACrD,wBAAsB,qBAAqB,CACzC,OAAO,EAAE,4BAA4B,GACpC,OAAO,CAAC,sBAAsB,CAAC,CA0GjC;AAED,+EAA+E;AAC/E,wBAAgB,kBAAkB,CAChC,QAAQ,EAAE,MAAM,EAChB,SAAS,CAAC,EAAE,MAAM,EAAE,GACnB,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAQxB"}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { type CompletedSocialConnect, type CompleteSocialConnectOptions, completeSocialConnect, isSocialConnectConfigured, type SocialConnectContext, type StartSocialConnectOptions, socialConnectHrefs, startSocialConnect, } from './flow.js';
|
|
2
|
+
export { getSocialConnectProvider, listSocialConnectProviders, registerSocialConnectProvider, } from './registry.js';
|
|
3
|
+
export { type SocialAuthorizeRequest, type SocialClientCredentials, type SocialCodeExchange, SocialConnectError, type SocialConnectErrorCode, type SocialConnectProvider, type SocialProfile, type SocialTokenSet, } from './types.js';
|
|
4
|
+
export { X_AUTHORIZE_URL, X_DEFAULT_SCOPES, X_ME_URL, X_TOKEN_URL, xConnectProvider, } from './x.js';
|
|
5
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/connect/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,sBAAsB,EAC3B,KAAK,4BAA4B,EACjC,qBAAqB,EACrB,yBAAyB,EACzB,KAAK,oBAAoB,EACzB,KAAK,yBAAyB,EAC9B,kBAAkB,EAClB,kBAAkB,GACnB,MAAM,WAAW,CAAC;AACnB,OAAO,EACL,wBAAwB,EACxB,0BAA0B,EAC1B,6BAA6B,GAC9B,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,KAAK,sBAAsB,EAC3B,KAAK,uBAAuB,EAC5B,KAAK,kBAAkB,EACvB,kBAAkB,EAClB,KAAK,sBAAsB,EAC3B,KAAK,qBAAqB,EAC1B,KAAK,aAAa,EAClB,KAAK,cAAc,GACpB,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,eAAe,EACf,gBAAgB,EAChB,QAAQ,EACR,WAAW,EACX,gBAAgB,GACjB,MAAM,QAAQ,CAAC"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { SocialConnectProvider } from './types.js';
|
|
2
|
+
/** Register (or replace) a provider. Hosts can add platforms without a release. */
|
|
3
|
+
export declare function registerSocialConnectProvider(provider: SocialConnectProvider): void;
|
|
4
|
+
export declare function getSocialConnectProvider(platform: string): SocialConnectProvider | undefined;
|
|
5
|
+
export declare function listSocialConnectProviders(): SocialConnectProvider[];
|
|
6
|
+
//# sourceMappingURL=registry.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../../src/connect/registry.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AAOxD,mFAAmF;AACnF,wBAAgB,6BAA6B,CAC3C,QAAQ,EAAE,qBAAqB,GAC9B,IAAI,CAEN;AAED,wBAAgB,wBAAwB,CACtC,QAAQ,EAAE,MAAM,GACf,qBAAqB,GAAG,SAAS,CAEnC;AAED,wBAAgB,0BAA0B,IAAI,qBAAqB,EAAE,CAEpE"}
|