franchising 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +61 -0
- package/README.md +96 -2
- package/dist/accounts-B4bnTXUd.js +242 -0
- package/dist/accounts-B4bnTXUd.js.map +1 -0
- package/dist/accounts-TyMPSHM0.cjs +313 -0
- package/dist/accounts-TyMPSHM0.cjs.map +1 -0
- package/dist/adapters-DM59AJfR.d.cts +216 -0
- package/dist/adapters-DM59AJfR.d.ts +216 -0
- package/dist/cli/template-assets/api/src/errors/codes.ts +17 -0
- package/dist/cli/template-assets/api/src/errors/index.ts +16 -0
- package/dist/cli/template-assets/api/src/filters/exception.ts +53 -0
- package/dist/cli/template-assets/api/src/main.ts +189 -0
- package/dist/cli/template-assets/api/src/modules/health/controller.ts +23 -0
- package/dist/cli/template-assets/api/src/modules/health/dto/response.dto.ts +23 -0
- package/dist/cli/template-assets/api/src/modules/health/module.ts +12 -0
- package/dist/cli/template-assets/api/src/modules/health/service.ts +54 -0
- package/dist/cli/template-assets/api/src/modules/messaging/module.ts +7 -0
- package/dist/cli/template-assets/api/src/modules/messaging/service.ts +74 -0
- package/dist/cli/template-assets/api/src/shared/exceptions.ts +40 -0
- package/dist/cli/template-assets/api/src/shared/response.ts +31 -0
- package/dist/cli/template-assets/api/src/telemetry.ts +59 -0
- package/dist/cli/template-assets/api/src/types.ts +8 -0
- package/dist/cli/template-assets/cloudflare/cache.service.ts +23 -0
- package/dist/cli/template-assets/cloudflare/queue.service.ts +22 -0
- package/dist/cli/template-assets/cloudflare/worker.ts +33 -0
- package/dist/cli/template-assets/packages/jobs/src/index.ts +49 -0
- package/dist/cli/template-assets/packages/queue-runtime/src/index.ts +54 -0
- package/dist/cli/template-assets/root/dot-dockerignore +11 -0
- package/dist/cli/template-assets/root/dot-editorconfig +13 -0
- package/dist/cli/template-assets/root/dot-oxfmtrc.json +9 -0
- package/dist/cli/template-assets/root/dot-oxlintrc.json +47 -0
- package/dist/cli/template-assets/root/lefthook.yml +18 -0
- package/dist/cli/template-assets/web/postcss.config.mjs +9 -0
- package/dist/cli/template-assets/web/src/app/(app)/dashboard/page.tsx +5 -0
- package/dist/cli/template-assets/web/src/app/(app)/layout.tsx +25 -0
- package/dist/cli/template-assets/web/src/app/(auth)/login/page.tsx +75 -0
- package/dist/cli/template-assets/web/src/app/globals.css +48 -0
- package/dist/cli/template-assets/web/src/app/layout.tsx +30 -0
- package/dist/cli/template-assets/web/src/app/page.tsx +20 -0
- package/dist/cli/template-assets/web/src/components/overview/overview-panel.tsx +27 -0
- package/dist/cli/template-assets/web/src/components/shell/app-shell.tsx +37 -0
- package/dist/cli/template-assets/web/src/components/shell/providers.tsx +22 -0
- package/dist/cli/template-assets/web/src/lib/api-client.ts +57 -0
- package/dist/cli/template-assets/web/src/lib/auth-client.ts +15 -0
- package/dist/cli/template-assets/web/src/lib/server-auth.ts +38 -0
- package/dist/cli/template-assets/web/src/types/api.ts +18 -0
- package/dist/cli/template-assets/worker/src/app.module.ts +5 -0
- package/dist/cli/template-assets/worker/src/env.ts +8 -0
- package/dist/cli/template-assets/worker/src/main.ts +25 -0
- package/dist/cli/template-assets/worker/src/modules/queue/config.ts +16 -0
- package/dist/cli/template-assets/worker/src/modules/queue/module.ts +11 -0
- package/dist/cli/template-assets/worker/src/modules/queue/processor.ts +105 -0
- package/dist/cli/template-assets/worker/src/modules/queue/repository.ts +16 -0
- package/dist/cli/template-assets/worker/src/modules/queue/retry.ts +17 -0
- package/dist/cli/template-assets/worker/test/retry.test.ts.tpl +12 -0
- package/dist/cli/template-assets/worker-messaging/jobs-messaging.ts +12 -0
- package/dist/cli/template-assets/worker-messaging/messaging-api-service.ts +39 -0
- package/dist/cli/template-assets/worker-messaging/src/env.ts +14 -0
- package/dist/cli/template-assets/worker-messaging/src/modules/messaging/service.ts +59 -0
- package/dist/cli/template-assets/worker-messaging/src/modules/queue/module.ts +8 -0
- package/dist/cli/template-assets/worker-messaging/src/modules/queue/processor.ts +113 -0
- package/dist/cli.js +1218 -0
- package/dist/cn-BVOnrSza.js +1 -0
- package/dist/constants-C4iP0--i.js +38 -0
- package/dist/constants-C4iP0--i.js.map +1 -0
- package/dist/constants-rCR-LNSN.cjs +91 -0
- package/dist/constants-rCR-LNSN.cjs.map +1 -0
- package/dist/core-BidJDmSN.cjs +759 -0
- package/dist/core-BidJDmSN.cjs.map +1 -0
- package/dist/core-C-EFrEd6.js +710 -0
- package/dist/core-C-EFrEd6.js.map +1 -0
- package/dist/decorate-BR5FVX5x.js +14 -0
- package/dist/decorate-R-oqksAh.cjs +25 -0
- package/dist/decorateParam-BFJPEGKJ.cjs +13 -0
- package/dist/decorateParam-CKE7_J1s.js +8 -0
- package/dist/define-adapter-Cc0QrfKt.cjs +16 -0
- package/dist/define-adapter-Cc0QrfKt.cjs.map +1 -0
- package/dist/define-adapter-DRcXno3j.js +11 -0
- package/dist/define-adapter-DRcXno3j.js.map +1 -0
- package/dist/dispatcher-BsD7cO2w.cjs +84 -0
- package/dist/dispatcher-BsD7cO2w.cjs.map +1 -0
- package/dist/dispatcher-DA_l1Vkv.js +73 -0
- package/dist/dispatcher-DA_l1Vkv.js.map +1 -0
- package/dist/errors-DxHoXrLd.d.cts +46 -0
- package/dist/errors-DxHoXrLd.d.ts +46 -0
- package/dist/http/index.cjs +440 -0
- package/dist/http/index.cjs.map +1 -0
- package/dist/http/index.d.cts +257 -0
- package/dist/http/index.d.ts +257 -0
- package/dist/http/index.js +400 -0
- package/dist/http/index.js.map +1 -0
- package/dist/http/swagger.cjs +122 -0
- package/dist/http/swagger.cjs.map +1 -0
- package/dist/http/swagger.d.cts +59 -0
- package/dist/http/swagger.d.ts +59 -0
- package/dist/http/swagger.js +117 -0
- package/dist/http/swagger.js.map +1 -0
- package/dist/index--EJQTnHy.d.cts +174 -0
- package/dist/index-B3aVdDMV.d.cts +51 -0
- package/dist/index-BDYdEWl2.d.cts +833 -0
- package/dist/index-BDYdEWl2.d.ts +833 -0
- package/dist/index-Bdl0AiNM.d.ts +1262 -0
- package/dist/index-By8b4ksT.d.ts +25 -0
- package/dist/index-ByS2IC02.d.ts +51 -0
- package/dist/index-DDSaLjXV.d.cts +25 -0
- package/dist/index-FTrYdHfq.d.cts +1262 -0
- package/dist/index-u3ArUXO0.d.ts +174 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.cts +4 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +1 -0
- package/dist/label-BqmJoVE-.cjs +1 -0
- package/dist/label-XeChe1Bu.js +1 -0
- package/dist/messaging/index.cjs +1 -0
- package/dist/messaging/index.d.cts +1775 -0
- package/dist/messaging/index.d.ts +1775 -0
- package/dist/messaging/index.js +1 -0
- package/dist/misc-BpM_lMTx.js +1 -0
- package/dist/misc-DkqJOm1V.cjs +1 -0
- package/dist/operational-CnxdBwVG.d.cts +13 -0
- package/dist/operational-CnxdBwVG.d.ts +13 -0
- package/dist/redaction-DhuHTlHA.js +124 -0
- package/dist/redaction-DhuHTlHA.js.map +1 -0
- package/dist/redaction-uRIQbTwZ.cjs +171 -0
- package/dist/redaction-uRIQbTwZ.cjs.map +1 -0
- package/dist/rolldown-runtime-auK_WOaK.cjs +1 -0
- package/dist/rolldown-runtime-xuxB8TGW.cjs +32 -0
- package/dist/sdk-B2Lp3JCz.cjs +45 -0
- package/dist/sdk-B2Lp3JCz.cjs.map +1 -0
- package/dist/sdk-IGOHpAeG.js +22 -0
- package/dist/sdk-IGOHpAeG.js.map +1 -0
- package/dist/skills-C1uwr9Pp.js +4 -0
- package/dist/skills-DuE-XnBp.js +1 -0
- package/dist/sso/client.cjs +37 -0
- package/dist/sso/client.cjs.map +1 -0
- package/dist/sso/client.d.cts +89 -0
- package/dist/sso/client.d.ts +89 -0
- package/dist/sso/client.js +36 -0
- package/dist/sso/client.js.map +1 -0
- package/dist/sso/index.cjs +833 -0
- package/dist/sso/index.cjs.map +1 -0
- package/dist/sso/index.d.cts +2 -0
- package/dist/sso/index.d.ts +2 -0
- package/dist/sso/index.js +821 -0
- package/dist/sso/index.js.map +1 -0
- package/dist/sso/nestjs.cjs +169 -0
- package/dist/sso/nestjs.cjs.map +1 -0
- package/dist/sso/nestjs.d.cts +92 -0
- package/dist/sso/nestjs.d.ts +92 -0
- package/dist/sso/nestjs.js +151 -0
- package/dist/sso/nestjs.js.map +1 -0
- package/dist/sso/resource.cjs +124 -0
- package/dist/sso/resource.cjs.map +1 -0
- package/dist/sso/resource.d.cts +3 -0
- package/dist/sso/resource.d.ts +3 -0
- package/dist/sso/resource.js +114 -0
- package/dist/sso/resource.js.map +1 -0
- package/dist/status-CRvlFPIs.js +13 -0
- package/dist/status-CRvlFPIs.js.map +1 -0
- package/dist/status-DtK6OHtj.cjs +24 -0
- package/dist/status-DtK6OHtj.cjs.map +1 -0
- package/dist/telemetry/adapters.cjs +6 -0
- package/dist/telemetry/adapters.d.cts +3 -0
- package/dist/telemetry/adapters.d.ts +3 -0
- package/dist/telemetry/adapters.js +4 -0
- package/dist/telemetry/betterstack.cjs +74 -0
- package/dist/telemetry/betterstack.cjs.map +1 -0
- package/dist/telemetry/betterstack.d.cts +12 -0
- package/dist/telemetry/betterstack.d.ts +12 -0
- package/dist/telemetry/betterstack.js +71 -0
- package/dist/telemetry/betterstack.js.map +1 -0
- package/dist/telemetry/core.cjs +11 -0
- package/dist/telemetry/core.d.cts +4 -0
- package/dist/telemetry/core.d.ts +4 -0
- package/dist/telemetry/core.js +5 -0
- package/dist/telemetry/index.cjs +524 -0
- package/dist/telemetry/index.cjs.map +1 -0
- package/dist/telemetry/index.d.cts +68 -0
- package/dist/telemetry/index.d.ts +68 -0
- package/dist/telemetry/index.js +499 -0
- package/dist/telemetry/index.js.map +1 -0
- package/dist/telemetry/posthog.cjs +72 -0
- package/dist/telemetry/posthog.cjs.map +1 -0
- package/dist/telemetry/posthog.d.cts +10 -0
- package/dist/telemetry/posthog.d.ts +10 -0
- package/dist/telemetry/posthog.js +71 -0
- package/dist/telemetry/posthog.js.map +1 -0
- package/dist/telemetry/register.cjs +88 -0
- package/dist/telemetry/register.cjs.map +1 -0
- package/dist/telemetry/register.d.cts +14 -0
- package/dist/telemetry/register.d.ts +14 -0
- package/dist/telemetry/register.js +85 -0
- package/dist/telemetry/register.js.map +1 -0
- package/dist/telemetry/testing.cjs +54 -0
- package/dist/telemetry/testing.cjs.map +1 -0
- package/dist/telemetry/testing.d.cts +15 -0
- package/dist/telemetry/testing.d.ts +15 -0
- package/dist/telemetry/testing.js +52 -0
- package/dist/telemetry/testing.js.map +1 -0
- package/dist/telemetry.mock-BSsx7L6S.cjs +45 -0
- package/dist/telemetry.mock-BSsx7L6S.cjs.map +1 -0
- package/dist/telemetry.mock-BZRpy63c.js +40 -0
- package/dist/telemetry.mock-BZRpy63c.js.map +1 -0
- package/dist/telemetry.mock-C1wXuf-M.d.cts +4 -0
- package/dist/telemetry.mock-CdaxofJ7.d.ts +4 -0
- package/dist/ui/chart.cjs +6 -0
- package/dist/ui/chart.d.cts +34 -0
- package/dist/ui/chart.d.ts +34 -0
- package/dist/ui/chart.js +6 -0
- package/dist/ui/form.cjs +1 -0
- package/dist/ui/form.d.cts +23 -0
- package/dist/ui/form.d.ts +23 -0
- package/dist/ui/form.js +1 -0
- package/dist/ui/hooks.cjs +1 -0
- package/dist/ui/hooks.d.cts +66 -0
- package/dist/ui/hooks.d.ts +66 -0
- package/dist/ui/hooks.js +1 -0
- package/dist/ui/index.cjs +1 -0
- package/dist/ui/index.d.cts +3 -0
- package/dist/ui/index.d.ts +3 -0
- package/dist/ui/index.js +1 -0
- package/dist/ui/styles.css +2 -0
- package/dist/ui/utils.cjs +1 -0
- package/dist/ui/utils.d.cts +199 -0
- package/dist/ui/utils.d.ts +199 -0
- package/dist/ui/utils.js +1 -0
- package/dist/use-mobile-BbeIMRgE.cjs +1 -0
- package/dist/use-mobile-Cdd4Lp7p.js +1 -0
- package/dist/use-mobile-ecpyXWz3.d.cts +10 -0
- package/dist/use-mobile-ecpyXWz3.d.ts +10 -0
- package/dist/verifier-BIBtPCVi.cjs +119 -0
- package/dist/verifier-BIBtPCVi.cjs.map +1 -0
- package/dist/verifier-DNdy5Ynw.js +90 -0
- package/dist/verifier-DNdy5Ynw.js.map +1 -0
- package/dist/version-B0ADow60.js +1 -0
- package/dist/version-CMkha8JJ.cjs +1 -0
- package/package.json +539 -5
|
@@ -0,0 +1,821 @@
|
|
|
1
|
+
import { c as readImpersonation, d as verifyLogoutToken, f as RockfellerErrorCode, i as isRockfellerError, l as readSid, n as grants, o as impersonationExpired, r as RockfellerError, s as readAuthTime, t as createAccountsApi, u as verifyIdToken } from "../accounts-B4bnTXUd.js";
|
|
2
|
+
import { a as SIGN_IN_SCOPES, c as accountsUrls, i as PROVIDER_ID, l as normalizeIssuer, o as TEAM_PROVIDER_ID, r as PROFILE_TABS, s as TEAM_SCOPE, t as DEFAULT_ISSUER } from "../constants-C4iP0--i.js";
|
|
3
|
+
import { APIError, createAuthEndpoint, createAuthMiddleware, sessionMiddleware } from "better-auth/api";
|
|
4
|
+
import * as z$1 from "zod";
|
|
5
|
+
import { createAuthorizationURL, decryptOAuthToken, refreshAccessToken, setTokenUtil, validateAuthorizationCode } from "better-auth/oauth2";
|
|
6
|
+
|
|
7
|
+
// src/modules/sso/shared/constants.ts
|
|
8
|
+
const HOOK_NAMES = {
|
|
9
|
+
"user.updated": "onUserUpdated",
|
|
10
|
+
"user.disabled": "onUserDisabled",
|
|
11
|
+
"user.enabled": "onUserEnabled",
|
|
12
|
+
"user.deactivated": "onUserDeactivated",
|
|
13
|
+
"user.deleted": "onUserDeleted",
|
|
14
|
+
"membership.granted": "onMembershipGranted",
|
|
15
|
+
"membership.revoked": "onMembershipRevoked",
|
|
16
|
+
"app.access_revoked": "onAppAccessRevoked"
|
|
17
|
+
};
|
|
18
|
+
const ENDS_ALL_SESSIONS = /* @__PURE__ */ new Set([
|
|
19
|
+
"user.disabled",
|
|
20
|
+
"user.deactivated",
|
|
21
|
+
"user.deleted",
|
|
22
|
+
"app.access_revoked"
|
|
23
|
+
]);
|
|
24
|
+
const SID_FIELD = "rockfellerSid";
|
|
25
|
+
const LOCAL_SIGN_IN_PATHS = /* @__PURE__ */ new Set([
|
|
26
|
+
"/sign-in/email",
|
|
27
|
+
"/sign-up/email",
|
|
28
|
+
"/sign-in/username",
|
|
29
|
+
"/sign-in/magic-link",
|
|
30
|
+
"/sign-in/email-otp",
|
|
31
|
+
"/sign-in/phone-number",
|
|
32
|
+
"/request-password-reset"
|
|
33
|
+
]);
|
|
34
|
+
const STATUS_NAMES = {
|
|
35
|
+
400: "BAD_REQUEST",
|
|
36
|
+
401: "UNAUTHORIZED",
|
|
37
|
+
403: "FORBIDDEN",
|
|
38
|
+
404: "NOT_FOUND",
|
|
39
|
+
409: "CONFLICT",
|
|
40
|
+
429: "TOO_MANY_REQUESTS"
|
|
41
|
+
};
|
|
42
|
+
const REFRESH_MARGIN_MS = 3e4;
|
|
43
|
+
|
|
44
|
+
// src/modules/sso/shared/errors.ts
|
|
45
|
+
function toAPIError(error) {
|
|
46
|
+
if (!(error instanceof RockfellerError)) return error;
|
|
47
|
+
const status = STATUS_NAMES[error.status] ?? "BAD_GATEWAY";
|
|
48
|
+
return new APIError(status, {
|
|
49
|
+
code: error.code,
|
|
50
|
+
message: error.message
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
function fail(code, status, message) {
|
|
54
|
+
throw new RockfellerError(code, status, message);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// src/modules/sso/shared/account.ts
|
|
58
|
+
async function linkedAccount(ctx, providerId = PROVIDER_ID) {
|
|
59
|
+
const userId = ctx.context.session?.user.id;
|
|
60
|
+
if (!userId) throw new APIError("UNAUTHORIZED");
|
|
61
|
+
return (await ctx.context.internalAdapter.findAccounts(userId)).find((account) => account.providerId === providerId) ?? null;
|
|
62
|
+
}
|
|
63
|
+
function impersonationSid(account) {
|
|
64
|
+
return readImpersonation(account.idToken) ? readSid(account.idToken) : null;
|
|
65
|
+
}
|
|
66
|
+
async function requireAccount(ctx) {
|
|
67
|
+
const account = await linkedAccount(ctx) ?? fail(RockfellerErrorCode.NOT_CONNECTED, 403, "A pessoa não entrou pela Conta Rockfeller.");
|
|
68
|
+
if (impersonationExpired(account.idToken)) fail(RockfellerErrorCode.IMPERSONATION_EXPIRED, 401, "A impersonação acabou. Entre de novo.");
|
|
69
|
+
return account;
|
|
70
|
+
}
|
|
71
|
+
async function localUserId(context, sub) {
|
|
72
|
+
return (await context.adapter.findOne({
|
|
73
|
+
model: "account",
|
|
74
|
+
where: [{
|
|
75
|
+
field: "providerId",
|
|
76
|
+
value: "rockfeller"
|
|
77
|
+
}, {
|
|
78
|
+
field: "accountId",
|
|
79
|
+
value: sub
|
|
80
|
+
}]
|
|
81
|
+
}))?.userId ?? null;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// src/modules/sso/shared/handler.ts
|
|
85
|
+
function handle(run) {
|
|
86
|
+
return async (ctx) => {
|
|
87
|
+
try {
|
|
88
|
+
return await run(ctx);
|
|
89
|
+
} catch (error) {
|
|
90
|
+
throw toAPIError(error);
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// src/modules/sso/plugin/endpoints/get-api-token.ts
|
|
96
|
+
function createGetApiTokenEndpoint(runtime) {
|
|
97
|
+
const { accessTokenFor, options } = runtime;
|
|
98
|
+
return createAuthEndpoint("/rockfeller/api-token", {
|
|
99
|
+
method: "GET",
|
|
100
|
+
use: [sessionMiddleware],
|
|
101
|
+
metadata: { SERVER_ONLY: true }
|
|
102
|
+
}, handle(async (ctx) => {
|
|
103
|
+
if (!options.api) fail(RockfellerErrorCode.API_NOT_CONFIGURED, 400, "Configure `api` no plugin rockfeller().");
|
|
104
|
+
const account = await requireAccount(ctx);
|
|
105
|
+
return ctx.json({ accessToken: await accessTokenFor(ctx.context, account) });
|
|
106
|
+
}));
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// src/modules/sso/plugin/endpoints/get-profile-url.ts
|
|
110
|
+
function createGetProfileUrlEndpoint(runtime) {
|
|
111
|
+
const { options, urls } = runtime;
|
|
112
|
+
return createAuthEndpoint("/rockfeller/profile/url", {
|
|
113
|
+
method: "GET",
|
|
114
|
+
query: z$1.object({
|
|
115
|
+
returnTo: z$1.string().url(),
|
|
116
|
+
tab: z$1.enum([
|
|
117
|
+
"profile",
|
|
118
|
+
"security",
|
|
119
|
+
"sessions",
|
|
120
|
+
"apps"
|
|
121
|
+
]).optional()
|
|
122
|
+
})
|
|
123
|
+
}, async (ctx) => {
|
|
124
|
+
const url = new URL(`${urls.account}${PROFILE_TABS[ctx.query.tab ?? "profile"]}`);
|
|
125
|
+
url.searchParams.set("client_id", options.clientId);
|
|
126
|
+
url.searchParams.set("return_to", ctx.query.returnTo);
|
|
127
|
+
return ctx.json({ url: url.toString() });
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// src/modules/sso/plugin/endpoints/get-rockfeller-account.ts
|
|
132
|
+
function createGetRockfellerAccountEndpoint() {
|
|
133
|
+
return createAuthEndpoint("/rockfeller/account", {
|
|
134
|
+
method: "GET",
|
|
135
|
+
use: [sessionMiddleware]
|
|
136
|
+
}, handle(async (ctx) => {
|
|
137
|
+
const account = await requireAccount(ctx);
|
|
138
|
+
const authTime = readAuthTime(account.idToken);
|
|
139
|
+
return ctx.json({
|
|
140
|
+
sub: account.accountId,
|
|
141
|
+
accountId: account.id,
|
|
142
|
+
authTime: authTime?.toISOString() ?? null,
|
|
143
|
+
impersonatedBy: readImpersonation(account.idToken)
|
|
144
|
+
});
|
|
145
|
+
}));
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// src/modules/sso/shared/schools.ts
|
|
149
|
+
const schoolFields = {
|
|
150
|
+
school: z$1.string().min(1).optional(),
|
|
151
|
+
joyUnit: z$1.string().min(1).optional()
|
|
152
|
+
};
|
|
153
|
+
function schoolRef(input) {
|
|
154
|
+
if (input.school && !input.joyUnit) return input.school;
|
|
155
|
+
if (input.joyUnit && !input.school) return { joyUnit: input.joyUnit };
|
|
156
|
+
return fail("VALIDATION_FAILED", 400, "Informe `school` ou `joyUnit`, um dos dois.");
|
|
157
|
+
}
|
|
158
|
+
function cacheScope(school) {
|
|
159
|
+
return typeof school === "string" ? `org:${school}` : `joy:${school.joyUnit}`;
|
|
160
|
+
}
|
|
161
|
+
const permissionBody = z$1.object({
|
|
162
|
+
...schoolFields,
|
|
163
|
+
permission: z$1.string().min(1)
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
// src/modules/sso/plugin/endpoints/get-school-permissions.ts
|
|
167
|
+
function createGetSchoolPermissionsEndpoint(runtime) {
|
|
168
|
+
const { permissionsFor } = runtime;
|
|
169
|
+
return createAuthEndpoint("/rockfeller/schools/permissions", {
|
|
170
|
+
method: "GET",
|
|
171
|
+
use: [sessionMiddleware],
|
|
172
|
+
query: z$1.object(schoolFields)
|
|
173
|
+
}, handle(async (ctx) => {
|
|
174
|
+
const account = await requireAccount(ctx);
|
|
175
|
+
return ctx.json(await permissionsFor(account.accountId, schoolRef(ctx.query), impersonationSid(account)));
|
|
176
|
+
}));
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// src/modules/sso/plugin/endpoints/has-permission.ts
|
|
180
|
+
function createHasPermissionEndpoint(runtime) {
|
|
181
|
+
const { permissionsFor } = runtime;
|
|
182
|
+
return createAuthEndpoint("/rockfeller/permissions/check", {
|
|
183
|
+
method: "POST",
|
|
184
|
+
use: [sessionMiddleware],
|
|
185
|
+
body: permissionBody,
|
|
186
|
+
metadata: { SERVER_ONLY: true }
|
|
187
|
+
}, handle(async (ctx) => {
|
|
188
|
+
const account = await linkedAccount(ctx);
|
|
189
|
+
if (!account || impersonationExpired(account.idToken)) return false;
|
|
190
|
+
const access = await permissionsFor(account.accountId, schoolRef(ctx.body), impersonationSid(account));
|
|
191
|
+
return grants(access, ctx.body.permission);
|
|
192
|
+
}));
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// src/modules/sso/plugin/endpoints/invite-team-member.ts
|
|
196
|
+
function createInviteTeamMemberEndpoint(runtime) {
|
|
197
|
+
const { accounts, teamToken } = runtime;
|
|
198
|
+
return createAuthEndpoint("/rockfeller/team/invite", {
|
|
199
|
+
method: "POST",
|
|
200
|
+
use: [sessionMiddleware],
|
|
201
|
+
body: z$1.object({
|
|
202
|
+
school: z$1.string().min(1),
|
|
203
|
+
email: z$1.string().email(),
|
|
204
|
+
name: z$1.string().min(1),
|
|
205
|
+
roles: z$1.array(z$1.enum([
|
|
206
|
+
"coordenador",
|
|
207
|
+
"secretaria",
|
|
208
|
+
"financeiro",
|
|
209
|
+
"gestor_unidade",
|
|
210
|
+
"franqueado",
|
|
211
|
+
"afiliado"
|
|
212
|
+
])).min(1)
|
|
213
|
+
})
|
|
214
|
+
}, handle(async (ctx) => {
|
|
215
|
+
const { school, ...input } = ctx.body;
|
|
216
|
+
const invitation = await accounts.team.invite(await teamToken(ctx), school, input);
|
|
217
|
+
return ctx.json(invitation);
|
|
218
|
+
}));
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// src/modules/sso/plugin/endpoints/list-schools.ts
|
|
222
|
+
function createListSchoolsEndpoint(runtime) {
|
|
223
|
+
const { accounts } = runtime;
|
|
224
|
+
return createAuthEndpoint("/rockfeller/schools", {
|
|
225
|
+
method: "GET",
|
|
226
|
+
use: [sessionMiddleware]
|
|
227
|
+
}, handle(async (ctx) => {
|
|
228
|
+
const account = await requireAccount(ctx);
|
|
229
|
+
const sid = impersonationSid(account);
|
|
230
|
+
const key = sid ? `schools:imp:${sid}` : "schools";
|
|
231
|
+
const cached = await runtime.cache.get(account.accountId, key);
|
|
232
|
+
const list = cached ?? await accounts.schools(account.accountId, sid ?? void 0);
|
|
233
|
+
if (!cached) await runtime.cache.set(account.accountId, key, list);
|
|
234
|
+
return ctx.json(list);
|
|
235
|
+
}));
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// src/modules/sso/plugin/endpoints/list-team-members.ts
|
|
239
|
+
function createListTeamMembersEndpoint(runtime) {
|
|
240
|
+
const { accounts, teamToken } = runtime;
|
|
241
|
+
return createAuthEndpoint("/rockfeller/team/members", {
|
|
242
|
+
method: "GET",
|
|
243
|
+
use: [sessionMiddleware],
|
|
244
|
+
query: z$1.object({
|
|
245
|
+
school: z$1.string().min(1),
|
|
246
|
+
q: z$1.string().optional(),
|
|
247
|
+
role: z$1.string().optional(),
|
|
248
|
+
origin: z$1.enum([
|
|
249
|
+
"joy",
|
|
250
|
+
"invite",
|
|
251
|
+
"franchisor"
|
|
252
|
+
]).optional(),
|
|
253
|
+
cursor: z$1.string().optional(),
|
|
254
|
+
limit: z$1.coerce.number().int().min(1).max(15).optional()
|
|
255
|
+
})
|
|
256
|
+
}, handle(async (ctx) => {
|
|
257
|
+
const { school, ...query } = ctx.query;
|
|
258
|
+
const page = await accounts.team.members(await teamToken(ctx), school, query);
|
|
259
|
+
return ctx.json(page);
|
|
260
|
+
}));
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// src/modules/sso/plugin/endpoints/refresh-profile.ts
|
|
264
|
+
function createRefreshProfileEndpoint(runtime) {
|
|
265
|
+
const { accessTokenFor, urls } = runtime;
|
|
266
|
+
return createAuthEndpoint("/rockfeller/profile/refresh", {
|
|
267
|
+
method: "POST",
|
|
268
|
+
use: [sessionMiddleware]
|
|
269
|
+
}, handle(async (ctx) => {
|
|
270
|
+
const account = await requireAccount(ctx);
|
|
271
|
+
const accessToken = await accessTokenFor(ctx.context, account);
|
|
272
|
+
const response = await fetch(urls.userInfo, { headers: { authorization: `Bearer ${accessToken}` } });
|
|
273
|
+
if (!response.ok) fail("UPSTREAM_FAILED", 502, "O Accounts não devolveu o perfil.");
|
|
274
|
+
const profile = await response.json();
|
|
275
|
+
const update = {
|
|
276
|
+
name: profile.name ?? ctx.context.session.user.name,
|
|
277
|
+
image: profile.picture ?? null
|
|
278
|
+
};
|
|
279
|
+
await ctx.context.internalAdapter.updateUser(ctx.context.session.user.id, update);
|
|
280
|
+
return ctx.json(update);
|
|
281
|
+
}));
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// src/modules/sso/plugin/endpoints/require-permission.ts
|
|
285
|
+
function createRequirePermissionEndpoint(runtime) {
|
|
286
|
+
const { permissionsFor } = runtime;
|
|
287
|
+
return createAuthEndpoint("/rockfeller/permissions/require", {
|
|
288
|
+
method: "POST",
|
|
289
|
+
use: [sessionMiddleware],
|
|
290
|
+
body: permissionBody,
|
|
291
|
+
metadata: { SERVER_ONLY: true }
|
|
292
|
+
}, handle(async (ctx) => {
|
|
293
|
+
const account = await requireAccount(ctx);
|
|
294
|
+
const access = await permissionsFor(account.accountId, schoolRef(ctx.body), impersonationSid(account));
|
|
295
|
+
if (!grants(access, ctx.body.permission)) fail(RockfellerErrorCode.FORBIDDEN, 403, `Sem a permissão ${ctx.body.permission} nesta escola.`);
|
|
296
|
+
return ctx.json(access);
|
|
297
|
+
}));
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// src/modules/sso/plugin/endpoints/revoke-team-roles.ts
|
|
301
|
+
function createRevokeTeamRolesEndpoint(runtime) {
|
|
302
|
+
const { accounts, teamToken } = runtime;
|
|
303
|
+
return createAuthEndpoint("/rockfeller/team/revoke", {
|
|
304
|
+
method: "POST",
|
|
305
|
+
use: [sessionMiddleware],
|
|
306
|
+
body: z$1.object({
|
|
307
|
+
school: z$1.string().min(1),
|
|
308
|
+
userId: z$1.string().min(1),
|
|
309
|
+
roles: z$1.array(z$1.string().min(1)).min(1)
|
|
310
|
+
})
|
|
311
|
+
}, handle(async (ctx) => ctx.json(await accounts.team.revoke(await teamToken(ctx), ctx.body.school, ctx.body.userId, ctx.body.roles))));
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
// src/modules/sso/plugin/endpoints/rockfeller-backchannel-logout.ts
|
|
315
|
+
function createRockfellerBackchannelLogoutEndpoint(runtime) {
|
|
316
|
+
const { issuer, options, sessionEnded } = runtime;
|
|
317
|
+
return createAuthEndpoint("/rockfeller/backchannel-logout", {
|
|
318
|
+
method: "POST",
|
|
319
|
+
body: z$1.object({ logout_token: z$1.string().min(1) }),
|
|
320
|
+
metadata: {
|
|
321
|
+
isAction: false,
|
|
322
|
+
allowedMediaTypes: ["application/x-www-form-urlencoded"]
|
|
323
|
+
}
|
|
324
|
+
}, async (ctx) => {
|
|
325
|
+
ctx.setHeader("cache-control", "no-store");
|
|
326
|
+
let sub;
|
|
327
|
+
let sid;
|
|
328
|
+
try {
|
|
329
|
+
({sub, sid} = await verifyLogoutToken(ctx.body.logout_token, {
|
|
330
|
+
issuer,
|
|
331
|
+
clientId: options.clientId
|
|
332
|
+
}));
|
|
333
|
+
} catch {
|
|
334
|
+
throw new APIError("BAD_REQUEST", { code: "INVALID_LOGOUT_TOKEN" });
|
|
335
|
+
}
|
|
336
|
+
const userId = await localUserId(ctx.context, sub);
|
|
337
|
+
await sessionEnded(ctx.context, {
|
|
338
|
+
sub,
|
|
339
|
+
userId,
|
|
340
|
+
sid,
|
|
341
|
+
source: "backchannel",
|
|
342
|
+
event: null
|
|
343
|
+
});
|
|
344
|
+
await options.onBackchannelLogout?.({
|
|
345
|
+
sub,
|
|
346
|
+
userId
|
|
347
|
+
});
|
|
348
|
+
return ctx.json({ ok: true });
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// src/modules/sso/shared/encoding.ts
|
|
353
|
+
const encoder = new TextEncoder();
|
|
354
|
+
function base64ToBytes(value) {
|
|
355
|
+
return Uint8Array.from(atob(value), (char) => char.charCodeAt(0));
|
|
356
|
+
}
|
|
357
|
+
function bytesToBase64(bytes) {
|
|
358
|
+
let binary = "";
|
|
359
|
+
for (const byte of new Uint8Array(bytes)) binary += String.fromCharCode(byte);
|
|
360
|
+
return btoa(binary);
|
|
361
|
+
}
|
|
362
|
+
function safeEqual(a, b) {
|
|
363
|
+
if (a.length !== b.length) return false;
|
|
364
|
+
let diff = 0;
|
|
365
|
+
for (let index = 0; index < a.length; index++) diff |= a.charCodeAt(index) ^ b.charCodeAt(index);
|
|
366
|
+
return diff === 0;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// src/modules/sso/core/webhooks.ts
|
|
370
|
+
const WEBHOOK_EVENT_TYPES = [
|
|
371
|
+
"user.updated",
|
|
372
|
+
"user.disabled",
|
|
373
|
+
"user.enabled",
|
|
374
|
+
"user.deactivated",
|
|
375
|
+
"user.deleted",
|
|
376
|
+
"membership.granted",
|
|
377
|
+
"membership.revoked",
|
|
378
|
+
"app.access_revoked",
|
|
379
|
+
"session.ended"
|
|
380
|
+
];
|
|
381
|
+
const WEBHOOK_TEST_EVENT = "webhook.test";
|
|
382
|
+
const TIMESTAMP_TOLERANCE_SECONDS = 300;
|
|
383
|
+
var WebhookVerificationError = class extends Error {};
|
|
384
|
+
async function verifyWebhook(secret, body, headers, now = Date.now()) {
|
|
385
|
+
const id = headers.get("webhook-id");
|
|
386
|
+
const timestamp = headers.get("webhook-timestamp");
|
|
387
|
+
const signatures = headers.get("webhook-signature");
|
|
388
|
+
if (!(id && timestamp && signatures)) throw new WebhookVerificationError("Cabeçalhos do webhook ausentes.");
|
|
389
|
+
const sentAt = Number(timestamp);
|
|
390
|
+
if (!Number.isFinite(sentAt) || Math.abs(now / 1e3 - sentAt) > TIMESTAMP_TOLERANCE_SECONDS) throw new WebhookVerificationError("webhook-timestamp fora da janela.");
|
|
391
|
+
const key = await crypto.subtle.importKey("raw", base64ToBytes(secret.replace(/^whsec_/, "")), {
|
|
392
|
+
name: "HMAC",
|
|
393
|
+
hash: "SHA-256"
|
|
394
|
+
}, false, ["sign"]);
|
|
395
|
+
const expected = bytesToBase64(await crypto.subtle.sign("HMAC", key, encoder.encode(`${id}.${timestamp}.${body}`)));
|
|
396
|
+
if (!signatures.split(" ").some((entry) => {
|
|
397
|
+
const [version, signature] = entry.split(",");
|
|
398
|
+
return version === "v1" && signature !== void 0 ? safeEqual(signature, expected) : false;
|
|
399
|
+
})) throw new WebhookVerificationError("Assinatura do webhook inválida.");
|
|
400
|
+
const event = JSON.parse(body);
|
|
401
|
+
if (event.id !== id) throw new WebhookVerificationError("webhook-id não confere com o corpo.");
|
|
402
|
+
return event;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
// src/modules/sso/plugin/endpoints/rockfeller-webhooks.ts
|
|
406
|
+
function createRockfellerWebhooksEndpoint(runtime) {
|
|
407
|
+
const { handleWebhook, options, webhookPath } = runtime;
|
|
408
|
+
return createAuthEndpoint(webhookPath, {
|
|
409
|
+
method: "POST",
|
|
410
|
+
disableBody: true,
|
|
411
|
+
metadata: { isAction: false }
|
|
412
|
+
}, async (ctx) => {
|
|
413
|
+
ctx.setHeader("cache-control", "no-store");
|
|
414
|
+
const config = options.webhooks;
|
|
415
|
+
if (!config) throw new APIError("NOT_FOUND", {
|
|
416
|
+
code: RockfellerErrorCode.WEBHOOKS_NOT_CONFIGURED,
|
|
417
|
+
message: "Configure `webhooks` no plugin rockfeller()."
|
|
418
|
+
});
|
|
419
|
+
if (!ctx.request) throw new APIError("BAD_REQUEST");
|
|
420
|
+
let event;
|
|
421
|
+
try {
|
|
422
|
+
event = await verifyWebhook(config.secret, await ctx.request.text(), ctx.request.headers);
|
|
423
|
+
} catch (error) {
|
|
424
|
+
if (error instanceof WebhookVerificationError || error instanceof SyntaxError) throw new APIError("UNAUTHORIZED", {
|
|
425
|
+
code: RockfellerErrorCode.INVALID_WEBHOOK_SIGNATURE,
|
|
426
|
+
message: error.message
|
|
427
|
+
});
|
|
428
|
+
throw error;
|
|
429
|
+
}
|
|
430
|
+
if (event.type !== "webhook.test" && WEBHOOK_EVENT_TYPES.includes(event.type)) await handleWebhook(ctx.context, event, config.hooks);
|
|
431
|
+
return ctx.json({ ok: true });
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
// src/modules/sso/core/cache.ts
|
|
436
|
+
const MEMORY_LIMIT = 1e4;
|
|
437
|
+
function memoryStorage() {
|
|
438
|
+
const entries = /* @__PURE__ */ new Map();
|
|
439
|
+
return {
|
|
440
|
+
get(key) {
|
|
441
|
+
const entry = entries.get(key);
|
|
442
|
+
if (!entry) return null;
|
|
443
|
+
if (entry.expiresAt <= Date.now()) {
|
|
444
|
+
entries.delete(key);
|
|
445
|
+
return null;
|
|
446
|
+
}
|
|
447
|
+
return entry.value;
|
|
448
|
+
},
|
|
449
|
+
set(key, value, ttl = 60) {
|
|
450
|
+
if (entries.size >= MEMORY_LIMIT) {
|
|
451
|
+
const oldest = entries.keys().next().value;
|
|
452
|
+
if (oldest !== void 0) entries.delete(oldest);
|
|
453
|
+
}
|
|
454
|
+
entries.set(key, {
|
|
455
|
+
value,
|
|
456
|
+
expiresAt: Date.now() + ttl * 1e3
|
|
457
|
+
});
|
|
458
|
+
},
|
|
459
|
+
delete(key) {
|
|
460
|
+
entries.delete(key);
|
|
461
|
+
}
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
const GENERATION_TTL_SECONDS = 86400;
|
|
465
|
+
function createPermissionCache(options) {
|
|
466
|
+
const storage = options.storage ?? memoryStorage();
|
|
467
|
+
const enabled = options.ttlSeconds > 0;
|
|
468
|
+
async function generation(sub) {
|
|
469
|
+
const value = await storage.get(`rockfeller:gen:${sub}`);
|
|
470
|
+
return value === null || value === void 0 ? "0" : String(value);
|
|
471
|
+
}
|
|
472
|
+
async function key(sub, scope) {
|
|
473
|
+
return `rockfeller:perm:${sub}:${await generation(sub)}:${scope}`;
|
|
474
|
+
}
|
|
475
|
+
return {
|
|
476
|
+
async get(sub, scope) {
|
|
477
|
+
if (!enabled) return null;
|
|
478
|
+
const value = await storage.get(await key(sub, scope));
|
|
479
|
+
if (value === null || value === void 0) return null;
|
|
480
|
+
if (typeof value !== "string") return value;
|
|
481
|
+
try {
|
|
482
|
+
return JSON.parse(value);
|
|
483
|
+
} catch {
|
|
484
|
+
return null;
|
|
485
|
+
}
|
|
486
|
+
},
|
|
487
|
+
async set(sub, scope, value) {
|
|
488
|
+
if (enabled) await storage.set(await key(sub, scope), JSON.stringify(value), options.ttlSeconds);
|
|
489
|
+
},
|
|
490
|
+
async clear(sub) {
|
|
491
|
+
await storage.set(`rockfeller:gen:${sub}`, String(Date.now()), GENERATION_TTL_SECONDS);
|
|
492
|
+
}
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
// src/modules/sso/provider.ts
|
|
497
|
+
function createRockfellerProvider(config) {
|
|
498
|
+
const credentials = {
|
|
499
|
+
clientId: config.clientId,
|
|
500
|
+
clientSecret: config.clientSecret
|
|
501
|
+
};
|
|
502
|
+
const resource = config.resource ? { resource: config.resource } : void 0;
|
|
503
|
+
return {
|
|
504
|
+
id: config.id,
|
|
505
|
+
name: config.name,
|
|
506
|
+
issuer: config.urls.issuer,
|
|
507
|
+
requiresIdTokenNonce: true,
|
|
508
|
+
accountSubject: ({ profile }) => profile.sub,
|
|
509
|
+
options: {
|
|
510
|
+
disableIdTokenSignIn: true,
|
|
511
|
+
overrideUserInfoOnSignIn: true
|
|
512
|
+
},
|
|
513
|
+
createAuthorizationURL(data) {
|
|
514
|
+
return createAuthorizationURL({
|
|
515
|
+
id: config.id,
|
|
516
|
+
options: credentials,
|
|
517
|
+
authorizationEndpoint: config.urls.authorize,
|
|
518
|
+
state: data.state,
|
|
519
|
+
codeVerifier: data.codeVerifier,
|
|
520
|
+
scopes: [.../* @__PURE__ */ new Set([...config.scopes, ...data.scopes ?? []])],
|
|
521
|
+
redirectURI: data.redirectURI,
|
|
522
|
+
nonce: data.idTokenNonce,
|
|
523
|
+
loginHint: data.loginHint,
|
|
524
|
+
additionalParams: {
|
|
525
|
+
...resource,
|
|
526
|
+
...data.additionalParams
|
|
527
|
+
}
|
|
528
|
+
});
|
|
529
|
+
},
|
|
530
|
+
validateAuthorizationCode(data) {
|
|
531
|
+
return validateAuthorizationCode({
|
|
532
|
+
code: data.code,
|
|
533
|
+
codeVerifier: data.codeVerifier,
|
|
534
|
+
redirectURI: data.redirectURI,
|
|
535
|
+
options: credentials,
|
|
536
|
+
tokenEndpoint: config.urls.token,
|
|
537
|
+
authentication: "basic",
|
|
538
|
+
additionalParams: resource
|
|
539
|
+
});
|
|
540
|
+
},
|
|
541
|
+
refreshAccessToken(refreshToken) {
|
|
542
|
+
return refreshAccessToken({
|
|
543
|
+
refreshToken,
|
|
544
|
+
options: credentials,
|
|
545
|
+
tokenEndpoint: config.urls.token,
|
|
546
|
+
authentication: "basic",
|
|
547
|
+
extraParams: resource
|
|
548
|
+
});
|
|
549
|
+
},
|
|
550
|
+
async getUserInfo(tokens) {
|
|
551
|
+
if (!tokens.idToken) return null;
|
|
552
|
+
try {
|
|
553
|
+
const claims = await verifyIdToken(tokens.idToken, {
|
|
554
|
+
issuer: config.urls.issuer,
|
|
555
|
+
clientId: config.clientId,
|
|
556
|
+
nonce: tokens.expectedIdTokenNonce
|
|
557
|
+
});
|
|
558
|
+
return {
|
|
559
|
+
user: {
|
|
560
|
+
name: claims.name ?? claims.email ?? "",
|
|
561
|
+
email: claims.email ?? null,
|
|
562
|
+
emailVerified: claims.email_verified ?? false,
|
|
563
|
+
...claims.picture ? { image: claims.picture } : {}
|
|
564
|
+
},
|
|
565
|
+
data: claims
|
|
566
|
+
};
|
|
567
|
+
} catch {
|
|
568
|
+
return null;
|
|
569
|
+
}
|
|
570
|
+
},
|
|
571
|
+
createEndSessionURL({ idToken, postLogoutRedirectURI, state }) {
|
|
572
|
+
const target = postLogoutRedirectURI ?? config.postLogoutRedirectURI;
|
|
573
|
+
if (!target) return null;
|
|
574
|
+
const url = new URL(config.urls.endSession);
|
|
575
|
+
url.searchParams.set("client_id", config.clientId);
|
|
576
|
+
url.searchParams.set("post_logout_redirect_uri", target);
|
|
577
|
+
if (idToken) url.searchParams.set("id_token_hint", idToken);
|
|
578
|
+
if (state) url.searchParams.set("state", state);
|
|
579
|
+
return url;
|
|
580
|
+
}
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
// src/modules/sso/plugin/init.ts
|
|
585
|
+
function createInit(runtime) {
|
|
586
|
+
const { options, providers, urls } = runtime;
|
|
587
|
+
return function init(ctx) {
|
|
588
|
+
const storage = ctx.options.secondaryStorage;
|
|
589
|
+
if (storage) runtime.replaceCache(createPermissionCache({
|
|
590
|
+
ttlSeconds: options.permissionsCacheSeconds ?? 60,
|
|
591
|
+
storage
|
|
592
|
+
}));
|
|
593
|
+
const postLogoutRedirectURI = options.postLogoutRedirect ?? new URL(ctx.baseURL).origin;
|
|
594
|
+
const created = [createRockfellerProvider({
|
|
595
|
+
id: PROVIDER_ID,
|
|
596
|
+
name: "Conta Rockfeller",
|
|
597
|
+
urls,
|
|
598
|
+
clientId: options.clientId,
|
|
599
|
+
clientSecret: options.clientSecret,
|
|
600
|
+
scopes: [...SIGN_IN_SCOPES, ...options.scopes ?? []],
|
|
601
|
+
resource: options.api,
|
|
602
|
+
postLogoutRedirectURI
|
|
603
|
+
}), ...options.team ? [createRockfellerProvider({
|
|
604
|
+
id: TEAM_PROVIDER_ID,
|
|
605
|
+
name: "Conta Rockfeller (equipe)",
|
|
606
|
+
urls,
|
|
607
|
+
clientId: options.clientId,
|
|
608
|
+
clientSecret: options.clientSecret,
|
|
609
|
+
scopes: [...SIGN_IN_SCOPES, TEAM_SCOPE],
|
|
610
|
+
resource: urls.manage
|
|
611
|
+
})] : []];
|
|
612
|
+
for (const provider of created) providers.set(provider.id, provider);
|
|
613
|
+
return {
|
|
614
|
+
context: { socialProviders: [...created, ...ctx.socialProviders] },
|
|
615
|
+
options: {
|
|
616
|
+
databaseHooks: { session: { create: { async before(session, hookCtx) {
|
|
617
|
+
const callback = hookCtx;
|
|
618
|
+
if (!callback?.path?.includes("/callback") || callback.params?.id !== "rockfeller") return;
|
|
619
|
+
const linked = await ctx.internalAdapter.findAccounts(session.userId);
|
|
620
|
+
const sid = readSid(linked.find((account) => account.providerId === PROVIDER_ID)?.idToken);
|
|
621
|
+
return sid ? { data: {
|
|
622
|
+
...session,
|
|
623
|
+
[SID_FIELD]: sid
|
|
624
|
+
} } : void 0;
|
|
625
|
+
} } } },
|
|
626
|
+
account: { accountLinking: { trustedProviders: created.map((provider) => provider.id) } }
|
|
627
|
+
}
|
|
628
|
+
};
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
// src/modules/sso/shared/sessions.ts
|
|
633
|
+
async function endSessions(context, userId, sid) {
|
|
634
|
+
if (!sid) {
|
|
635
|
+
await context.internalAdapter.deleteUserSessions(userId);
|
|
636
|
+
return;
|
|
637
|
+
}
|
|
638
|
+
const sessions = await context.internalAdapter.listSessions(userId);
|
|
639
|
+
await Promise.all(sessions.filter((session) => {
|
|
640
|
+
const linked = session[SID_FIELD];
|
|
641
|
+
return !linked || linked === sid;
|
|
642
|
+
}).map((session) => context.internalAdapter.deleteSession(session.token)));
|
|
643
|
+
}
|
|
644
|
+
async function syncUser(context, userId, user) {
|
|
645
|
+
const update = {};
|
|
646
|
+
if (user.name !== void 0) update.name = user.name;
|
|
647
|
+
if (user.picture !== void 0) update.image = user.picture;
|
|
648
|
+
if (user.emailVerified !== void 0) update.emailVerified = user.emailVerified;
|
|
649
|
+
if (user.email !== void 0) {
|
|
650
|
+
const owner = await context.internalAdapter.findUserByEmail(user.email);
|
|
651
|
+
if (!owner || owner.user.id === userId) update.email = user.email;
|
|
652
|
+
}
|
|
653
|
+
if (Object.keys(update).length > 0) await context.internalAdapter.updateUser(userId, update);
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
// src/modules/sso/shared/webhook-path.ts
|
|
657
|
+
function normalizeWebhookPath(path = "/webhooks/sso") {
|
|
658
|
+
const trimmed = path.trim().replace(/^\/+|\/+$/g, "");
|
|
659
|
+
if (!trimmed) throw new Error("`webhooks.path` não pode ser vazio.");
|
|
660
|
+
return `/${trimmed}`;
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
// src/modules/sso/plugin/runtime.ts
|
|
664
|
+
function createRuntime(options) {
|
|
665
|
+
const issuer = normalizeIssuer(options.issuer);
|
|
666
|
+
const urls = accountsUrls(issuer);
|
|
667
|
+
const webhookPath = normalizeWebhookPath(options.webhooks?.path);
|
|
668
|
+
const accounts = createAccountsApi({
|
|
669
|
+
issuer,
|
|
670
|
+
clientId: options.clientId,
|
|
671
|
+
clientSecret: options.clientSecret
|
|
672
|
+
});
|
|
673
|
+
let cache = createPermissionCache({ ttlSeconds: options.permissionsCacheSeconds ?? 60 });
|
|
674
|
+
const providers = /* @__PURE__ */ new Map();
|
|
675
|
+
const refreshing = /* @__PURE__ */ new Map();
|
|
676
|
+
async function refresh(context, account) {
|
|
677
|
+
const provider = providers.get(account.providerId);
|
|
678
|
+
if (!(provider?.refreshAccessToken && account.refreshToken)) fail(RockfellerErrorCode.INVALID_TOKEN, 401, "A conta não tem refresh token.");
|
|
679
|
+
const tokens = await provider.refreshAccessToken(await decryptOAuthToken(account.refreshToken, context));
|
|
680
|
+
if (!tokens.accessToken) fail(RockfellerErrorCode.INVALID_TOKEN, 401, "O Accounts não renovou o token.");
|
|
681
|
+
await context.internalAdapter.updateAccount(account.id, {
|
|
682
|
+
accessToken: await setTokenUtil(tokens.accessToken, context),
|
|
683
|
+
accessTokenExpiresAt: tokens.accessTokenExpiresAt,
|
|
684
|
+
refreshToken: tokens.refreshToken ? await setTokenUtil(tokens.refreshToken, context) : account.refreshToken,
|
|
685
|
+
refreshTokenExpiresAt: tokens.refreshTokenExpiresAt ?? account.refreshTokenExpiresAt,
|
|
686
|
+
idToken: tokens.idToken ?? account.idToken
|
|
687
|
+
});
|
|
688
|
+
return tokens.accessToken;
|
|
689
|
+
}
|
|
690
|
+
async function accessTokenFor(context, account) {
|
|
691
|
+
const expiresAt = account.accessTokenExpiresAt ? new Date(account.accessTokenExpiresAt).getTime() : null;
|
|
692
|
+
if (account.accessToken && (expiresAt === null || expiresAt - Date.now() > 3e4)) return decryptOAuthToken(account.accessToken, context);
|
|
693
|
+
let pending = refreshing.get(account.id);
|
|
694
|
+
if (!pending) {
|
|
695
|
+
pending = refresh(context, account).finally(() => {
|
|
696
|
+
refreshing.delete(account.id);
|
|
697
|
+
});
|
|
698
|
+
refreshing.set(account.id, pending);
|
|
699
|
+
}
|
|
700
|
+
return pending;
|
|
701
|
+
}
|
|
702
|
+
async function permissionsFor(sub, school, sid = null) {
|
|
703
|
+
const scope = sid ? `${cacheScope(school)}:imp:${sid}` : cacheScope(school);
|
|
704
|
+
const cached = await cache.get(sub, scope);
|
|
705
|
+
if (cached) return cached;
|
|
706
|
+
const fresh = await accounts.permissions(sub, school, sid ?? void 0);
|
|
707
|
+
await cache.set(sub, scope, fresh);
|
|
708
|
+
return fresh;
|
|
709
|
+
}
|
|
710
|
+
async function teamToken(ctx) {
|
|
711
|
+
if (!options.team) fail(RockfellerErrorCode.TEAM_NOT_ENABLED, 400, "Ligue `team: true` no plugin rockfeller().");
|
|
712
|
+
const account = await linkedAccount(ctx, "rockfeller-team") ?? fail(RockfellerErrorCode.TEAM_NOT_CONNECTED, 403, "Vincule a gestão de equipe com authClient.rockfeller.team.connect().");
|
|
713
|
+
return accessTokenFor(ctx.context, account);
|
|
714
|
+
}
|
|
715
|
+
const defaultActions = options.webhooks?.defaultActions ?? true;
|
|
716
|
+
async function sessionEnded(context, input) {
|
|
717
|
+
if (defaultActions) {
|
|
718
|
+
if (input.userId) await endSessions(context, input.userId, input.sid);
|
|
719
|
+
await cache.clear(input.sub);
|
|
720
|
+
}
|
|
721
|
+
await options.webhooks?.hooks?.onSessionEnded?.(input);
|
|
722
|
+
}
|
|
723
|
+
async function handleWebhook(context, event, hooks) {
|
|
724
|
+
const sub = event.data.user.sub;
|
|
725
|
+
const userId = await localUserId(context, sub);
|
|
726
|
+
if (event.type === "session.ended") {
|
|
727
|
+
await sessionEnded(context, {
|
|
728
|
+
sub,
|
|
729
|
+
userId,
|
|
730
|
+
sid: event.data.sid,
|
|
731
|
+
source: "webhook",
|
|
732
|
+
event
|
|
733
|
+
});
|
|
734
|
+
return;
|
|
735
|
+
}
|
|
736
|
+
if (defaultActions) {
|
|
737
|
+
if (ENDS_ALL_SESSIONS.has(event.type)) {
|
|
738
|
+
if (userId) await context.internalAdapter.deleteUserSessions(userId);
|
|
739
|
+
await cache.clear(sub);
|
|
740
|
+
} else if (event.type === "membership.granted" || event.type === "membership.revoked") await cache.clear(sub);
|
|
741
|
+
else if (event.type === "user.updated" && userId) await syncUser(context, userId, event.data.user);
|
|
742
|
+
}
|
|
743
|
+
const hook = hooks?.[HOOK_NAMES[event.type]];
|
|
744
|
+
await hook?.({
|
|
745
|
+
sub,
|
|
746
|
+
userId,
|
|
747
|
+
event
|
|
748
|
+
});
|
|
749
|
+
}
|
|
750
|
+
return {
|
|
751
|
+
options,
|
|
752
|
+
issuer,
|
|
753
|
+
urls,
|
|
754
|
+
webhookPath,
|
|
755
|
+
accounts,
|
|
756
|
+
providers,
|
|
757
|
+
accessTokenFor,
|
|
758
|
+
permissionsFor,
|
|
759
|
+
teamToken,
|
|
760
|
+
sessionEnded,
|
|
761
|
+
handleWebhook,
|
|
762
|
+
get cache() {
|
|
763
|
+
return cache;
|
|
764
|
+
},
|
|
765
|
+
replaceCache(next) {
|
|
766
|
+
cache = next;
|
|
767
|
+
}
|
|
768
|
+
};
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
// src/modules/sso/plugin/rockfeller.ts
|
|
772
|
+
function rockfeller(options) {
|
|
773
|
+
const runtime = createRuntime(options);
|
|
774
|
+
return {
|
|
775
|
+
id: "rockfeller",
|
|
776
|
+
init: createInit(runtime),
|
|
777
|
+
hooks: { before: [{
|
|
778
|
+
matcher: (ctx) => ctx.path === "/sign-out",
|
|
779
|
+
handler: createAuthMiddleware(async (ctx) => ({ context: { body: {
|
|
780
|
+
...ctx.body,
|
|
781
|
+
disableRedirect: ctx.body?.disableRedirect ?? true
|
|
782
|
+
} } }))
|
|
783
|
+
}, ...options.allowLocalSignIn ? [] : [{
|
|
784
|
+
matcher: (ctx) => LOCAL_SIGN_IN_PATHS.has(ctx.path ?? ""),
|
|
785
|
+
handler: createAuthMiddleware(async () => {
|
|
786
|
+
throw new APIError("FORBIDDEN", {
|
|
787
|
+
code: RockfellerErrorCode.LOCAL_SIGN_IN_DISABLED,
|
|
788
|
+
message: "Este app só aceita login pela Conta Rockfeller."
|
|
789
|
+
});
|
|
790
|
+
})
|
|
791
|
+
}]] },
|
|
792
|
+
endpoints: {
|
|
793
|
+
getRockfellerAccount: createGetRockfellerAccountEndpoint(),
|
|
794
|
+
getApiToken: createGetApiTokenEndpoint(runtime),
|
|
795
|
+
refreshProfile: createRefreshProfileEndpoint(runtime),
|
|
796
|
+
getProfileUrl: createGetProfileUrlEndpoint(runtime),
|
|
797
|
+
listSchools: createListSchoolsEndpoint(runtime),
|
|
798
|
+
getSchoolPermissions: createGetSchoolPermissionsEndpoint(runtime),
|
|
799
|
+
hasPermission: createHasPermissionEndpoint(runtime),
|
|
800
|
+
requirePermission: createRequirePermissionEndpoint(runtime),
|
|
801
|
+
listTeamMembers: createListTeamMembersEndpoint(runtime),
|
|
802
|
+
inviteTeamMember: createInviteTeamMemberEndpoint(runtime),
|
|
803
|
+
revokeTeamRoles: createRevokeTeamRolesEndpoint(runtime),
|
|
804
|
+
rockfellerBackchannelLogout: createRockfellerBackchannelLogoutEndpoint(runtime),
|
|
805
|
+
rockfellerWebhooks: createRockfellerWebhooksEndpoint(runtime)
|
|
806
|
+
},
|
|
807
|
+
schema: { session: { fields: { [SID_FIELD]: {
|
|
808
|
+
type: "string",
|
|
809
|
+
required: false,
|
|
810
|
+
input: false
|
|
811
|
+
} } } },
|
|
812
|
+
rateLimit: [{
|
|
813
|
+
pathMatcher: (path) => path === "/rockfeller/backchannel-logout" || path === runtime.webhookPath,
|
|
814
|
+
window: 60,
|
|
815
|
+
max: 300
|
|
816
|
+
}]
|
|
817
|
+
};
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
export { DEFAULT_ISSUER, PROVIDER_ID, RockfellerError, RockfellerErrorCode, TEAM_PROVIDER_ID, WEBHOOK_EVENT_TYPES, WebhookVerificationError, isRockfellerError, rockfeller, verifyWebhook };
|
|
821
|
+
//# sourceMappingURL=index.js.map
|