@app-vitals/agent-admin 1.61.0 → 1.62.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/package.json +2 -2
- package/prisma/client/browser.ts +5 -0
- package/prisma/client/client.ts +5 -0
- package/prisma/client/internal/class.ts +14 -4
- package/prisma/client/internal/prismaNamespace.ts +94 -1
- package/prisma/client/internal/prismaNamespaceBrowser.ts +18 -0
- package/prisma/client/models/Account.ts +164 -0
- package/prisma/client/models/SlackConfigToken.ts +1574 -0
- package/prisma/client/models.ts +1 -0
- package/prisma/migrations/20261115000000_add_slack_config_token/migration.sql +34 -0
- package/prisma/schema/schema.prisma +33 -1
- package/src/slack-config-token.integration.test.ts +208 -0
- package/src/slack-config-token.ts +181 -0
package/prisma/client/models.ts
CHANGED
|
@@ -23,6 +23,7 @@ export type * from './models/AgentMember.ts'
|
|
|
23
23
|
export type * from './models/Account.ts'
|
|
24
24
|
export type * from './models/AgentTemplate.ts'
|
|
25
25
|
export type * from './models/AgentTemplateItem.ts'
|
|
26
|
+
export type * from './models/SlackConfigToken.ts'
|
|
26
27
|
export type * from './models/AccountMember.ts'
|
|
27
28
|
export type * from './models/AccountInvite.ts'
|
|
28
29
|
export type * from './models/AgentCronRun.ts'
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
-- SlackConfigToken: Slack app-configuration token per scope (account or
|
|
2
|
+
-- deployment-wide default). Additive only: one new table.
|
|
3
|
+
-- CreateTable
|
|
4
|
+
CREATE TABLE "SlackConfigToken" (
|
|
5
|
+
"id" TEXT NOT NULL,
|
|
6
|
+
"accountId" TEXT,
|
|
7
|
+
"refreshTokenEncrypted" TEXT NOT NULL,
|
|
8
|
+
"accessTokenEncrypted" TEXT,
|
|
9
|
+
"accessTokenExpiresAt" TIMESTAMP(3),
|
|
10
|
+
"slackTeamId" TEXT,
|
|
11
|
+
"slackUserId" TEXT,
|
|
12
|
+
"lastRotatedAt" TIMESTAMP(3),
|
|
13
|
+
"lastError" TEXT,
|
|
14
|
+
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
15
|
+
"updatedAt" TIMESTAMP(3) NOT NULL,
|
|
16
|
+
|
|
17
|
+
CONSTRAINT "SlackConfigToken_pkey" PRIMARY KEY ("id")
|
|
18
|
+
);
|
|
19
|
+
|
|
20
|
+
-- CreateIndex
|
|
21
|
+
CREATE INDEX "SlackConfigToken_accountId_idx" ON "SlackConfigToken"("accountId");
|
|
22
|
+
|
|
23
|
+
-- AddForeignKey
|
|
24
|
+
ALTER TABLE "SlackConfigToken" ADD CONSTRAINT "SlackConfigToken_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES "Account"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
|
25
|
+
|
|
26
|
+
-- Partial unique indexes (not expressible in Prisma; see the SlackConfigToken
|
|
27
|
+
-- comment in schema.prisma). Together they allow at most one row per scope with
|
|
28
|
+
-- NULL treated as a value, which a plain UNIQUE index would not do since NULLs
|
|
29
|
+
-- compare distinct.
|
|
30
|
+
-- CreateIndex
|
|
31
|
+
CREATE UNIQUE INDEX "SlackConfigToken_accountId_key" ON "SlackConfigToken"("accountId") WHERE "accountId" IS NOT NULL;
|
|
32
|
+
|
|
33
|
+
-- CreateIndex
|
|
34
|
+
CREATE UNIQUE INDEX "SlackConfigToken_global_key" ON "SlackConfigToken"((1)) WHERE "accountId" IS NULL;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Shipwright — Admin Service Schema
|
|
2
2
|
// Owns: Agent, AgentEnv, AgentCronJob, AgentTool, AgentToken, AgentPlugin,
|
|
3
|
-
// AgentMarketplace, AgentTemplate, AgentTemplateItem,
|
|
3
|
+
// AgentMarketplace, AgentTemplate, AgentTemplateItem, SlackConfigToken,
|
|
4
4
|
// plus the coding-owned models in coding.prisma (AgentWorkQueueSnapshot,
|
|
5
5
|
// AgentPhaseMethodology, SessionFollow, SessionAlertState).
|
|
6
6
|
// Agent is a first-class model (standalone, not embedded in a User model).
|
|
@@ -293,6 +293,7 @@ model Account {
|
|
|
293
293
|
invites AccountInvite[]
|
|
294
294
|
templates AgentTemplate[]
|
|
295
295
|
githubEnterpriseApps GitHubEnterpriseApp[]
|
|
296
|
+
slackConfigTokens SlackConfigToken[]
|
|
296
297
|
}
|
|
297
298
|
|
|
298
299
|
// ─── Agent Templates ──────────────────────────────────────────────────────────
|
|
@@ -343,6 +344,37 @@ model AgentTemplateItem {
|
|
|
343
344
|
@@unique([templateId, kind, key])
|
|
344
345
|
}
|
|
345
346
|
|
|
347
|
+
// ─── Slack Config Token ───────────────────────────────────────────────────────
|
|
348
|
+
// Slack app-configuration token pair (refresh + short-lived access token) used
|
|
349
|
+
// to manage Slack apps. accountId null = deployment-wide default; an account
|
|
350
|
+
// row overrides the default for that account. Tokens are AES-256-GCM encrypted
|
|
351
|
+
// at the service layer (admin/src/slack-config-token.ts) and never read back.
|
|
352
|
+
//
|
|
353
|
+
// UNIQUENESS: at most one row per scope, with NULL treated as a value. Prisma
|
|
354
|
+
// cannot express partial unique indexes, so they are hand-written in
|
|
355
|
+
// 20261115000000_add_slack_config_token/migration.sql:
|
|
356
|
+
// SlackConfigToken_accountId_key (accountId set)
|
|
357
|
+
// SlackConfigToken_global_key (accountId NULL)
|
|
358
|
+
// Prisma's schema diff does not see them, so keep them when editing this
|
|
359
|
+
// model and re-create them by hand if the table is ever rebuilt.
|
|
360
|
+
|
|
361
|
+
model SlackConfigToken {
|
|
362
|
+
id String @id @default(cuid())
|
|
363
|
+
accountId String?
|
|
364
|
+
account Account? @relation(fields: [accountId], references: [id], onDelete: Cascade)
|
|
365
|
+
refreshTokenEncrypted String
|
|
366
|
+
accessTokenEncrypted String?
|
|
367
|
+
accessTokenExpiresAt DateTime?
|
|
368
|
+
slackTeamId String?
|
|
369
|
+
slackUserId String?
|
|
370
|
+
lastRotatedAt DateTime?
|
|
371
|
+
lastError String?
|
|
372
|
+
createdAt DateTime @default(now())
|
|
373
|
+
updatedAt DateTime @updatedAt
|
|
374
|
+
|
|
375
|
+
@@index([accountId])
|
|
376
|
+
}
|
|
377
|
+
|
|
346
378
|
model AccountMember {
|
|
347
379
|
id String @id @default(cuid())
|
|
348
380
|
accountId String
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Integration tests for SlackConfigTokenService against a real PostgreSQL DB.
|
|
3
|
+
*
|
|
4
|
+
* Requires DATABASE_URL_ADMIN_TEST to be set; skips otherwise.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { afterEach, beforeEach, describe, expect, it } from "bun:test";
|
|
8
|
+
import type { PrismaClient } from "../prisma/client/client.ts";
|
|
9
|
+
import { createAdminPrismaClient } from "./prisma-client.ts";
|
|
10
|
+
import {
|
|
11
|
+
SlackConfigTokenEncryptionUnavailableError,
|
|
12
|
+
SlackConfigTokenService,
|
|
13
|
+
toSlackConfigTokenMetadata,
|
|
14
|
+
} from "./slack-config-token.ts";
|
|
15
|
+
import { makeStrictTokenCrypto } from "./token-crypto.ts";
|
|
16
|
+
|
|
17
|
+
const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
|
|
18
|
+
const describeOrSkip = TEST_DB ? describe : describe.skip;
|
|
19
|
+
|
|
20
|
+
const KEY = "a".repeat(64);
|
|
21
|
+
const REFRESH = "test-refresh-SUPERSECRET";
|
|
22
|
+
const ACCESS = "test-access-SUPERSECRET";
|
|
23
|
+
|
|
24
|
+
describeOrSkip("SlackConfigTokenService (integration)", () => {
|
|
25
|
+
let prisma: PrismaClient;
|
|
26
|
+
let service: SlackConfigTokenService;
|
|
27
|
+
let acctA: string;
|
|
28
|
+
let acctB: string;
|
|
29
|
+
|
|
30
|
+
beforeEach(async () => {
|
|
31
|
+
prisma = createAdminPrismaClient(TEST_DB as string);
|
|
32
|
+
await prisma.slackConfigToken.deleteMany();
|
|
33
|
+
await prisma.agentTemplateItem.deleteMany();
|
|
34
|
+
await prisma.agentTemplate.deleteMany();
|
|
35
|
+
await prisma.agent.deleteMany();
|
|
36
|
+
await prisma.accountInvite.deleteMany();
|
|
37
|
+
await prisma.accountMember.deleteMany();
|
|
38
|
+
await prisma.account.deleteMany();
|
|
39
|
+
acctA = (await prisma.account.create({ data: { name: "A" } })).id;
|
|
40
|
+
acctB = (await prisma.account.create({ data: { name: "B" } })).id;
|
|
41
|
+
service = new SlackConfigTokenService(prisma, makeStrictTokenCrypto(KEY));
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
afterEach(async () => {
|
|
45
|
+
await prisma.$disconnect();
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it("returns null / empty when nothing is saved", async () => {
|
|
49
|
+
expect(await service.get(null)).toBeNull();
|
|
50
|
+
expect(await service.get(acctA)).toBeNull();
|
|
51
|
+
expect(await service.resolveForAccount(acctA)).toBeNull();
|
|
52
|
+
expect(await service.list()).toEqual([]);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it("saves, gets and clears per scope; metadata only", async () => {
|
|
56
|
+
const exp = new Date("2030-01-01T00:00:00Z");
|
|
57
|
+
const saved = await service.save(acctA, {
|
|
58
|
+
refreshToken: REFRESH,
|
|
59
|
+
accessToken: ACCESS,
|
|
60
|
+
accessTokenExpiresAt: exp,
|
|
61
|
+
slackTeamId: "T1",
|
|
62
|
+
slackUserId: "U1",
|
|
63
|
+
});
|
|
64
|
+
expect(saved).toMatchObject({
|
|
65
|
+
accountId: acctA,
|
|
66
|
+
refreshTokenSet: true,
|
|
67
|
+
accessTokenSet: true,
|
|
68
|
+
slackTeamId: "T1",
|
|
69
|
+
slackUserId: "U1",
|
|
70
|
+
});
|
|
71
|
+
expect(saved.accessTokenExpiresAt).toEqual(exp);
|
|
72
|
+
expect(saved.lastRotatedAt).not.toBeNull();
|
|
73
|
+
const got = await service.get(acctA);
|
|
74
|
+
expect(got?.id).toBe(saved.id);
|
|
75
|
+
for (const out of [saved, got, await service.list()]) {
|
|
76
|
+
const json = JSON.stringify(out);
|
|
77
|
+
expect(json).not.toContain("SUPERSECRET");
|
|
78
|
+
expect(json).not.toContain("Encrypted");
|
|
79
|
+
}
|
|
80
|
+
// stored encrypted, not plain
|
|
81
|
+
const raw = await prisma.slackConfigToken.findFirstOrThrow({
|
|
82
|
+
where: { accountId: acctA },
|
|
83
|
+
});
|
|
84
|
+
expect(raw.refreshTokenEncrypted).not.toContain("SUPERSECRET");
|
|
85
|
+
expect(raw.accessTokenEncrypted).not.toContain("SUPERSECRET");
|
|
86
|
+
|
|
87
|
+
await service.clear(acctA);
|
|
88
|
+
expect(await service.get(acctA)).toBeNull();
|
|
89
|
+
await service.clear(acctA); // no-op
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it("allows a token with no access token", async () => {
|
|
93
|
+
const saved = await service.save(null, { refreshToken: REFRESH });
|
|
94
|
+
expect(saved.accessTokenSet).toBe(false);
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it("upserts one row per scope, including two NULL-scope saves", async () => {
|
|
98
|
+
const first = await service.save(null, { refreshToken: REFRESH });
|
|
99
|
+
const second = await service.save(null, {
|
|
100
|
+
refreshToken: "test-refresh-OTHER",
|
|
101
|
+
slackTeamId: "T2",
|
|
102
|
+
});
|
|
103
|
+
expect(second.id).toBe(first.id);
|
|
104
|
+
expect(second.slackTeamId).toBe("T2");
|
|
105
|
+
expect(
|
|
106
|
+
await prisma.slackConfigToken.count({ where: { accountId: null } }),
|
|
107
|
+
).toBe(1);
|
|
108
|
+
|
|
109
|
+
const a1 = await service.save(acctA, { refreshToken: REFRESH });
|
|
110
|
+
const a2 = await service.save(acctA, { refreshToken: REFRESH });
|
|
111
|
+
expect(a2.id).toBe(a1.id);
|
|
112
|
+
await service.save(acctB, { refreshToken: REFRESH });
|
|
113
|
+
expect(await prisma.slackConfigToken.count()).toBe(3);
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
it("enforces both partial unique indexes at the database", async () => {
|
|
117
|
+
const base = { refreshTokenEncrypted: "x" };
|
|
118
|
+
await prisma.slackConfigToken.create({
|
|
119
|
+
data: { ...base, accountId: null },
|
|
120
|
+
});
|
|
121
|
+
await expect(
|
|
122
|
+
(async () =>
|
|
123
|
+
prisma.slackConfigToken.create({
|
|
124
|
+
data: { ...base, accountId: null },
|
|
125
|
+
}))(),
|
|
126
|
+
).rejects.toThrow();
|
|
127
|
+
await prisma.slackConfigToken.create({
|
|
128
|
+
data: { ...base, accountId: acctA },
|
|
129
|
+
});
|
|
130
|
+
await expect(
|
|
131
|
+
(async () =>
|
|
132
|
+
prisma.slackConfigToken.create({
|
|
133
|
+
data: { ...base, accountId: acctA },
|
|
134
|
+
}))(),
|
|
135
|
+
).rejects.toThrow();
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
it("resolveForAccount prefers the account row, then default, then null", async () => {
|
|
139
|
+
expect(await service.resolveForAccount(acctA)).toBeNull();
|
|
140
|
+
const def = await service.save(null, { refreshToken: REFRESH });
|
|
141
|
+
expect((await service.resolveForAccount(acctA))?.id).toBe(def.id);
|
|
142
|
+
const own = await service.save(acctA, { refreshToken: REFRESH });
|
|
143
|
+
expect((await service.resolveForAccount(acctA))?.id).toBe(own.id);
|
|
144
|
+
expect((await service.resolveForAccount(acctB))?.id).toBe(def.id);
|
|
145
|
+
await service.clear(null);
|
|
146
|
+
await service.clear(acctA);
|
|
147
|
+
expect(await service.resolveForAccount(acctA)).toBeNull();
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
it("clears only the targeted scope", async () => {
|
|
151
|
+
await service.save(null, { refreshToken: REFRESH });
|
|
152
|
+
await service.save(acctA, { refreshToken: REFRESH });
|
|
153
|
+
await service.clear(acctA);
|
|
154
|
+
expect(await service.get(null)).not.toBeNull();
|
|
155
|
+
expect(await service.get(acctA)).toBeNull();
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
it("deleting an account cascades its token", async () => {
|
|
159
|
+
await service.save(acctA, { refreshToken: REFRESH });
|
|
160
|
+
await prisma.account.delete({ where: { id: acctA } });
|
|
161
|
+
expect(await prisma.slackConfigToken.count()).toBe(0);
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
it("refuses to save without an encryption key", async () => {
|
|
165
|
+
const noKey = new SlackConfigTokenService(prisma, null);
|
|
166
|
+
await expect(
|
|
167
|
+
noKey.save(null, { refreshToken: REFRESH }),
|
|
168
|
+
).rejects.toBeInstanceOf(SlackConfigTokenEncryptionUnavailableError);
|
|
169
|
+
expect(await prisma.slackConfigToken.count()).toBe(0);
|
|
170
|
+
});
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
describe("toSlackConfigTokenMetadata", () => {
|
|
174
|
+
it("never includes secret fields", () => {
|
|
175
|
+
const now = new Date();
|
|
176
|
+
const out = toSlackConfigTokenMetadata({
|
|
177
|
+
id: "i",
|
|
178
|
+
accountId: null,
|
|
179
|
+
refreshTokenEncrypted: "SECRETREFRESHCIPHER",
|
|
180
|
+
accessTokenEncrypted: "SECRETACCESSCIPHER",
|
|
181
|
+
accessTokenExpiresAt: now,
|
|
182
|
+
slackTeamId: "T",
|
|
183
|
+
slackUserId: "U",
|
|
184
|
+
lastRotatedAt: now,
|
|
185
|
+
lastError: null,
|
|
186
|
+
createdAt: now,
|
|
187
|
+
updatedAt: now,
|
|
188
|
+
});
|
|
189
|
+
expect(Object.keys(out).sort()).toEqual(
|
|
190
|
+
[
|
|
191
|
+
"id",
|
|
192
|
+
"accountId",
|
|
193
|
+
"refreshTokenSet",
|
|
194
|
+
"accessTokenSet",
|
|
195
|
+
"accessTokenExpiresAt",
|
|
196
|
+
"slackTeamId",
|
|
197
|
+
"slackUserId",
|
|
198
|
+
"lastRotatedAt",
|
|
199
|
+
"lastError",
|
|
200
|
+
"createdAt",
|
|
201
|
+
"updatedAt",
|
|
202
|
+
].sort(),
|
|
203
|
+
);
|
|
204
|
+
expect(JSON.stringify(out)).not.toContain("SECRET");
|
|
205
|
+
expect(out.refreshTokenSet).toBe(true);
|
|
206
|
+
expect(out.accessTokenSet).toBe(true);
|
|
207
|
+
});
|
|
208
|
+
});
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* admin/src/slack-config-token.ts
|
|
3
|
+
* SlackConfigTokenService — storage for the Slack app-configuration token
|
|
4
|
+
* (refresh token plus short-lived access token), scoped like AgentTemplate:
|
|
5
|
+
* accountId null = deployment-wide default, an account row overrides it.
|
|
6
|
+
*
|
|
7
|
+
* Tokens are encrypted on write (AES-256-GCM via a strict TokenCrypto) and are
|
|
8
|
+
* never returned by any read path: reads return metadata plus `*Set` flags.
|
|
9
|
+
* save() refuses when no encryption key is configured (no plain-text fallback).
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import type { PrismaClient } from "../prisma/client/client.ts";
|
|
13
|
+
import { type Clock, SystemClock } from "./clock.ts";
|
|
14
|
+
import { UnprocessableEntityError } from "./errors.ts";
|
|
15
|
+
import type { TokenCrypto } from "./token-crypto.ts";
|
|
16
|
+
|
|
17
|
+
export interface SlackConfigTokenMetadata {
|
|
18
|
+
id: string;
|
|
19
|
+
/** null = deployment-wide default. */
|
|
20
|
+
accountId: string | null;
|
|
21
|
+
refreshTokenSet: boolean;
|
|
22
|
+
accessTokenSet: boolean;
|
|
23
|
+
accessTokenExpiresAt: Date | null;
|
|
24
|
+
slackTeamId: string | null;
|
|
25
|
+
slackUserId: string | null;
|
|
26
|
+
lastRotatedAt: Date | null;
|
|
27
|
+
lastError: string | null;
|
|
28
|
+
createdAt: Date;
|
|
29
|
+
updatedAt: Date;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface SaveSlackConfigTokenInput {
|
|
33
|
+
/** Encrypted before it is stored. */
|
|
34
|
+
refreshToken: string;
|
|
35
|
+
/** Encrypted before it is stored. */
|
|
36
|
+
accessToken?: string | null;
|
|
37
|
+
accessTokenExpiresAt?: Date | null;
|
|
38
|
+
slackTeamId?: string | null;
|
|
39
|
+
slackUserId?: string | null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
interface SlackConfigTokenRow {
|
|
43
|
+
id: string;
|
|
44
|
+
accountId: string | null;
|
|
45
|
+
refreshTokenEncrypted: string;
|
|
46
|
+
accessTokenEncrypted: string | null;
|
|
47
|
+
accessTokenExpiresAt: Date | null;
|
|
48
|
+
slackTeamId: string | null;
|
|
49
|
+
slackUserId: string | null;
|
|
50
|
+
lastRotatedAt: Date | null;
|
|
51
|
+
lastError: string | null;
|
|
52
|
+
createdAt: Date;
|
|
53
|
+
updatedAt: Date;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export class SlackConfigTokenEncryptionUnavailableError extends UnprocessableEntityError {
|
|
57
|
+
constructor() {
|
|
58
|
+
super(
|
|
59
|
+
"SHIPWRIGHT_ENCRYPTION_KEY is not configured; refusing to store a Slack config token unencrypted. Set it to a 64-character hex string (openssl rand -hex 32) and retry.",
|
|
60
|
+
);
|
|
61
|
+
this.name = "SlackConfigTokenEncryptionUnavailableError";
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Serializer: metadata plus set flags. Never includes token material. */
|
|
66
|
+
export function toSlackConfigTokenMetadata(
|
|
67
|
+
row: SlackConfigTokenRow,
|
|
68
|
+
): SlackConfigTokenMetadata {
|
|
69
|
+
return {
|
|
70
|
+
id: row.id,
|
|
71
|
+
accountId: row.accountId,
|
|
72
|
+
refreshTokenSet: row.refreshTokenEncrypted.length > 0,
|
|
73
|
+
accessTokenSet: !!row.accessTokenEncrypted,
|
|
74
|
+
accessTokenExpiresAt: row.accessTokenExpiresAt,
|
|
75
|
+
slackTeamId: row.slackTeamId,
|
|
76
|
+
slackUserId: row.slackUserId,
|
|
77
|
+
lastRotatedAt: row.lastRotatedAt,
|
|
78
|
+
lastError: row.lastError,
|
|
79
|
+
createdAt: row.createdAt,
|
|
80
|
+
updatedAt: row.updatedAt,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function isUniqueViolation(err: unknown): boolean {
|
|
85
|
+
return (
|
|
86
|
+
typeof err === "object" &&
|
|
87
|
+
err !== null &&
|
|
88
|
+
(err as { code?: unknown }).code === "P2002"
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export class SlackConfigTokenService {
|
|
93
|
+
constructor(
|
|
94
|
+
private prisma: PrismaClient,
|
|
95
|
+
/** Strict crypto (see makeStrictTokenCrypto); null when no encryption key is configured. */
|
|
96
|
+
private crypto: TokenCrypto | null,
|
|
97
|
+
private clock: Clock = SystemClock(),
|
|
98
|
+
) {}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Create or replace the token for a scope (accountId null = deployment-wide
|
|
102
|
+
* default). Resets lastError; stamps lastRotatedAt.
|
|
103
|
+
*/
|
|
104
|
+
async save(
|
|
105
|
+
accountId: string | null,
|
|
106
|
+
input: SaveSlackConfigTokenInput,
|
|
107
|
+
): Promise<SlackConfigTokenMetadata> {
|
|
108
|
+
if (!this.crypto) throw new SlackConfigTokenEncryptionUnavailableError();
|
|
109
|
+
if (!input.refreshToken) {
|
|
110
|
+
throw new UnprocessableEntityError("refreshToken is required");
|
|
111
|
+
}
|
|
112
|
+
const now = this.clock.now();
|
|
113
|
+
const data = {
|
|
114
|
+
refreshTokenEncrypted: this.crypto.encrypt(input.refreshToken),
|
|
115
|
+
accessTokenEncrypted: input.accessToken
|
|
116
|
+
? this.crypto.encrypt(input.accessToken)
|
|
117
|
+
: null,
|
|
118
|
+
accessTokenExpiresAt: input.accessTokenExpiresAt ?? null,
|
|
119
|
+
slackTeamId: input.slackTeamId ?? null,
|
|
120
|
+
slackUserId: input.slackUserId ?? null,
|
|
121
|
+
lastRotatedAt: now,
|
|
122
|
+
lastError: null,
|
|
123
|
+
updatedAt: now,
|
|
124
|
+
};
|
|
125
|
+
// Prisma has no upsert for a nullable-scoped partial unique index, so
|
|
126
|
+
// update-then-create; a concurrent create loses on the index and retries
|
|
127
|
+
// as an update.
|
|
128
|
+
const update = async () => {
|
|
129
|
+
const existing = await this.prisma.slackConfigToken.findFirst({
|
|
130
|
+
where: { accountId },
|
|
131
|
+
});
|
|
132
|
+
if (!existing) return null;
|
|
133
|
+
return this.prisma.slackConfigToken.update({
|
|
134
|
+
where: { id: existing.id },
|
|
135
|
+
data,
|
|
136
|
+
});
|
|
137
|
+
};
|
|
138
|
+
let row = await update();
|
|
139
|
+
if (!row) {
|
|
140
|
+
try {
|
|
141
|
+
row = await this.prisma.slackConfigToken.create({
|
|
142
|
+
data: { accountId, ...data },
|
|
143
|
+
});
|
|
144
|
+
} catch (err) {
|
|
145
|
+
if (!isUniqueViolation(err)) throw err;
|
|
146
|
+
row = await update();
|
|
147
|
+
if (!row) throw err;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return toSlackConfigTokenMetadata(row);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Metadata for exactly this scope (no fallback), or null. */
|
|
154
|
+
async get(
|
|
155
|
+
accountId: string | null,
|
|
156
|
+
): Promise<SlackConfigTokenMetadata | null> {
|
|
157
|
+
const row = await this.prisma.slackConfigToken.findFirst({
|
|
158
|
+
where: { accountId },
|
|
159
|
+
});
|
|
160
|
+
return row ? toSlackConfigTokenMetadata(row) : null;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Account row, else the deployment-wide default row, else null. */
|
|
164
|
+
async resolveForAccount(
|
|
165
|
+
accountId: string,
|
|
166
|
+
): Promise<SlackConfigTokenMetadata | null> {
|
|
167
|
+
return (await this.get(accountId)) ?? (await this.get(null));
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
async list(): Promise<SlackConfigTokenMetadata[]> {
|
|
171
|
+
const rows = await this.prisma.slackConfigToken.findMany({
|
|
172
|
+
orderBy: { createdAt: "asc" },
|
|
173
|
+
});
|
|
174
|
+
return rows.map(toSlackConfigTokenMetadata);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Delete the token for a scope. No-ops if absent. */
|
|
178
|
+
async clear(accountId: string | null): Promise<void> {
|
|
179
|
+
await this.prisma.slackConfigToken.deleteMany({ where: { accountId } });
|
|
180
|
+
}
|
|
181
|
+
}
|