@dolfinhos/standalone 0.0.0-stage → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +70 -2
- package/dist/bin.js +11 -0
- package/dist/bin.js.map +1 -0
- package/dist/chunk-KXJJDYJM.js +539 -0
- package/dist/chunk-KXJJDYJM.js.map +1 -0
- package/dist/index.d.ts +147 -0
- package/dist/index.js +31 -0
- package/dist/index.js.map +1 -0
- package/dist/web/studio.css +1 -0
- package/dist/web/studio.js +86 -0
- package/package.json +70 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Dolfinsis
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,71 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @dolfinhos/standalone
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
O Dolfinhos como servidor separado, para aplicações que não são Node: Java (Spring), .NET, Go, Python, PHP. A aplicação é descrita pelo OpenAPI dela; o Dolfinhos roda ao lado, com Postgres, e oferece o mesmo que a integração com NestJS: chat, operadores, aprovações, regras por empresa, memória, agenda, relatórios, auditoria, uso e avaliações.
|
|
4
|
+
|
|
5
|
+
## Como funciona
|
|
6
|
+
|
|
7
|
+
- **Ações:** cada operação do OpenAPI vira uma ação da IA. O verbo diz o tipo (GET consulta, POST cria, PUT/PATCH altera, DELETE exclui), então as regras de aprovação já valem: consultar é livre, o resto pergunta.
|
|
8
|
+
- **Permissões continuam na aplicação:** cada ação chama a API com o `Authorization` e o `cookie` da própria pessoa. O que ela não pode fazer na aplicação, a IA também não faz por ela.
|
|
9
|
+
- **Quem está pedindo:** o Dolfinhos confere o JWT da aplicação (segredo compartilhado ou JWKS do provedor de login) ou pergunta a um endpoint da aplicação (`/me`). O token precisa ter validade (`exp`); `none` e troca de algoritmo são recusados.
|
|
10
|
+
- **Agenda, bots e tarefas de operadores** chamam a aplicação com `APP_SERVICE_TOKEN` e o cabeçalho da empresa (`x-tenant-id`). A aplicação só deve aceitar esse cabeçalho junto com o token de serviço.
|
|
11
|
+
|
|
12
|
+
## Subir com Docker
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
cp packages/standalone/docker-compose.example.yml packages/standalone/docker-compose.yml
|
|
16
|
+
cp packages/standalone/.env.example packages/standalone/.env # preencha
|
|
17
|
+
cd packages/standalone && docker compose up -d
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Ou só a imagem (da raiz do repositório): `docker build -f packages/standalone/Dockerfile -t dolfinhos .`
|
|
21
|
+
|
|
22
|
+
Sem Docker: `npm i @dolfinhos/standalone` e `npx dolfinhos-server`, com as variáveis no ambiente. As tabelas são criadas ao subir. `GET /health` responde `{ "ok": true }`.
|
|
23
|
+
|
|
24
|
+
## Variáveis
|
|
25
|
+
|
|
26
|
+
| Variável | Para quê |
|
|
27
|
+
|---|---|
|
|
28
|
+
| `DATABASE_URL` | Postgres (obrigatório). |
|
|
29
|
+
| `PORT` | Padrão: 4000. |
|
|
30
|
+
| `APP_OPENAPI_URL` | O OpenAPI 3 em JSON (no Spring com springdoc: `/v3/api-docs`; em Express, Fastify e Next.js, a rota com `openApiFromRoutes`, veja o README principal). Buscado com o `APP_SERVICE_TOKEN`. |
|
|
31
|
+
| `APP_BASE_URL` | Endereço da API, se o OpenAPI não trouxer um absoluto em `servers`. |
|
|
32
|
+
| `APP_SERVICE_TOKEN` | Token das chamadas de agenda, bots e operadores. |
|
|
33
|
+
| `APP_TENANT_HEADER` | Cabeçalho da empresa nessas chamadas. Padrão: `x-tenant-id`. |
|
|
34
|
+
| `APP_INCLUDE_TAGS` | Só estas etiquetas do OpenAPI viram ações (vírgula). |
|
|
35
|
+
| `APP_READ_ONLY` | `true`: só consultas, para começar com segurança. |
|
|
36
|
+
| `APP_DESCRIPTION` | Uma frase sobre a aplicação, para o assistente. |
|
|
37
|
+
| `AUTH_JWT_SECRET` / `AUTH_JWKS_URL` / `AUTH_INTROSPECT_URL` | Um deles: como identificar a pessoa. |
|
|
38
|
+
| `AUTH_ISSUER`, `AUTH_AUDIENCE` | Conferidos no JWT, se informados. |
|
|
39
|
+
| `AUTH_CLAIM_USER`, `AUTH_CLAIM_TENANT`, `AUTH_CLAIM_ROLES` | Onde ler cada dado (aceita `realm_access.roles`). Padrões: `sub`, `tenant_id`, `roles`. |
|
|
40
|
+
| `ADMIN_ROLES` | Perfis que administram (regras, operadores, auditoria). Padrão: `ADMIN`. |
|
|
41
|
+
| `CORS_ORIGINS` | Front-ends que chamam o Dolfinhos direto do navegador. |
|
|
42
|
+
| `APP_PUBLIC_URL` | Endereço da aplicação para o botão "Voltar" do Studio. |
|
|
43
|
+
| `STUDIO_ENABLED` | `false` desliga a página `/studio`. Padrão: ligada. |
|
|
44
|
+
| `AI_PROVIDER`, `AI_API_KEY`, `AI_MODEL` | Chave da plataforma (`deepseek`, `anthropic` ou `openai`). |
|
|
45
|
+
| `DOLFINHOS_SECRET` | Criptografa as chaves e os conectores que cada empresa cadastra no Studio (32+ caracteres). Sem ele, a aba Conectores fica vazia. Com ele, WhatsApp e e-mail também respondem às mensagens que chegam, pelo operador de atendimento, que só consulta a base de conhecimento; o endereço para colar no provedor aparece na própria aba. |
|
|
46
|
+
|
|
47
|
+
Falta algo obrigatório ou há combinação inválida: o servidor não sobe e lista tudo o que falta de uma vez.
|
|
48
|
+
|
|
49
|
+
## Studio pronto em `/studio`
|
|
50
|
+
|
|
51
|
+
A administração da IA (aprovações, tarefas, relatórios, operadores, regras, automações, conhecimento, memória, custos, modelo e auditoria) vem pronta em `/studio`, sem nada para instalar no front-end. Ponha no menu da aplicação um link para `https://<dolfinhos>/studio#token=<o JWT da pessoa>`: o que vem depois do `#` não vai ao servidor nem aparece em logs, e a página guarda o token só naquela aba e o tira do endereço. Com sessão por cookie no mesmo domínio, basta `/studio`.
|
|
52
|
+
|
|
53
|
+
Só quem tem um perfil de `ADMIN_ROLES` vê o Studio; os outros veem "Sem permissão". Token vencido ou inválido leva a "Entre pela aplicação", com o botão de voltar para `APP_PUBLIC_URL`. A página só fala com o próprio servidor e não pode ser embutida em outro site (CSP com `frame-ancestors 'none'`).
|
|
54
|
+
|
|
55
|
+
## No front-end (React)
|
|
56
|
+
|
|
57
|
+
Para embutir o chat ou o Studio no front-end da aplicação, os componentes são os mesmos da integração com NestJS, apontando para o endereço do Dolfinhos e mandando o token da pessoa:
|
|
58
|
+
|
|
59
|
+
```tsx
|
|
60
|
+
<DolfinhosProvider endpoint="https://dolfinhos.loja.exemplo/dolfinhos" headers={() => ({ authorization: `Bearer ${token()}` })}>
|
|
61
|
+
<StudioProvider endpoint="https://dolfinhos.loja.exemplo/dolfinhos" headers={() => ({ authorization: `Bearer ${token()}` })}>
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Lembre de pôr o endereço do front-end em `CORS_ORIGINS`.
|
|
65
|
+
|
|
66
|
+
## No Spring
|
|
67
|
+
|
|
68
|
+
- springdoc (`org.springdoc:springdoc-openapi-starter-webmvc-ui`) publica o OpenAPI em `/v3/api-docs`. Dê `operationId` e `summary` claros às operações: viram o nome e a descrição das ações. Use `@Tag` para agrupar e `APP_INCLUDE_TAGS` para escolher.
|
|
69
|
+
- Com Spring Security + JWT (Keycloak, Auth0, Cognito), use `AUTH_JWKS_URL` com o mesmo provedor.
|
|
70
|
+
- Com sessão por cookie, exponha um `GET /api/me` que devolve `{ "id", "tenantId", "roles" }` e use `AUTH_INTROSPECT_URL` com `AUTH_CLAIM_USER=id` e `AUTH_CLAIM_TENANT=tenantId`. Sirva o Dolfinhos no mesmo domínio da aplicação (proxy reverso em `/dolfinhos`), senão o navegador não manda o cookie; no front-end, passe `credentials="include"` ao `DolfinhosProvider`.
|
|
71
|
+
- Para o token de serviço, aceite `APP_SERVICE_TOKEN` num filtro que lê `x-tenant-id` só quando esse token vem junto.
|
package/dist/bin.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
startStandalone
|
|
4
|
+
} from "./chunk-KXJJDYJM.js";
|
|
5
|
+
|
|
6
|
+
// src/bin.ts
|
|
7
|
+
startStandalone().catch((error) => {
|
|
8
|
+
console.error(error instanceof Error ? error.message : error);
|
|
9
|
+
process.exit(1);
|
|
10
|
+
});
|
|
11
|
+
//# sourceMappingURL=bin.js.map
|
package/dist/bin.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/bin.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { startStandalone } from './server.js';\n\nstartStandalone().catch((error: unknown) => {\n console.error(error instanceof Error ? error.message : error);\n process.exit(1);\n});\n"],"mappings":";;;;;;AAGA,gBAAgB,EAAE,MAAM,CAAC,UAAmB;AAC1C,UAAQ,MAAM,iBAAiB,QAAQ,MAAM,UAAU,KAAK;AAC5D,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":[]}
|
|
@@ -0,0 +1,539 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __decorateClass = (decorators, target, key, kind) => {
|
|
4
|
+
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
|
|
5
|
+
for (var i = decorators.length - 1, decorator; i >= 0; i--)
|
|
6
|
+
if (decorator = decorators[i])
|
|
7
|
+
result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
8
|
+
if (kind && result) __defProp(target, key, result);
|
|
9
|
+
return result;
|
|
10
|
+
};
|
|
11
|
+
var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
|
|
12
|
+
|
|
13
|
+
// src/env.ts
|
|
14
|
+
import { z } from "zod";
|
|
15
|
+
var csv = z.string().optional().transform((v) => v ? v.split(",").map((s) => s.trim()).filter(Boolean) : []);
|
|
16
|
+
var flag = z.enum(["true", "false", "1", "0", ""]).optional().transform((v) => v === "true" || v === "1");
|
|
17
|
+
var url = (name) => z.url({ protocol: /^https?$/, error: `${name} precisa ser um endere\xE7o http(s) completo.` });
|
|
18
|
+
var schema = z.object({
|
|
19
|
+
DATABASE_URL: z.string({ error: "Informe o endere\xE7o do Postgres." }).min(1, "Informe o endere\xE7o do Postgres."),
|
|
20
|
+
PORT: z.coerce.number().int().min(1).max(65535).default(4e3),
|
|
21
|
+
APP_OPENAPI_URL: url("APP_OPENAPI_URL (o endere\xE7o do OpenAPI da aplica\xE7\xE3o, ex.: http://app:8080/v3/api-docs)"),
|
|
22
|
+
APP_BASE_URL: url("APP_BASE_URL").optional(),
|
|
23
|
+
APP_SERVICE_TOKEN: z.string().min(1).optional(),
|
|
24
|
+
APP_TENANT_HEADER: z.string().regex(/^[a-zA-Z0-9-]+$/).default("x-tenant-id"),
|
|
25
|
+
APP_INCLUDE_TAGS: csv,
|
|
26
|
+
APP_READ_ONLY: flag,
|
|
27
|
+
APP_DESCRIPTION: z.string().max(500).optional(),
|
|
28
|
+
AUTH_JWT_SECRET: z.string().min(32, "AUTH_JWT_SECRET precisa de pelo menos 32 caracteres.").optional(),
|
|
29
|
+
AUTH_JWKS_URL: url("AUTH_JWKS_URL").optional(),
|
|
30
|
+
AUTH_INTROSPECT_URL: url("AUTH_INTROSPECT_URL").optional(),
|
|
31
|
+
AUTH_ISSUER: z.string().optional(),
|
|
32
|
+
AUTH_AUDIENCE: z.string().optional(),
|
|
33
|
+
AUTH_CLAIM_USER: z.string().default("sub"),
|
|
34
|
+
AUTH_CLAIM_TENANT: z.string().default("tenant_id"),
|
|
35
|
+
AUTH_CLAIM_ROLES: z.string().default("roles"),
|
|
36
|
+
ADMIN_ROLES: csv.transform((v) => v.length ? v : ["ADMIN"]),
|
|
37
|
+
CORS_ORIGINS: csv,
|
|
38
|
+
STUDIO_ENABLED: z.enum(["true", "false", "1", "0", ""]).optional().transform((v) => v !== "false" && v !== "0"),
|
|
39
|
+
APP_PUBLIC_URL: url("APP_PUBLIC_URL").optional(),
|
|
40
|
+
AI_PROVIDER: z.enum(["deepseek", "anthropic", "openai"]).optional(),
|
|
41
|
+
AI_API_KEY: z.string().min(1).optional(),
|
|
42
|
+
AI_MODEL: z.string().min(1).optional(),
|
|
43
|
+
DOLFINHOS_SECRET: z.string().min(32, "DOLFINHOS_SECRET precisa de pelo menos 32 caracteres (openssl rand -base64 32).").optional()
|
|
44
|
+
});
|
|
45
|
+
function crossCheck(env) {
|
|
46
|
+
const problems = [];
|
|
47
|
+
const auth = [env.AUTH_JWT_SECRET, env.AUTH_JWKS_URL, env.AUTH_INTROSPECT_URL].filter(Boolean).length;
|
|
48
|
+
if (auth !== 1) problems.push("Configure um (e s\xF3 um) jeito de identificar o usu\xE1rio: AUTH_JWT_SECRET, AUTH_JWKS_URL ou AUTH_INTROSPECT_URL.");
|
|
49
|
+
const platform = [env.AI_PROVIDER, env.AI_API_KEY, env.AI_MODEL].filter(Boolean).length;
|
|
50
|
+
if (platform && platform !== 3) problems.push("Para a chave da plataforma, informe AI_PROVIDER, AI_API_KEY e AI_MODEL juntos.");
|
|
51
|
+
if (!platform && !env.DOLFINHOS_SECRET) {
|
|
52
|
+
problems.push("Sem modelo: informe AI_PROVIDER, AI_API_KEY e AI_MODEL, ou DOLFINHOS_SECRET para cada empresa cadastrar a pr\xF3pria chave no Studio.");
|
|
53
|
+
}
|
|
54
|
+
return problems;
|
|
55
|
+
}
|
|
56
|
+
function readConfig(env = process.env) {
|
|
57
|
+
const parsed = schema.safeParse(env);
|
|
58
|
+
const problems = [...parsed.success ? [] : parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`), ...crossCheck(env)];
|
|
59
|
+
if (!parsed.success || problems.length) throw new Error(`Configura\xE7\xE3o do Dolfinhos incompleta:
|
|
60
|
+
${problems.map((p) => ` - ${p}`).join("\n")}`);
|
|
61
|
+
const e = parsed.data;
|
|
62
|
+
const claims = { user: e.AUTH_CLAIM_USER, tenant: e.AUTH_CLAIM_TENANT, roles: e.AUTH_CLAIM_ROLES };
|
|
63
|
+
return {
|
|
64
|
+
databaseUrl: e.DATABASE_URL,
|
|
65
|
+
port: e.PORT,
|
|
66
|
+
app: {
|
|
67
|
+
openapiUrl: e.APP_OPENAPI_URL,
|
|
68
|
+
...e.APP_BASE_URL ? { baseUrl: e.APP_BASE_URL } : {},
|
|
69
|
+
...e.APP_SERVICE_TOKEN ? { serviceToken: e.APP_SERVICE_TOKEN } : {},
|
|
70
|
+
tenantHeader: e.APP_TENANT_HEADER.toLowerCase(),
|
|
71
|
+
includeTags: e.APP_INCLUDE_TAGS,
|
|
72
|
+
readOnly: e.APP_READ_ONLY,
|
|
73
|
+
...e.APP_DESCRIPTION ? { description: e.APP_DESCRIPTION } : {}
|
|
74
|
+
},
|
|
75
|
+
auth: e.AUTH_INTROSPECT_URL ? { kind: "introspect", url: e.AUTH_INTROSPECT_URL, claims } : {
|
|
76
|
+
kind: "jwt",
|
|
77
|
+
...e.AUTH_JWT_SECRET ? { secret: e.AUTH_JWT_SECRET } : {},
|
|
78
|
+
...e.AUTH_JWKS_URL ? { jwksUrl: e.AUTH_JWKS_URL } : {},
|
|
79
|
+
...e.AUTH_ISSUER ? { issuer: e.AUTH_ISSUER } : {},
|
|
80
|
+
...e.AUTH_AUDIENCE ? { audience: e.AUTH_AUDIENCE } : {},
|
|
81
|
+
claims
|
|
82
|
+
},
|
|
83
|
+
adminRoles: e.ADMIN_ROLES,
|
|
84
|
+
corsOrigins: e.CORS_ORIGINS,
|
|
85
|
+
studio: { enabled: e.STUDIO_ENABLED, ...e.APP_PUBLIC_URL ? { appUrl: e.APP_PUBLIC_URL } : {} },
|
|
86
|
+
ai: {
|
|
87
|
+
platform: e.AI_PROVIDER && e.AI_API_KEY && e.AI_MODEL ? { provider: e.AI_PROVIDER, apiKey: e.AI_API_KEY, model: e.AI_MODEL } : null,
|
|
88
|
+
...e.DOLFINHOS_SECRET ? { secret: e.DOLFINHOS_SECRET } : {}
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// src/auth.ts
|
|
94
|
+
import { createHash, createHmac, createPublicKey, timingSafeEqual, verify, constants } from "crypto";
|
|
95
|
+
function at(value, path) {
|
|
96
|
+
return path.split(".").reduce((v, key) => v && typeof v === "object" ? v[key] : void 0, value);
|
|
97
|
+
}
|
|
98
|
+
function identityFrom(claims, paths = {}) {
|
|
99
|
+
const user = at(claims, paths.user ?? "sub");
|
|
100
|
+
if (typeof user !== "string" && typeof user !== "number" || String(user) === "") return null;
|
|
101
|
+
const tenant = at(claims, paths.tenant ?? "tenant_id");
|
|
102
|
+
const rawRoles = at(claims, paths.roles ?? "roles");
|
|
103
|
+
const roles = Array.isArray(rawRoles) ? rawRoles.map(String) : typeof rawRoles === "string" ? rawRoles.split(/[\s,]+/).filter(Boolean) : [];
|
|
104
|
+
return { userId: String(user), tenantId: typeof tenant === "string" || typeof tenant === "number" ? String(tenant) : null, roles };
|
|
105
|
+
}
|
|
106
|
+
var b64 = (part) => Buffer.from(part, "base64url");
|
|
107
|
+
var ASYMMETRIC = {
|
|
108
|
+
RS256: { hash: "sha256" },
|
|
109
|
+
RS384: { hash: "sha384" },
|
|
110
|
+
RS512: { hash: "sha512" },
|
|
111
|
+
PS256: { hash: "sha256", pss: true },
|
|
112
|
+
PS384: { hash: "sha384", pss: true },
|
|
113
|
+
PS512: { hash: "sha512", pss: true },
|
|
114
|
+
ES256: { hash: "sha256", ecdsa: true },
|
|
115
|
+
ES384: { hash: "sha384", ecdsa: true },
|
|
116
|
+
ES512: { hash: "sha512", ecdsa: true },
|
|
117
|
+
EdDSA: { hash: null }
|
|
118
|
+
};
|
|
119
|
+
var HMAC = { HS256: "sha256", HS384: "sha384", HS512: "sha512" };
|
|
120
|
+
var JwtError = class extends Error {
|
|
121
|
+
constructor(message) {
|
|
122
|
+
super(message);
|
|
123
|
+
this.name = "JwtError";
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
async function verifyJwt(token, options) {
|
|
127
|
+
const parts = token.split(".");
|
|
128
|
+
if (parts.length !== 3) throw new JwtError("Token malformado.");
|
|
129
|
+
const [h, p, s] = parts;
|
|
130
|
+
let header;
|
|
131
|
+
let payload;
|
|
132
|
+
try {
|
|
133
|
+
header = JSON.parse(b64(h).toString("utf8"));
|
|
134
|
+
payload = JSON.parse(b64(p).toString("utf8"));
|
|
135
|
+
} catch {
|
|
136
|
+
throw new JwtError("Token malformado.");
|
|
137
|
+
}
|
|
138
|
+
const data = Buffer.from(`${h}.${p}`);
|
|
139
|
+
const signature = b64(s);
|
|
140
|
+
const alg = header.alg ?? "";
|
|
141
|
+
if (options.secret) {
|
|
142
|
+
const hash = HMAC[alg];
|
|
143
|
+
if (!hash) throw new JwtError(`Algoritmo ${alg || "vazio"} n\xE3o aceito com segredo compartilhado.`);
|
|
144
|
+
const expected = createHmac(hash, options.secret).update(data).digest();
|
|
145
|
+
if (expected.length !== signature.length || !timingSafeEqual(expected, signature)) throw new JwtError("Assinatura inv\xE1lida.");
|
|
146
|
+
} else if (options.key) {
|
|
147
|
+
const spec = ASYMMETRIC[alg];
|
|
148
|
+
if (!spec) throw new JwtError(`Algoritmo ${alg || "vazio"} n\xE3o aceito com chave p\xFAblica.`);
|
|
149
|
+
const key = await options.key(header.kid);
|
|
150
|
+
if (!key) throw new JwtError("Chave do token desconhecida.");
|
|
151
|
+
const ok = verify(spec.hash, data, {
|
|
152
|
+
key,
|
|
153
|
+
...spec.pss ? { padding: constants.RSA_PKCS1_PSS_PADDING, saltLength: constants.RSA_PSS_SALTLEN_DIGEST } : {},
|
|
154
|
+
...spec.ecdsa ? { dsaEncoding: "ieee-p1363" } : {}
|
|
155
|
+
}, signature);
|
|
156
|
+
if (!ok) throw new JwtError("Assinatura inv\xE1lida.");
|
|
157
|
+
} else {
|
|
158
|
+
throw new JwtError("Nenhuma chave configurada.");
|
|
159
|
+
}
|
|
160
|
+
const now = Math.floor((options.now ?? Date.now)() / 1e3);
|
|
161
|
+
const tolerance = options.clockToleranceSec ?? 60;
|
|
162
|
+
if (typeof payload.exp !== "number") throw new JwtError("Token sem validade (exp).");
|
|
163
|
+
if (now > payload.exp + tolerance) throw new JwtError("Token vencido.");
|
|
164
|
+
if (typeof payload.nbf === "number" && now + tolerance < payload.nbf) throw new JwtError("Token ainda n\xE3o vale.");
|
|
165
|
+
if (options.issuer && payload.iss !== options.issuer) throw new JwtError("Emissor do token n\xE3o confere.");
|
|
166
|
+
if (options.audience) {
|
|
167
|
+
const aud = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
|
|
168
|
+
if (!aud.includes(options.audience)) throw new JwtError("P\xFAblico do token n\xE3o confere.");
|
|
169
|
+
}
|
|
170
|
+
return payload;
|
|
171
|
+
}
|
|
172
|
+
function jwksKeys(url2, doFetch = fetch) {
|
|
173
|
+
let keys = /* @__PURE__ */ new Map();
|
|
174
|
+
let fetchedAt = 0;
|
|
175
|
+
let pending = null;
|
|
176
|
+
const refresh = () => pending ??= (async () => {
|
|
177
|
+
try {
|
|
178
|
+
const res = await doFetch(url2, { signal: AbortSignal.timeout(1e4) });
|
|
179
|
+
if (!res.ok) throw new Error(`JWKS respondeu ${res.status}.`);
|
|
180
|
+
const { keys: list } = await res.json();
|
|
181
|
+
const next = /* @__PURE__ */ new Map();
|
|
182
|
+
for (const jwk of list ?? []) {
|
|
183
|
+
if (jwk.use === "enc") continue;
|
|
184
|
+
try {
|
|
185
|
+
next.set(String(jwk.kid ?? ""), createPublicKey({ key: jwk, format: "jwk" }));
|
|
186
|
+
} catch {
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
keys = next;
|
|
190
|
+
fetchedAt = Date.now();
|
|
191
|
+
} finally {
|
|
192
|
+
pending = null;
|
|
193
|
+
}
|
|
194
|
+
})();
|
|
195
|
+
return async (kid) => {
|
|
196
|
+
const age = Date.now() - fetchedAt;
|
|
197
|
+
const pick = () => kid === void 0 ? keys.size === 1 ? [...keys.values()][0] : null : keys.get(kid) ?? null;
|
|
198
|
+
if (age > 6e5 || !pick() && age > 3e4) await refresh();
|
|
199
|
+
return pick();
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
function bearer(headers) {
|
|
203
|
+
const raw = headers.authorization;
|
|
204
|
+
const value = Array.isArray(raw) ? raw[0] : raw;
|
|
205
|
+
const match = value?.match(/^Bearer\s+(.+)$/i);
|
|
206
|
+
return match ? match[1].trim() : null;
|
|
207
|
+
}
|
|
208
|
+
function createAuthenticator(config, doFetch = fetch) {
|
|
209
|
+
if (config.kind === "jwt") {
|
|
210
|
+
const key = config.jwksUrl ? jwksKeys(config.jwksUrl, doFetch) : void 0;
|
|
211
|
+
if (!config.secret && !key) throw new Error("Configure AUTH_JWT_SECRET ou AUTH_JWKS_URL.");
|
|
212
|
+
return async (headers) => {
|
|
213
|
+
const token = bearer(headers);
|
|
214
|
+
if (!token) return null;
|
|
215
|
+
try {
|
|
216
|
+
const claims = await verifyJwt(token, {
|
|
217
|
+
...config.secret ? { secret: config.secret } : { key },
|
|
218
|
+
...config.issuer ? { issuer: config.issuer } : {},
|
|
219
|
+
...config.audience ? { audience: config.audience } : {}
|
|
220
|
+
});
|
|
221
|
+
return identityFrom(claims, config.claims);
|
|
222
|
+
} catch (error) {
|
|
223
|
+
if (error instanceof JwtError) return null;
|
|
224
|
+
throw error;
|
|
225
|
+
}
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
const cache = /* @__PURE__ */ new Map();
|
|
229
|
+
return async (headers) => {
|
|
230
|
+
const forward = {};
|
|
231
|
+
for (const name of ["authorization", "cookie"]) {
|
|
232
|
+
const value = headers[name];
|
|
233
|
+
if (typeof value === "string") forward[name] = value;
|
|
234
|
+
}
|
|
235
|
+
if (!Object.keys(forward).length) return null;
|
|
236
|
+
const id = createHash("sha256").update(JSON.stringify(forward)).digest("hex");
|
|
237
|
+
const hit = cache.get(id);
|
|
238
|
+
if (hit && Date.now() - hit.at < 3e4) return hit.identity;
|
|
239
|
+
const res = await doFetch(config.url, { headers: { ...forward, accept: "application/json" }, signal: AbortSignal.timeout(1e4) });
|
|
240
|
+
let identity = null;
|
|
241
|
+
if (res.ok) identity = identityFrom(await res.json(), config.claims);
|
|
242
|
+
else if (res.status !== 401 && res.status !== 403) throw new Error(`A aplica\xE7\xE3o respondeu ${res.status} ao identificar o usu\xE1rio (${config.url}).`);
|
|
243
|
+
if (cache.size > 1e3) cache.clear();
|
|
244
|
+
cache.set(id, { at: Date.now(), identity });
|
|
245
|
+
return identity;
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// src/options.ts
|
|
250
|
+
import { boardTools, connectorTools, createModelRouter, createOrchestrator, createPod, knowledgeTool, memoryPrompt, processMemoryPrompt, processMemoryTools, rememberTool } from "@dolfinhos/core";
|
|
251
|
+
import { builtinConnectors, openApiTools } from "@dolfinhos/connectors";
|
|
252
|
+
import {
|
|
253
|
+
createPostgresAdapter,
|
|
254
|
+
createPostgresAuditStore,
|
|
255
|
+
createPostgresCatalogStore,
|
|
256
|
+
createPostgresCredentialStore,
|
|
257
|
+
createPostgresEventBus,
|
|
258
|
+
createPostgresFactStore,
|
|
259
|
+
createPostgresJobQueue,
|
|
260
|
+
createPostgresKnowledgeStore,
|
|
261
|
+
createPostgresMemoryItemStore,
|
|
262
|
+
createPostgresOperatorStore,
|
|
263
|
+
createPostgresReportStore,
|
|
264
|
+
createPostgresSettingsStore,
|
|
265
|
+
createPostgresTaskStore,
|
|
266
|
+
createPostgresUsageStore
|
|
267
|
+
} from "@dolfinhos/db-postgres";
|
|
268
|
+
import { anthropicProvider, deepseekProvider, openaiProvider } from "@dolfinhos/providers";
|
|
269
|
+
var ROLE = "assistente";
|
|
270
|
+
function apiBaseUrl(config, spec) {
|
|
271
|
+
if (config.app.baseUrl) return config.app.baseUrl;
|
|
272
|
+
const server = spec.servers?.[0]?.url;
|
|
273
|
+
if (typeof server === "string" && /^https?:\/\//.test(server)) return server;
|
|
274
|
+
return new URL(typeof server === "string" ? server : "/", config.app.openapiUrl).toString();
|
|
275
|
+
}
|
|
276
|
+
function standaloneOptions(config, deps) {
|
|
277
|
+
const { pool, spec } = deps;
|
|
278
|
+
const doFetch = deps.fetch ?? fetch;
|
|
279
|
+
const warn = deps.warn ?? ((m) => console.warn(`[dolfinhos] ${m}`));
|
|
280
|
+
const authenticate = createAuthenticator(config.auth, doFetch);
|
|
281
|
+
const settings = createPostgresSettingsStore({ client: pool });
|
|
282
|
+
const knowledge = createPostgresKnowledgeStore({ client: pool });
|
|
283
|
+
const facts = createPostgresFactStore({ client: pool });
|
|
284
|
+
const memoryItems = createPostgresMemoryItemStore({ client: pool });
|
|
285
|
+
const board = createPostgresTaskStore({ client: pool });
|
|
286
|
+
const operators = createPostgresOperatorStore({ client: pool });
|
|
287
|
+
const credentials = config.ai.secret ? createPostgresCredentialStore({ client: pool, encryptionKey: config.ai.secret }) : null;
|
|
288
|
+
const connectors = credentials ? builtinConnectors({ fetch: doFetch }) : [];
|
|
289
|
+
const providers = { deepseek: deepseekProvider(), anthropic: anthropicProvider(), openai: openaiProvider() };
|
|
290
|
+
const platform = config.ai.platform;
|
|
291
|
+
const models = createModelRouter({
|
|
292
|
+
providers,
|
|
293
|
+
roles: { [ROLE]: { label: "Assistente e operadores" } },
|
|
294
|
+
credentials,
|
|
295
|
+
settings,
|
|
296
|
+
...platform ? { platform: { provider: platform.provider, apiKey: platform.apiKey, models: { [ROLE]: platform.model } } } : {}
|
|
297
|
+
});
|
|
298
|
+
const app = openApiTools({
|
|
299
|
+
spec,
|
|
300
|
+
baseUrl: apiBaseUrl(config, spec),
|
|
301
|
+
fetch: doFetch,
|
|
302
|
+
// O que a pessoa mandou para o Dolfinhos vai para a aplicação: ela confere as permissões.
|
|
303
|
+
headers: (ctx) => ({ ...ctx.credentials }),
|
|
304
|
+
include: (op) => (!config.app.readOnly || op.method === "get") && (!config.app.includeTags.length || op.tags.some((t) => config.app.includeTags.includes(t)))
|
|
305
|
+
});
|
|
306
|
+
if (!app.length) warn("A especifica\xE7\xE3o OpenAPI n\xE3o gerou nenhuma a\xE7\xE3o (confira APP_INCLUDE_TAGS e APP_READ_ONLY).");
|
|
307
|
+
if (!config.app.serviceToken) warn("Sem APP_SERVICE_TOKEN: agenda, bots e tarefas de operadores n\xE3o conseguem chamar a aplica\xE7\xE3o.");
|
|
308
|
+
const subjects = ({ ctx }) => ctx.userId ? { eu: { type: "user", id: String(ctx.userId) } } : {};
|
|
309
|
+
const scopes = ({ ctx }) => ctx.userId ? { voce: { type: "user", id: String(ctx.userId) } } : {};
|
|
310
|
+
const model = ({ ctx }) => models.model(ctx.tenantId, ROLE);
|
|
311
|
+
return {
|
|
312
|
+
context: async (req) => {
|
|
313
|
+
const who = await authenticate(req.headers);
|
|
314
|
+
if (!who) return null;
|
|
315
|
+
return {
|
|
316
|
+
actor: { type: "user", id: who.userId, tenantId: who.tenantId, roles: who.roles },
|
|
317
|
+
tenantId: who.tenantId,
|
|
318
|
+
userId: who.userId
|
|
319
|
+
};
|
|
320
|
+
},
|
|
321
|
+
canManage: (ctx) => (ctx.actor?.roles ?? []).some((r) => config.adminRoles.includes(r)),
|
|
322
|
+
serviceContext: ({ tenantId, actor, channel }) => ({
|
|
323
|
+
actor: { ...actor, tenantId },
|
|
324
|
+
tenantId,
|
|
325
|
+
userId: null,
|
|
326
|
+
channel,
|
|
327
|
+
// A aplicação só deve aceitar o cabeçalho da empresa junto com o token de serviço.
|
|
328
|
+
credentials: config.app.serviceToken ? { authorization: `Bearer ${config.app.serviceToken}`, ...tenantId ? { [config.app.tenantHeader]: tenantId } : {} } : {}
|
|
329
|
+
}),
|
|
330
|
+
pod: () => createOrchestrator({
|
|
331
|
+
name: "Assistente",
|
|
332
|
+
capabilities: [
|
|
333
|
+
...app,
|
|
334
|
+
knowledgeTool({ store: knowledge, audience: "internal" }),
|
|
335
|
+
rememberTool({ store: facts, subjects }),
|
|
336
|
+
...processMemoryTools({ store: memoryItems, scopes }),
|
|
337
|
+
...boardTools({ store: board }),
|
|
338
|
+
...credentials ? connectorTools(connectors, credentials) : []
|
|
339
|
+
],
|
|
340
|
+
orchestratorCapabilities: [{ kinds: ["read"] }, { names: ["lembrar"] }],
|
|
341
|
+
model,
|
|
342
|
+
operators: { store: operators },
|
|
343
|
+
instructions: async ({ ctx, screen }) => `Voc\xEA ajuda o usu\xE1rio a usar ${config.app.description ?? spec.info?.title ?? "a aplica\xE7\xE3o"}. Use as ferramentas para consultar e agir; n\xE3o invente dados.` + await processMemoryPrompt({ store: memoryItems, ctx, screen, scopes }),
|
|
344
|
+
systemPrompt: ({ ctx, screen }) => memoryPrompt({ store: facts, ctx, screen, subjects })
|
|
345
|
+
}),
|
|
346
|
+
// Quem escreve de fora (WhatsApp, e-mail) fala com este bot, não com o assistente interno:
|
|
347
|
+
// ele só consulta o que a empresa marcou para clientes na base de conhecimento.
|
|
348
|
+
pods: () => ({
|
|
349
|
+
atendimento: createPod({
|
|
350
|
+
name: "Atendimento",
|
|
351
|
+
entryAgentId: "atendimento",
|
|
352
|
+
agents: [
|
|
353
|
+
{
|
|
354
|
+
id: "atendimento",
|
|
355
|
+
name: "Atendimento",
|
|
356
|
+
model,
|
|
357
|
+
tools: [knowledgeTool({ store: knowledge, audience: "all" })],
|
|
358
|
+
systemPrompt: `Voc\xEA atende clientes de ${config.app.description ?? spec.info?.title ?? "uma empresa"} por mensagem. Responda curto, com educa\xE7\xE3o, s\xF3 com o que estiver na base de conhecimento. Sem a resposta, diga que algu\xE9m da equipe vai retornar. Nunca invente prazos, pre\xE7os nem dados de pedidos.`
|
|
359
|
+
}
|
|
360
|
+
]
|
|
361
|
+
})
|
|
362
|
+
}),
|
|
363
|
+
inboundPod: "atendimento",
|
|
364
|
+
policies: [{ match: { capability: "lembrar" }, mode: "auto", description: "Guardar uma prefer\xEAncia n\xE3o precisa de aprova\xE7\xE3o." }],
|
|
365
|
+
// Não há rotas Nest para descobrir: as ações vêm do OpenAPI.
|
|
366
|
+
capabilitiesFile: false,
|
|
367
|
+
forwardHeaders: ["authorization", "cookie"],
|
|
368
|
+
memory: createPostgresAdapter({ client: pool, table: "dolfinhos.sessions" }),
|
|
369
|
+
settings,
|
|
370
|
+
audit: createPostgresAuditStore({ client: pool }),
|
|
371
|
+
usage: createPostgresUsageStore({ client: pool }),
|
|
372
|
+
knowledge,
|
|
373
|
+
facts,
|
|
374
|
+
memoryItems,
|
|
375
|
+
episodes: true,
|
|
376
|
+
queue: createPostgresJobQueue({ client: pool }),
|
|
377
|
+
...typeof pool.connect === "function" ? { bus: createPostgresEventBus({ client: pool }) } : {},
|
|
378
|
+
board,
|
|
379
|
+
operators,
|
|
380
|
+
reports: createPostgresReportStore({ client: pool }),
|
|
381
|
+
catalog: createPostgresCatalogStore({ client: pool }),
|
|
382
|
+
models,
|
|
383
|
+
...credentials ? { credentials: { store: credentials }, connectors } : {}
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// src/studio-page.ts
|
|
388
|
+
import { existsSync } from "fs";
|
|
389
|
+
import { fileURLToPath } from "url";
|
|
390
|
+
var STUDIO_ASSETS = [new URL("./web/", import.meta.url), new URL("../dist/web/", import.meta.url)].map((u) => fileURLToPath(u)).find((dir) => existsSync(`${dir}studio.js`)) ?? fileURLToPath(new URL("./web/", import.meta.url));
|
|
391
|
+
var studioBuilt = () => existsSync(`${STUDIO_ASSETS}studio.js`);
|
|
392
|
+
var STUDIO_HEADERS = {
|
|
393
|
+
"content-security-policy": [
|
|
394
|
+
"default-src 'none'",
|
|
395
|
+
"script-src 'self'",
|
|
396
|
+
"style-src 'self' 'unsafe-inline'",
|
|
397
|
+
"img-src 'self' data:",
|
|
398
|
+
"connect-src 'self'",
|
|
399
|
+
"base-uri 'none'",
|
|
400
|
+
"form-action 'none'",
|
|
401
|
+
"frame-ancestors 'none'"
|
|
402
|
+
].join("; "),
|
|
403
|
+
"referrer-policy": "no-referrer",
|
|
404
|
+
"x-content-type-options": "nosniff",
|
|
405
|
+
"cache-control": "no-store"
|
|
406
|
+
};
|
|
407
|
+
var escape = (text) => text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
|
408
|
+
function studioHtml({ appName, appUrl }) {
|
|
409
|
+
return `<!doctype html>
|
|
410
|
+
<html lang="pt-BR">
|
|
411
|
+
<head>
|
|
412
|
+
<meta charset="utf-8">
|
|
413
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
414
|
+
<meta name="robots" content="noindex">
|
|
415
|
+
<title>Administra\xE7\xE3o da IA \xB7 ${escape(appName)}</title>
|
|
416
|
+
<link rel="stylesheet" href="/studio/assets/studio.css">
|
|
417
|
+
</head>
|
|
418
|
+
<body>
|
|
419
|
+
<div id="root" data-app-name="${escape(appName)}"${appUrl ? ` data-app-url="${escape(appUrl)}"` : ""}></div>
|
|
420
|
+
<noscript>Ative o JavaScript para usar a administra\xE7\xE3o da IA.</noscript>
|
|
421
|
+
<script src="/studio/assets/studio.js" defer></script>
|
|
422
|
+
</body>
|
|
423
|
+
</html>
|
|
424
|
+
`;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
// src/server.ts
|
|
428
|
+
import "reflect-metadata";
|
|
429
|
+
import { Controller, Get, Module, Res } from "@nestjs/common";
|
|
430
|
+
import { NestFactory } from "@nestjs/core";
|
|
431
|
+
import { AiIgnore, DolfinhosModule } from "@dolfinhos/nestjs";
|
|
432
|
+
import pg from "pg";
|
|
433
|
+
var HealthController = class {
|
|
434
|
+
health() {
|
|
435
|
+
return { ok: true };
|
|
436
|
+
}
|
|
437
|
+
};
|
|
438
|
+
__decorateClass([
|
|
439
|
+
Get("health")
|
|
440
|
+
], HealthController.prototype, "health", 1);
|
|
441
|
+
HealthController = __decorateClass([
|
|
442
|
+
AiIgnore(),
|
|
443
|
+
Controller()
|
|
444
|
+
], HealthController);
|
|
445
|
+
async function loadSpec(config, doFetch = fetch) {
|
|
446
|
+
const headers = { accept: "application/json" };
|
|
447
|
+
if (config.app.serviceToken) headers.authorization = `Bearer ${config.app.serviceToken}`;
|
|
448
|
+
let res;
|
|
449
|
+
try {
|
|
450
|
+
res = await doFetch(config.app.openapiUrl, { headers, signal: AbortSignal.timeout(15e3) });
|
|
451
|
+
} catch (error) {
|
|
452
|
+
throw new Error(`N\xE3o consegui ler a especifica\xE7\xE3o em ${config.app.openapiUrl}: ${error.message}. A aplica\xE7\xE3o est\xE1 no ar?`);
|
|
453
|
+
}
|
|
454
|
+
if (!res.ok) throw new Error(`A especifica\xE7\xE3o em ${config.app.openapiUrl} respondeu ${res.status}.`);
|
|
455
|
+
const text = await res.text();
|
|
456
|
+
let spec;
|
|
457
|
+
try {
|
|
458
|
+
spec = JSON.parse(text);
|
|
459
|
+
} catch {
|
|
460
|
+
throw new Error(`A especifica\xE7\xE3o em ${config.app.openapiUrl} n\xE3o \xE9 JSON. Aponte APP_OPENAPI_URL para a vers\xE3o JSON (no Spring: /v3/api-docs).`);
|
|
461
|
+
}
|
|
462
|
+
if (typeof spec.openapi !== "string" || !spec.openapi.startsWith("3")) throw new Error("S\xF3 OpenAPI 3 \xE9 aceito (no Spring, o springdoc j\xE1 gera 3.x).");
|
|
463
|
+
return spec;
|
|
464
|
+
}
|
|
465
|
+
async function createStandaloneApp(config, spec, options) {
|
|
466
|
+
const studio = config.studio.enabled && studioBuilt();
|
|
467
|
+
if (config.studio.enabled && !studio) console.warn("[dolfinhos] A p\xE1gina do Studio n\xE3o foi constru\xEDda (dist/web): rode o build do pacote.");
|
|
468
|
+
const html = studioHtml({ appName: config.app.description ?? spec.info?.title ?? "a aplica\xE7\xE3o", appUrl: config.studio.appUrl });
|
|
469
|
+
let StudioController = class {
|
|
470
|
+
page(res) {
|
|
471
|
+
res.set(STUDIO_HEADERS).type("html").send(html);
|
|
472
|
+
}
|
|
473
|
+
};
|
|
474
|
+
__decorateClass([
|
|
475
|
+
Get("studio"),
|
|
476
|
+
__decorateParam(0, Res())
|
|
477
|
+
], StudioController.prototype, "page", 1);
|
|
478
|
+
StudioController = __decorateClass([
|
|
479
|
+
AiIgnore(),
|
|
480
|
+
Controller()
|
|
481
|
+
], StudioController);
|
|
482
|
+
let StandaloneModule = class {
|
|
483
|
+
};
|
|
484
|
+
StandaloneModule = __decorateClass([
|
|
485
|
+
Module({ imports: [DolfinhosModule.forRoot(options)], controllers: studio ? [HealthController, StudioController] : [HealthController] })
|
|
486
|
+
], StandaloneModule);
|
|
487
|
+
const app = await NestFactory.create(StandaloneModule, {
|
|
488
|
+
cors: config.corsOrigins.length ? { origin: config.corsOrigins, credentials: true } : false,
|
|
489
|
+
logger: ["error", "warn"],
|
|
490
|
+
// A Meta assina o corpo exato dos webhooks do WhatsApp.
|
|
491
|
+
rawBody: true
|
|
492
|
+
});
|
|
493
|
+
app.useBodyParser("json", { limit: "2mb" });
|
|
494
|
+
app.disable("x-powered-by");
|
|
495
|
+
if (studio) app.useStaticAssets(STUDIO_ASSETS, { prefix: "/studio/assets/", index: false, setHeaders: (res) => res.setHeader("x-content-type-options", "nosniff") });
|
|
496
|
+
return app;
|
|
497
|
+
}
|
|
498
|
+
async function startStandalone(config = readConfig()) {
|
|
499
|
+
const spec = await loadSpec(config);
|
|
500
|
+
const pool = new pg.Pool({ connectionString: config.databaseUrl, max: 10 });
|
|
501
|
+
try {
|
|
502
|
+
await pool.query("select 1");
|
|
503
|
+
} catch (error) {
|
|
504
|
+
await pool.end().catch(() => {
|
|
505
|
+
});
|
|
506
|
+
throw new Error(`N\xE3o consegui conectar ao Postgres (DATABASE_URL): ${error.message}`);
|
|
507
|
+
}
|
|
508
|
+
const options = {
|
|
509
|
+
...standaloneOptions(config, { pool, spec }),
|
|
510
|
+
onError: (error) => console.error("[dolfinhos]", error instanceof Error ? error.message : error)
|
|
511
|
+
};
|
|
512
|
+
const app = await createStandaloneApp(config, spec, options);
|
|
513
|
+
app.enableShutdownHooks();
|
|
514
|
+
await app.listen(config.port, "0.0.0.0");
|
|
515
|
+
const close = app.close.bind(app);
|
|
516
|
+
app.close = async () => {
|
|
517
|
+
await close();
|
|
518
|
+
await pool.end();
|
|
519
|
+
};
|
|
520
|
+
console.log(`[dolfinhos] no ar na porta ${config.port}, com ${Object.keys(spec.paths ?? {}).length} caminhos de ${spec.info?.title ?? "API"}.${config.studio.enabled ? " Studio em /studio." : ""}`);
|
|
521
|
+
return app;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
export {
|
|
525
|
+
readConfig,
|
|
526
|
+
identityFrom,
|
|
527
|
+
JwtError,
|
|
528
|
+
verifyJwt,
|
|
529
|
+
jwksKeys,
|
|
530
|
+
createAuthenticator,
|
|
531
|
+
apiBaseUrl,
|
|
532
|
+
standaloneOptions,
|
|
533
|
+
STUDIO_HEADERS,
|
|
534
|
+
studioHtml,
|
|
535
|
+
loadSpec,
|
|
536
|
+
createStandaloneApp,
|
|
537
|
+
startStandalone
|
|
538
|
+
};
|
|
539
|
+
//# sourceMappingURL=chunk-KXJJDYJM.js.map
|