@flytedesk/app-kit 11.3.0 → 11.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.
Files changed (72) hide show
  1. package/README.md +128 -0
  2. package/dist/auth/guards.d.ts +4 -0
  3. package/dist/auth/guards.js +22 -0
  4. package/dist/auth/guards.js.map +1 -1
  5. package/dist/auth/index.d.ts +1 -1
  6. package/dist/auth/index.js +1 -1
  7. package/dist/auth/index.js.map +1 -1
  8. package/dist/auth/prisma/index.d.ts +1 -0
  9. package/dist/auth/prisma/index.js +2 -0
  10. package/dist/auth/prisma/index.js.map +1 -0
  11. package/dist/auth/prisma/prismaAuthStore.d.ts +181 -0
  12. package/dist/auth/prisma/prismaAuthStore.js +273 -0
  13. package/dist/auth/prisma/prismaAuthStore.js.map +1 -0
  14. package/dist/chat/tools/index.d.ts +38 -0
  15. package/dist/chat/tools/index.js +60 -0
  16. package/dist/chat/tools/index.js.map +1 -0
  17. package/dist/cli/auth-sync.d.ts +2 -0
  18. package/dist/cli/auth-sync.js +23 -0
  19. package/dist/cli/auth-sync.js.map +1 -0
  20. package/dist/flytebot/client.d.ts +66 -0
  21. package/dist/flytebot/client.js +377 -0
  22. package/dist/flytebot/client.js.map +1 -0
  23. package/dist/flytebot/env.d.ts +11 -0
  24. package/dist/flytebot/env.js +25 -0
  25. package/dist/flytebot/env.js.map +1 -0
  26. package/dist/flytebot/error.d.ts +36 -0
  27. package/dist/flytebot/error.js +60 -0
  28. package/dist/flytebot/error.js.map +1 -0
  29. package/dist/flytebot/index.d.ts +32 -0
  30. package/dist/flytebot/index.js +28 -0
  31. package/dist/flytebot/index.js.map +1 -0
  32. package/dist/flytebot/sse.d.ts +11 -0
  33. package/dist/flytebot/sse.js +55 -0
  34. package/dist/flytebot/sse.js.map +1 -0
  35. package/dist/flytebot/testing/fake.d.ts +77 -0
  36. package/dist/flytebot/testing/fake.js +399 -0
  37. package/dist/flytebot/testing/fake.js.map +1 -0
  38. package/dist/flytebot/testing/index.d.ts +18 -0
  39. package/dist/flytebot/testing/index.js +18 -0
  40. package/dist/flytebot/testing/index.js.map +1 -0
  41. package/dist/flytebot/webhook.d.ts +24 -0
  42. package/dist/flytebot/webhook.js +63 -0
  43. package/dist/flytebot/webhook.js.map +1 -0
  44. package/dist/repo-check/checkNarration.d.ts +13 -0
  45. package/dist/repo-check/checkNarration.js +346 -0
  46. package/dist/repo-check/checkNarration.js.map +1 -0
  47. package/dist/repo-check/checkNoNul.d.ts +3 -0
  48. package/dist/repo-check/checkNoNul.js +35 -0
  49. package/dist/repo-check/checkNoNul.js.map +1 -0
  50. package/dist/repo-check/cli.d.ts +9 -0
  51. package/dist/repo-check/cli.js +103 -0
  52. package/dist/repo-check/cli.js.map +1 -0
  53. package/dist/repo-check/config.d.ts +13 -0
  54. package/dist/repo-check/config.js +39 -0
  55. package/dist/repo-check/config.js.map +1 -0
  56. package/dist/repo-check/repoFiles.d.ts +8 -0
  57. package/dist/repo-check/repoFiles.js +44 -0
  58. package/dist/repo-check/repoFiles.js.map +1 -0
  59. package/dist/repo-check/repoHygiene.d.ts +5 -0
  60. package/dist/repo-check/repoHygiene.js +12 -0
  61. package/dist/repo-check/repoHygiene.js.map +1 -0
  62. package/dist/repo-check/scriptComments.d.ts +28 -0
  63. package/dist/repo-check/scriptComments.js +243 -0
  64. package/dist/repo-check/scriptComments.js.map +1 -0
  65. package/dist/spa-server/index.d.ts +25 -0
  66. package/dist/spa-server/index.js +35 -2
  67. package/dist/spa-server/index.js.map +1 -1
  68. package/package.json +26 -3
  69. package/prisma/fragments/auth.meta.json +4 -0
  70. package/prisma/fragments/auth.prisma +75 -0
  71. package/prisma/migrations/0004_app_kit_auth_init/migration.sql +47 -0
  72. package/prisma/migrations/manifest.json +7 -0
package/README.md CHANGED
@@ -97,6 +97,23 @@ await api.register(flytedeskAuth, {
97
97
  });
98
98
  ```
99
99
 
100
+ **Three pieces an app uses from app-kit and never writes itself** (each used to be copied
101
+ from app to app):
102
+
103
+ - **The `AuthStore`**: `PrismaAuthStore` from `@flytedesk/app-kit/auth/prisma`. It holds
104
+ the refresh-token rotation, family revocation (with the reuse-detection audit row) and
105
+ the session lock. It takes the app's own generated Prisma client (typed structurally,
106
+ so no generated client is imported). Install its models with `npx auth-sync init`
107
+ (`prisma/fragments/auth.prisma`: `IdpSession`, `RefreshToken`, `AuthAuditLog`), then
108
+ `new PrismaAuthStore(prisma)` is the `store` above.
109
+ - **The any-of-these-permissions guard**: `requireAnyPermission("chat", "admin")` from
110
+ `@flytedesk/app-kit/auth`, beside `requirePermission` (which wants all keys). It
111
+ refuses with the same 401/503/403 bodies.
112
+ - **The SPA cache policy**: hashed assets `public, max-age=31536000, immutable`,
113
+ `index.html` and every SPA-fallback route `no-cache`. `createSpaServer` and the
114
+ `spa-server` bin apply it; a Fastify app that serves its own SPA registers
115
+ `spaCachePolicy` from `@flytedesk/app-kit/spa-server` inside a scope that holds only its SPA routes (or calls `spaCacheControl(pathname)`).
116
+
100
117
  Its `AuthStore` persists `IdpSessionRow.idToken`, which is sent back to flytedesk ID as the
101
118
  logout's `id_token_hint`. That is what lets flytedesk ID end its session without a
102
119
  confirmation step for a real sign-out, while still asking on a forged one.
@@ -601,6 +618,109 @@ The job's MCP tools module (`app-kit-chat-mcp --tools <path>`) need not register
601
618
  tool: a module that builds `kit.createChatMcpProtocol({ serverName, tools })` with only
602
619
  its own tools is served as it is.
603
620
 
621
+ ## Flytebot (`@flytedesk/app-kit/flytebot`)
622
+
623
+ Flytebot is the service that runs flytedesk's agents and structured LLM calls. An app
624
+ reaches it with a Google ID token of its Cloud Run service account (audience: Flytebot's
625
+ origin); no shared secret exists. Wire types come from `@flytedesk/flytebot-contracts`.
626
+
627
+ ```ts
628
+ import { createFlytebotClient, parseFlytebotEnv, verifyTerminalWebhook } from "@flytedesk/app-kit/flytebot";
629
+
630
+ const env = parseFlytebotEnv(process.env); // FLYTEBOT_URL, FLYTEBOT_SERVICE_ACCOUNT
631
+ const flytebot = createFlytebotClient({
632
+ baseUrl: env.flytebotUrl,
633
+ timeoutMs: 15_000,
634
+ retries: 3, // network failures, timeouts, 5xx and 429, with the SAME idempotency key
635
+ // idToken: (audience) => ..., // default: google-auth-library; inject one in tests
636
+ });
637
+
638
+ // one structured answer (an `llm` profile), validated against your zod schema
639
+ const { output, usage, costUsd } = await flytebot.llm.generate(
640
+ { profile: "goal-judgment", messages, actor },
641
+ outputZodSchema,
642
+ );
643
+
644
+ // an agent run; the key is your own row id, so a retried launch never starts a second run
645
+ const { run } = await flytebot.runs.create({
646
+ profile: "audience-chat",
647
+ conversation: { externalRef: conversationId },
648
+ task,
649
+ actor,
650
+ tools: { "sms-app-chat": { bearer } }, // the per-run bearer for your MCP server
651
+ webhook: { url },
652
+ idempotencyKey: dispatchId,
653
+ });
654
+ for await (const event of flytebot.runs.stream(run.id, { signal })) {
655
+ // in order, once each; reconnects with Last-Event-ID; ends after the terminal event
656
+ }
657
+ await flytebot.runs.get(run.id);
658
+ await flytebot.runs.usage(run.id);
659
+ await flytebot.runs.cancel(run.id, "user pressed stop"); // idempotent
660
+ await flytebot.profiles.get("planner-chat"); // model and effort pickers
661
+ ```
662
+
663
+ Every failure is a `FlytebotError` with `code` (the service's error code, or
664
+ `network_error`, `timeout`, `aborted`, `invalid_response`), `httpStatus` (null when no
665
+ response arrived), `retryable` and `requestId`. A `409 conversation_busy` carries
666
+ `details.activeRunId`.
667
+
668
+ The terminal webhook route verifies the call before it trusts the body:
669
+
670
+ ```ts
671
+ const run = await verifyTerminalWebhook(request, {
672
+ flytebotServiceAccount: env.flytebotServiceAccount,
673
+ audienceOrigin: "https://my-app.flytedesk.com", // the origin of the webhook URL you gave Flytebot
674
+ });
675
+ ```
676
+
677
+ It accepts only a Google-signed, unexpired ID token addressed to `audienceOrigin` whose
678
+ verified email is the Flytebot service account; anything else throws a
679
+ `FlytebotError` with code `unauthenticated` (answer 401). The route must be idempotent on
680
+ `(run.id, run.status)`: delivery is at-least-once.
681
+
682
+ ### Testing against the fake
683
+
684
+ `@flytedesk/app-kit/flytebot/testing` is an in-process Flytebot that speaks the contract:
685
+
686
+ ```ts
687
+ const fake = createFakeFlytebot();
688
+ await fake.start();
689
+ const flytebot = createFlytebotClient({ baseUrl: fake.url, idToken: async () => "t", timeoutMs: 1_000, retries: 2 });
690
+
691
+ fake.scriptRun({ events: [{ type: "text", messageId: "m1", delta: "hi" }], terminal: { status: "timeout" } });
692
+ fake.scriptRun({ hold: true }); // stays running: fake.emit(runId, ...) then fake.finish(runId)
693
+ fake.scriptRun({ events, dropStreamAfter: 3 }); // cuts the first stream to exercise reconnect
694
+ fake.failNext({ match: "POST /v1/runs", code: "unavailable" }); // a 503, then success
695
+ fake.setLlm("goal-judgment", { output: { achieved: true } });
696
+ fake.requests; // every request, with headers and parsed body
697
+ ```
698
+
699
+ Any terminal status and any error code can be scripted; it also enforces one active run per
700
+ conversation and replays an idempotency key.
701
+
702
+ ### Serving your tools to Flytebot (`@flytedesk/app-kit/chat/tools`)
703
+
704
+ `createRemoteMcpPlugin` serves your `AppRegisteredTool`s (and `createReplyTool`, unchanged)
705
+ over MCP streamable HTTP from your own API process. `authenticate` runs on every request and
706
+ returns your context for the bearer, or `null` (401); `tools(context)` builds that request's
707
+ tools, so a handler sees the context through its closure.
708
+
709
+ ```ts
710
+ await app.register(
711
+ createRemoteMcpPlugin({
712
+ serverName: "sms-app-chat",
713
+ authenticate: async (bearer) => findRunningTurnByToken(bearer),
714
+ tools: (turn) => [createReplyTool({ description, deliver: (reply) => recordReply(turn, reply) })],
715
+ }),
716
+ { prefix: "/mcp/chat" },
717
+ );
718
+ ```
719
+
720
+ A handler that throws is logged and reported to the agent as a tool error (`Tool "x"
721
+ failed.`); a validation error you return as `{ ok: false, retryable: false }` is read by the
722
+ model, and a retryable one is a JSON-RPC error.
723
+
604
724
  ## Tests
605
725
 
606
726
  `npm run check` is the full gate: lint, typecheck, build, unit tests, integration tests
@@ -620,3 +740,11 @@ tip (or a given ref), runs `npm run check`, applies pending changesets
620
740
  and prints a final `RESULT:` line. Every change under `src/` merges to `main` with a
621
741
  changeset in `.changeset/`; it sits there until the next release. Full steps:
622
742
  `.danxbot/config/workflow.md`, "Publishing".
743
+
744
+ ## Repo hygiene checks (`app-kit-repo-check`)
745
+
746
+ `app-kit-repo-check <narration|no-nul|hygiene|script-comments|repo-files> [--root <dir>] [--config <file>]`
747
+ runs the shared hygiene checks over a tree and exits 1 naming each finding. Per-repo values
748
+ live in `app-kit-repo-check.json` at the root (all optional): `excludedDirs` (added to the
749
+ built-in `node_modules`, `.git`, `dist`, ...), `narrationAllowlist` (exact strings the
750
+ narration check accepts) and `narrationExcludedBasenames` (files never read).
@@ -16,6 +16,10 @@ export declare function requireAuth(request: FastifyRequest, reply: FastifyReply
16
16
  /** Every route re-checks permissions server-side. 403s name the missing permission(s)
17
17
  * in `detail`, so a caller (or its UI) can tell exactly what was missing. */
18
18
  export declare function requirePermission(...permission: string[]): (request: FastifyRequest, reply: FastifyReply, done: () => void) => void;
19
+ /** For a route open to a caller holding ANY ONE of `permissions` (`requirePermission`
20
+ * wants all of them). Refuses like `requirePermission` does — 401/503 first, then the
21
+ * same 403 body — with `detail` naming the keys of which one was needed. */
22
+ export declare function requireAnyPermission(...permissions: string[]): (request: FastifyRequest, reply: FastifyReply, done: () => void) => void;
19
23
  /**
20
24
  * Answers the request unless it carries a signed-in PERSON, and returns whether it did:
21
25
  * `rejectUnauthenticated`'s 401/503 first, then `403 person_only` for a service
@@ -43,6 +43,28 @@ export function requirePermission(...permission) {
43
43
  done();
44
44
  };
45
45
  }
46
+ /** For a route open to a caller holding ANY ONE of `permissions` (`requirePermission`
47
+ * wants all of them). Refuses like `requirePermission` does — 401/503 first, then the
48
+ * same 403 body — with `detail` naming the keys of which one was needed. */
49
+ export function requireAnyPermission(...permissions) {
50
+ // An empty list would refuse everyone silently; it is a route written wrong.
51
+ if (permissions.length === 0) {
52
+ throw new Error("@flytedesk/app-kit/auth: requireAnyPermission() needs at least one permission key");
53
+ }
54
+ return function anyPermissionPreHandler(request, reply, done) {
55
+ if (rejectUnauthenticated(request, reply))
56
+ return;
57
+ if (!permissions.some((p) => request.authUser.permissions.includes(p))) {
58
+ reply.code(403).send({
59
+ error: "Missing permission",
60
+ code: "forbidden",
61
+ detail: `one of: ${permissions.join(", ")}`,
62
+ });
63
+ return;
64
+ }
65
+ done();
66
+ };
67
+ }
46
68
  /**
47
69
  * Answers the request unless it carries a signed-in PERSON, and returns whether it did:
48
70
  * `rejectUnauthenticated`'s 401/503 first, then `403 person_only` for a service
@@ -1 +1 @@
1
- {"version":3,"file":"guards.js","sourceRoot":"","sources":["../../src/auth/guards.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAEvD;;;;;;;;;;GAUG;AACH,MAAM,UAAU,qBAAqB,CAAC,OAAuB,EAAE,KAAmB;IAChF,IAAI,OAAO,CAAC,QAAQ;QAAE,OAAO,KAAK,CAAC;IACnC,IAAI,OAAO,CAAC,eAAe,EAAE,CAAC;QAC5B,mBAAmB,CAAC,KAAK,EAAE,OAAO,CAAC,eAAe,CAAC,CAAC;QACpD,OAAO,IAAI,CAAC;IACd,CAAC;IACD,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,yBAAyB,EAAE,IAAI,EAAE,iBAAiB,EAAE,CAAC,CAAC;IACpF,OAAO,IAAI,CAAC;AACd,CAAC;AAED,MAAM,UAAU,WAAW,CAAC,OAAuB,EAAE,KAAmB,EAAE,IAAgB;IACxF,IAAI,qBAAqB,CAAC,OAAO,EAAE,KAAK,CAAC;QAAE,OAAO;IAClD,IAAI,EAAE,CAAC;AACT,CAAC;AAED;8EAC8E;AAC9E,MAAM,UAAU,iBAAiB,CAAC,GAAG,UAAoB;IACvD,OAAO,SAAS,oBAAoB,CAClC,OAAuB,EACvB,KAAmB,EACnB,IAAgB;QAEhB,IAAI,qBAAqB,CAAC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QAAS,CAAC,IAAI,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IACtD,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,4CAA4C,EAAE,IAAI,EAAE,aAAa,EAAE,CAAC,CAAC;IACnG,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;oDAEoD;AACpD,MAAM,UAAU,aAAa,CAAC,OAAuB,EAAE,KAAmB,EAAE,IAAgB;IAC1F,IAAI,kBAAkB,CAAC,OAAO,EAAE,KAAK,CAAC;QAAE,OAAO;IAC/C,IAAI,EAAE,CAAC;AACT,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,YAAY,CAAC,OAAuB;IAClD,MAAM,IAAI,GAAG,OAAO,CAAC,QAAQ,CAAC;IAC9B,IAAI,IAAI,EAAE,IAAI,KAAK,QAAQ,EAAE,CAAC;QAC5B,MAAM,IAAI,KAAK,CACb,oFAAoF,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,IAAI,YAAY,CAAC,CAAC,CAAC,iBAAiB,wCAAwC,CAClL,CAAC;IACJ,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC"}
@@ -47,7 +47,7 @@
47
47
  * `readRoute` and `requirePerson`, and `@flytedesk/app-kit/auth/service` for the
48
48
  * caller's side.
49
49
  */
50
- export { authedPerson, requireAuth, requirePermission, requirePerson } from "./guards.js";
50
+ export { authedPerson, requireAnyPermission, requireAuth, requirePermission, requirePerson } from "./guards.js";
51
51
  export { readRoute } from "./readRoute.js";
52
52
  export type { AuthedUser, AuthStore, CreateIdpSessionInput, CreateRefreshTokenInput, DelegatedIdentity, DelegatedOutcome, FlytedeskAuthOptions, IdpRole, IdpSessionLockedStore, IdpSessionRow, RefreshTokenRevocation, RefreshTokenRevocationReason, RefreshTokenRow, RevokeFamilyReason, ServicePrincipalUser, UpdateIdpSessionInput, UserinfoClaims, } from "./types.js";
53
53
  export type { AppSwitcherEntry, IdpAuthorization, IdpServiceAuthorization, IdpTokenResponse, IdTokenClaims, OidcClient, OidcClientOptions, ServiceAccessTokenClaims, } from "./oidc-client.js";
@@ -47,7 +47,7 @@
47
47
  * `readRoute` and `requirePerson`, and `@flytedesk/app-kit/auth/service` for the
48
48
  * caller's side.
49
49
  */
50
- export { authedPerson, requireAuth, requirePermission, requirePerson } from "./guards.js";
50
+ export { authedPerson, requireAnyPermission, requireAuth, requirePermission, requirePerson } from "./guards.js";
51
51
  export { readRoute } from "./readRoute.js";
52
52
  export { createOidcClient, DEFAULT_OIDC_SCOPES, DEFAULT_IDP_REQUEST_TIMEOUT_MS } from "./oidc-client.js";
53
53
  export { AUTH_REQUEST_DEADLINE_MS, AUTH_ROUTE_PREFIX, AUTH_ROUTE_SEGMENTS, AUTH_UNAVAILABLE_CODES, authRoutePath, SIGNIN_ERROR_QUERY_PARAM, SIGNIN_ERROR_CODES, } from "./shared-types.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/auth/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgDG;AACH,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC1F,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAgC3C,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,8BAA8B,EAAE,MAAM,kBAAkB,CAAC;AAOzG,OAAO,EACL,wBAAwB,EACxB,iBAAiB,EACjB,mBAAmB,EACnB,sBAAsB,EACtB,aAAa,EACb,wBAAwB,EACxB,kBAAkB,GAEnB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,QAAQ,EACR,mBAAmB,EACnB,eAAe,EACf,qBAAqB,EACrB,cAAc,EACd,aAAa,EACb,cAAc,EACd,wBAAwB,EACxB,gBAAgB,GACjB,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,YAAY,EAAE,WAAW,EAAiB,MAAM,WAAW,CAAC;AAErE,OAAO,EACL,oBAAoB,EACpB,gBAAgB,EAChB,eAAe,EACf,iBAAiB,GAElB,MAAM,aAAa,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/auth/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgDG;AACH,OAAO,EAAE,YAAY,EAAE,oBAAoB,EAAE,WAAW,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAChH,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAgC3C,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,8BAA8B,EAAE,MAAM,kBAAkB,CAAC;AAOzG,OAAO,EACL,wBAAwB,EACxB,iBAAiB,EACjB,mBAAmB,EACnB,sBAAsB,EACtB,aAAa,EACb,wBAAwB,EACxB,kBAAkB,GAEnB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,QAAQ,EACR,mBAAmB,EACnB,eAAe,EACf,qBAAqB,EACrB,cAAc,EACd,aAAa,EACb,cAAc,EACd,wBAAwB,EACxB,gBAAgB,GACjB,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,YAAY,EAAE,WAAW,EAAiB,MAAM,WAAW,CAAC;AAErE,OAAO,EACL,oBAAoB,EACpB,gBAAgB,EAChB,eAAe,EACf,iBAAiB,GAElB,MAAM,aAAa,CAAC"}
@@ -0,0 +1 @@
1
+ export { PrismaAuthStore, type PrismaAuthClient } from "./prismaAuthStore.js";
@@ -0,0 +1,2 @@
1
+ export { PrismaAuthStore } from "./prismaAuthStore.js";
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/auth/prisma/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAyB,MAAM,sBAAsB,CAAC"}
@@ -0,0 +1,181 @@
1
+ import type { AuthStore, CreateIdpSessionInput, CreateRefreshTokenInput, IdpSessionLockedStore, IdpSessionRow, RefreshTokenRow, RevokeFamilyReason, UpdateIdpSessionInput } from "../types.js";
2
+ interface IdpSessionData {
3
+ id: string;
4
+ subject: string;
5
+ name: string;
6
+ email: string;
7
+ idpAccessToken: string;
8
+ idpAccessTokenExpiresAt: Date;
9
+ idpRefreshToken: string | null;
10
+ idToken: string;
11
+ }
12
+ interface RefreshTokenData {
13
+ id: string;
14
+ familyId: string;
15
+ userId: string;
16
+ idpSessionId: string;
17
+ expiresAt: Date;
18
+ ip: string;
19
+ userAgent: string | null;
20
+ revokedAt: Date | null;
21
+ revokedReason: string | null;
22
+ }
23
+ /** The IdP-session half of the structural client. */
24
+ interface IdpSessionModel {
25
+ findUnique(args: {
26
+ where: {
27
+ id: string;
28
+ };
29
+ }): Promise<IdpSessionData | null>;
30
+ update(args: {
31
+ where: {
32
+ id: string;
33
+ };
34
+ data: {
35
+ idpAccessToken?: string;
36
+ idpAccessTokenExpiresAt?: Date;
37
+ idpRefreshToken?: string | null;
38
+ };
39
+ }): Promise<unknown>;
40
+ create(args: {
41
+ data: Omit<IdpSessionData, "id">;
42
+ select: {
43
+ id: true;
44
+ };
45
+ }): Promise<{
46
+ id: string;
47
+ }>;
48
+ delete(args: {
49
+ where: {
50
+ id: string;
51
+ };
52
+ }): Promise<unknown>;
53
+ }
54
+ interface RefreshTokenModel {
55
+ create(args: {
56
+ data: {
57
+ id: string;
58
+ familyId: string;
59
+ userId: string;
60
+ tokenHash: string;
61
+ expiresAt: Date;
62
+ idpSessionId: string;
63
+ userAgent: string | null;
64
+ ip: string;
65
+ replacesId: string | null;
66
+ };
67
+ }): Promise<unknown>;
68
+ findUnique(args: {
69
+ where: {
70
+ tokenHash: string;
71
+ };
72
+ }): Promise<RefreshTokenData | null>;
73
+ findFirst(args: {
74
+ where: {
75
+ idpSessionId: string;
76
+ revokedAt: null;
77
+ expiresAt: {
78
+ gt: Date;
79
+ };
80
+ };
81
+ orderBy: {
82
+ createdAt: "desc";
83
+ };
84
+ }): Promise<RefreshTokenData | null>;
85
+ updateMany(args: {
86
+ where: {
87
+ id: string;
88
+ revokedAt: null;
89
+ } | {
90
+ familyId: string;
91
+ revokedAt: null;
92
+ };
93
+ data: {
94
+ revokedAt: Date;
95
+ revokedReason: string;
96
+ };
97
+ }): Promise<{
98
+ count: number;
99
+ }>;
100
+ }
101
+ interface AuthAuditLogModel {
102
+ create(args: {
103
+ data: {
104
+ familyId: string;
105
+ reason: string;
106
+ rotatedAt: Date;
107
+ ip: string | null;
108
+ userAgent: string | null;
109
+ };
110
+ }): Promise<unknown>;
111
+ }
112
+ /** What a transaction (or the pool) must expose: the three fragment models plus the raw
113
+ * executor the advisory lock goes through. */
114
+ interface PrismaAuthTransaction {
115
+ idpSession: IdpSessionModel;
116
+ refreshToken: RefreshTokenModel;
117
+ authAuditLog: AuthAuditLogModel;
118
+ $executeRaw(query: TemplateStringsArray, ...values: unknown[]): Promise<number>;
119
+ }
120
+ /** A generated Prisma client (carrying `prisma/fragments/auth.prisma`'s models) satisfies this. */
121
+ export interface PrismaAuthClient extends PrismaAuthTransaction {
122
+ $transaction<T>(fn: (tx: PrismaAuthTransaction) => Promise<T>, options: {
123
+ timeout: number;
124
+ maxWait: number;
125
+ }): Promise<T>;
126
+ }
127
+ /**
128
+ * `withIdpSessionLock` hands its callback a store bound to the SAME transaction the
129
+ * advisory lock lives on; `rotateRefreshToken` is one atomic transaction end to end;
130
+ * `revokeFamily` takes the same per-family lock so it can never race a concurrent
131
+ * rotation. The advisory-lock primitive itself lives in `@flytedesk/app-kit/postgres`.
132
+ */
133
+ export declare class PrismaAuthStore implements AuthStore {
134
+ private readonly prisma;
135
+ /** The pooled (unlocked) store — `POST {routePrefix}/refresh`'s initial read runs here,
136
+ * outside any lock; only reads/writes done WHILE holding `withIdpSessionLock` run on
137
+ * that lock's own transaction. */
138
+ private readonly pooled;
139
+ constructor(prisma: PrismaAuthClient);
140
+ findIdpSession(id: string): Promise<IdpSessionRow | null>;
141
+ updateIdpSession(id: string, patch: UpdateIdpSessionInput): Promise<void>;
142
+ createRefreshToken(row: CreateRefreshTokenInput): Promise<void>;
143
+ findRefreshTokenByHash(hash: string): Promise<RefreshTokenRow | null>;
144
+ /**
145
+ * Whether the IdP session is still signed in. Reuse detection and an authorization
146
+ * rejection revoke the family without deleting the session, so the session row existing
147
+ * proves nothing; a live refresh token (not revoked, not expired at `now`, the app's
148
+ * clock) of the session does. A sign-out deletes the session, cascading its tokens.
149
+ */
150
+ findLiveRefreshTokenForSession(idpSessionId: string, now: Date): Promise<RefreshTokenRow | null>;
151
+ /**
152
+ * One transaction — take the family lock, conditionally revoke `presentedId` with reason
153
+ * "rotated" (claims iff it was still live), and only then insert `successor`. `rotatedAt`
154
+ * (not `new Date()`) is persisted: the ONE-clock rule in `AuthStore`'s doc comment.
155
+ */
156
+ rotateRefreshToken(presentedId: string, successor: CreateRefreshTokenInput, rotatedAt: Date): Promise<boolean>;
157
+ /**
158
+ * Takes the SAME per-family lock as `rotateRefreshToken` before revoking, so whichever
159
+ * of a concurrent sign-out/rotation pair runs second sees the other's committed rows
160
+ * (under READ COMMITTED, skipping the lock lets a rotation's successor survive a revoke
161
+ * that started just before it committed). The reuse-detection audit write is in the SAME
162
+ * transaction as the revoke: a reuse is revoked AND audited, or neither.
163
+ */
164
+ revokeFamily(familyId: string, reason: RevokeFamilyReason, revokedAt: Date): Promise<void>;
165
+ createIdpSession(row: CreateIdpSessionInput): Promise<{
166
+ id: string;
167
+ }>;
168
+ deleteIdpSession(id: string): Promise<void>;
169
+ /**
170
+ * `fn` is handed an `IdpSessionLockedStore` bound to the SAME transaction the advisory
171
+ * lock lives on, so a lock holder never needs a second pooled connection: one that had
172
+ * to reach back into the pool would let concurrent stale-session refreshes exhaust it
173
+ * and sign out every session still waiting once their number reached the pool's size.
174
+ *
175
+ * Residual risk (documented on the contract): if `updateIdpSession` or this transaction's
176
+ * commit fails after flytedesk-id already rotated its own refresh token, that new token
177
+ * is lost and the user must sign in again.
178
+ */
179
+ withIdpSessionLock<T>(sessionId: string, fn: (locked: IdpSessionLockedStore) => Promise<T>): Promise<T>;
180
+ }
181
+ export {};