@quatronic/sdk 0.7.0-rc.8 → 0.7.0-test.3603305

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 (106) hide show
  1. package/dist/auth/index.js +1 -1
  2. package/dist/{chunk-2AYDFLKR.js → chunk-F3NHTHFO.js} +6 -104
  3. package/dist/chunk-F3NHTHFO.js.map +1 -0
  4. package/dist/{chunk-5MNPBJYS.js → chunk-G7VPNC6M.js} +5 -11
  5. package/dist/{chunk-5MNPBJYS.js.map → chunk-G7VPNC6M.js.map} +1 -1
  6. package/dist/{chunk-ZZTO5Z3N.js → chunk-HQT57ITV.js} +2 -2
  7. package/dist/{chunk-EK6TGWWT.js → chunk-MET4SIMB.js} +2 -8
  8. package/dist/chunk-MET4SIMB.js.map +1 -0
  9. package/dist/chunk-P7HNHLW7.js +65 -0
  10. package/dist/chunk-P7HNHLW7.js.map +1 -0
  11. package/dist/chunk-QMOZDE3U.js +158 -0
  12. package/dist/chunk-QMOZDE3U.js.map +1 -0
  13. package/dist/{chunk-ROHIN74F.js → chunk-TEBDKNUB.js} +2 -2
  14. package/dist/chunk-TOBGX4CZ.js +109 -0
  15. package/dist/chunk-TOBGX4CZ.js.map +1 -0
  16. package/dist/chunk-WU7N4PET.js +20 -0
  17. package/dist/chunk-WU7N4PET.js.map +1 -0
  18. package/dist/cli/legacy/qdc-sourcemaps.js +16 -6
  19. package/dist/cli/skills-postinstall.js +133 -3
  20. package/dist/cli/skills.js +133 -3
  21. package/dist/cli/sourcemaps.js +16 -6
  22. package/dist/eslint/index.js +2 -22
  23. package/dist/eslint/index.js.map +1 -1
  24. package/dist/integrations/index.d.ts +3 -75
  25. package/dist/integrations/index.js +6 -4
  26. package/dist/mail/index.d.ts +9 -0
  27. package/dist/mail/index.js +26 -0
  28. package/dist/mail/index.js.map +1 -0
  29. package/dist/next/auth/index.d.ts +12 -0
  30. package/dist/next/auth/index.js +15 -156
  31. package/dist/next/auth/index.js.map +1 -1
  32. package/dist/next/better-auth/index.js +1 -1
  33. package/dist/next/boot/index.d.ts +33 -0
  34. package/dist/next/boot/index.js +21 -0
  35. package/dist/next/boot/index.js.map +1 -0
  36. package/dist/next/connections/index.js +3 -3
  37. package/dist/next/db/index.d.ts +18 -1
  38. package/dist/next/db/index.js +25 -0
  39. package/dist/next/db/index.js.map +1 -1
  40. package/dist/next/global-error/index.d.ts +9 -0
  41. package/dist/next/global-error/index.js +17 -0
  42. package/dist/next/global-error/index.js.map +1 -0
  43. package/dist/next/integrations/index.d.ts +2 -1
  44. package/dist/next/integrations/index.js +6 -4
  45. package/dist/next/platform/index.d.ts +19 -0
  46. package/dist/next/platform/index.js +44 -0
  47. package/dist/next/platform/index.js.map +1 -0
  48. package/dist/next/security/index.d.ts +23 -1
  49. package/dist/next/security/index.js +41 -58
  50. package/dist/next/security/index.js.map +1 -1
  51. package/dist/next/sentry/client.d.ts +0 -1
  52. package/dist/next/sentry/client.js +2 -2
  53. package/dist/next/sentry/register.js +6 -14
  54. package/dist/next/sentry/register.js.map +1 -1
  55. package/dist/next/users/index.js +7 -4
  56. package/dist/next/users/index.js.map +1 -1
  57. package/dist/node/boot/index.d.ts +9 -0
  58. package/dist/node/boot/index.js +13 -0
  59. package/dist/node/boot/index.js.map +1 -0
  60. package/dist/node/connections/index.js +3 -3
  61. package/dist/node/identity/index.js +2 -2
  62. package/dist/node/integrations/index.d.ts +2 -1
  63. package/dist/node/integrations/index.js +6 -4
  64. package/dist/node/sentry/register.js +2 -2
  65. package/dist/node-Z7ERWJDZ.js +46 -0
  66. package/dist/node-Z7ERWJDZ.js.map +1 -0
  67. package/dist/types-CAwj03sM.d.ts +75 -0
  68. package/migrations/bootstrap-qore-env/codemod.mjs +77 -0
  69. package/migrations/bootstrap-qore-env/instructions.md +28 -0
  70. package/migrations/bootstrap-qore-env/meta.json +7 -0
  71. package/migrations/global-error/codemod.mjs +28 -0
  72. package/migrations/global-error/instructions.md +26 -0
  73. package/migrations/global-error/meta.json +7 -0
  74. package/migrations/local-db-port/codemod.mjs +61 -0
  75. package/migrations/local-db-port/instructions.md +35 -0
  76. package/migrations/local-db-port/meta.json +7 -0
  77. package/migrations/mail-reexport/codemod.mjs +64 -0
  78. package/migrations/mail-reexport/instructions.md +27 -0
  79. package/migrations/mail-reexport/meta.json +7 -0
  80. package/migrations/platform-routes/codemod.mjs +45 -0
  81. package/migrations/platform-routes/instructions.md +30 -0
  82. package/migrations/platform-routes/meta.json +7 -0
  83. package/migrations/qore-boot/codemod.mjs +261 -0
  84. package/migrations/qore-boot/instructions.md +74 -0
  85. package/migrations/qore-boot/meta.json +7 -0
  86. package/migrations/qore-proxy/codemod.mjs +88 -0
  87. package/migrations/qore-proxy/instructions.md +56 -0
  88. package/migrations/qore-proxy/meta.json +7 -0
  89. package/migrations/run.mjs +322 -0
  90. package/migrations/sourcemaps-finalize/codemod.mjs +63 -0
  91. package/migrations/sourcemaps-finalize/instructions.md +56 -0
  92. package/migrations/sourcemaps-finalize/meta.json +7 -0
  93. package/package.json +26 -8
  94. package/skills/qore-enable-auth-method/SKILL.md +4 -3
  95. package/skills/qore-use-mail-domain/SKILL.next.md +4 -4
  96. package/workspace-requirements.json +4 -0
  97. package/dist/chunk-2AYDFLKR.js.map +0 -1
  98. package/dist/chunk-EK6TGWWT.js.map +0 -1
  99. package/dist/observability/index.d.ts +0 -10
  100. package/dist/observability/index.js +0 -7
  101. package/dist/observability/index.js.map +0 -1
  102. package/migrations/report-error/codemod.mjs +0 -94
  103. package/migrations/report-error/instructions.md +0 -46
  104. package/migrations/report-error/meta.json +0 -6
  105. /package/dist/{chunk-ZZTO5Z3N.js.map → chunk-HQT57ITV.js.map} +0 -0
  106. /package/dist/{chunk-ROHIN74F.js.map → chunk-TEBDKNUB.js.map} +0 -0
@@ -1,79 +1,7 @@
1
+ import { I as IntegrationMap, a as IntegrationDefinition, E as EnvRef } from '../types-CAwj03sM.js';
2
+ export { A as AUTH_ENV_FIELDS, b as AUTH_SECRET_FIELDS, c as AuthKind, d as EnvKey, e as IntegrationAuth, P as Protocol, R as RESERVED_KEY_PREFIX, f as defineIntegrations } from '../types-CAwj03sM.js';
1
3
  import { E as Env } from '../env-R-bci5RU.js';
2
4
 
3
- /**
4
- * How an integration authenticates. Every field except `header` and
5
- * `credentialsIn` names an **env key** — the SDK reads the value from the
6
- * environment at call time, never from the declaration — so a declaration can
7
- * sit in source control and carry no secret.
8
- */
9
- type AuthKind = "none" | "api_key_header" | "bearer_static" | "basic" | "oauth2_client_credentials";
10
- /** What the API speaks. Informational for the portal; the client sends bytes either way. */
11
- type Protocol = "rest" | "odata" | "soap" | "graphql";
12
- /** The name of an env var, e.g. `SAP_BASE_URL`. */
13
- type EnvKey = string;
14
- /**
15
- * A reference to an env var. The short form is required; the object form can
16
- * be optional and carry a default the app falls back on when the key is unset.
17
- */
18
- type EnvRef = EnvKey | {
19
- key: EnvKey;
20
- optional?: boolean;
21
- default?: string | number | boolean;
22
- };
23
- type IntegrationAuth = {
24
- kind: "none";
25
- } | {
26
- kind: "api_key_header";
27
- header: string;
28
- apiKey: EnvKey;
29
- } | {
30
- kind: "bearer_static";
31
- token: EnvKey;
32
- } | {
33
- kind: "basic";
34
- username: EnvKey;
35
- password: EnvKey;
36
- } | {
37
- kind: "oauth2_client_credentials";
38
- tokenUrl: EnvKey;
39
- clientId: EnvKey;
40
- clientSecret: EnvKey;
41
- scope?: EnvKey;
42
- audience?: EnvKey;
43
- /** Where the client credentials go on the token request. Default `"header"`. */
44
- credentialsIn?: "header" | "body";
45
- };
46
- interface IntegrationDefinition {
47
- /** Human name shown in the portal, e.g. "SAP S/4HANA Cloud". */
48
- label: string;
49
- protocol: Protocol;
50
- /** Env key holding the base URL for this environment. */
51
- baseUrl: EnvKey;
52
- auth: IntegrationAuth;
53
- /** Further env the app reads for this integration, by logical name. */
54
- config?: Record<string, EnvRef>;
55
- }
56
- type IntegrationMap = Record<string, IntegrationDefinition>;
57
- /**
58
- * Identity function that pins the literal types of the map, so an alias typo
59
- * at a call site is a compile error (`keyof M`) rather than a runtime
60
- * `not_declared`. Same shape as `definePermissions` in `auth-core`.
61
- */
62
- declare function defineIntegrations<const M extends IntegrationMap>(map: M): M;
63
- /**
64
- * Which fields of each auth kind name an env key. Shared with the manifest
65
- * extractor and the portal, which derive the required-env list from a
66
- * declaration without evaluating app code.
67
- */
68
- declare const AUTH_ENV_FIELDS: Record<AuthKind, readonly string[]>;
69
- /** Auth fields whose env value is a secret, so the portal masks it. */
70
- declare const AUTH_SECRET_FIELDS: readonly ["apiKey", "token", "password", "clientSecret"];
71
- /**
72
- * Env keys under this prefix belong to the platform
73
- * (`QORE_INTEGRATION_<ALIAS>_LOGGING` today). A declaration may not claim one.
74
- */
75
- declare const RESERVED_KEY_PREFIX = "QORE_INTEGRATION_";
76
-
77
5
  interface IntegrationProblem {
78
6
  alias: string;
79
7
  key: string;
@@ -213,4 +141,4 @@ declare const INTEGRATION_SPAN_TYPE_ATTR = "qore.span.type";
213
141
  /** A cached OAuth2 token is refreshed this long before it expires. */
214
142
  declare const OAUTH_REFRESH_SKEW_MS = 30000;
215
143
 
216
- export { AUTH_ENV_FIELDS, AUTH_SECRET_FIELDS, type AuthKind, DEFAULT_INTEGRATION_TIMEOUT_MS, type EnvKey, type EnvRef, INTEGRATION_ALIAS_ATTR, INTEGRATION_SPAN_TYPE, INTEGRATION_SPAN_TYPE_ATTR, type IntegrationAuth, type IntegrationClient, type IntegrationConfig, type IntegrationDefinition, IntegrationError, type IntegrationErrorCode, type IntegrationHandle, type IntegrationMap, type IntegrationProblem, type IntegrationRequest, OAUTH_REFRESH_SKEW_MS, PLATFORM_MANAGED_HOSTS, type ParamValue, type Protocol, RESERVED_KEY_PREFIX, allKeys, assertIntegrations, createIntegrationClient, defineIntegrations, isPlatformManagedHost, loggingEnabled, loggingKey, readRef, requiredKeys };
144
+ export { DEFAULT_INTEGRATION_TIMEOUT_MS, EnvRef, INTEGRATION_ALIAS_ATTR, INTEGRATION_SPAN_TYPE, INTEGRATION_SPAN_TYPE_ATTR, type IntegrationClient, type IntegrationConfig, IntegrationDefinition, IntegrationError, type IntegrationErrorCode, type IntegrationHandle, IntegrationMap, type IntegrationProblem, type IntegrationRequest, OAUTH_REFRESH_SKEW_MS, PLATFORM_MANAGED_HOSTS, type ParamValue, allKeys, assertIntegrations, createIntegrationClient, isPlatformManagedHost, loggingEnabled, loggingKey, readRef, requiredKeys };
@@ -1,22 +1,24 @@
1
1
  import {
2
- AUTH_ENV_FIELDS,
3
- AUTH_SECRET_FIELDS,
4
2
  DEFAULT_INTEGRATION_TIMEOUT_MS,
5
3
  INTEGRATION_ALIAS_ATTR,
6
4
  INTEGRATION_SPAN_TYPE,
7
5
  INTEGRATION_SPAN_TYPE_ATTR,
8
6
  IntegrationError,
9
7
  OAUTH_REFRESH_SKEW_MS,
8
+ createIntegrationClient
9
+ } from "../chunk-F3NHTHFO.js";
10
+ import {
11
+ AUTH_ENV_FIELDS,
12
+ AUTH_SECRET_FIELDS,
10
13
  RESERVED_KEY_PREFIX,
11
14
  allKeys,
12
15
  assertIntegrations,
13
- createIntegrationClient,
14
16
  defineIntegrations,
15
17
  loggingEnabled,
16
18
  loggingKey,
17
19
  readRef,
18
20
  requiredKeys
19
- } from "../chunk-2AYDFLKR.js";
21
+ } from "../chunk-TOBGX4CZ.js";
20
22
  import {
21
23
  PLATFORM_MANAGED_HOSTS,
22
24
  isPlatformManagedHost
@@ -0,0 +1,9 @@
1
+ type Mail = {
2
+ to: string;
3
+ subject: string;
4
+ html: string;
5
+ text: string;
6
+ };
7
+ declare function sendMail(mail: Mail): Promise<void>;
8
+
9
+ export { type Mail, sendMail };
@@ -0,0 +1,26 @@
1
+ import {
2
+ getLogger
3
+ } from "../chunk-MET4SIMB.js";
4
+
5
+ // src/mail/index.ts
6
+ async function sendMail(mail) {
7
+ const apiKey = process.env.MAIL_API_KEY;
8
+ if (!apiKey) {
9
+ getLogger().warn({}, "mail skipped: no MAIL_API_KEY");
10
+ return;
11
+ }
12
+ const from = process.env.MAIL_FROM;
13
+ if (!from) {
14
+ throw new Error("sendMail: MAIL_API_KEY is set but MAIL_FROM is missing");
15
+ }
16
+ const res = await fetch("https://api.resend.com/emails", {
17
+ method: "POST",
18
+ headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
19
+ body: JSON.stringify({ from, to: mail.to, subject: mail.subject, html: mail.html, text: mail.text })
20
+ });
21
+ if (!res.ok) throw new Error(`sendMail failed: ${res.status} ${await res.text()}`);
22
+ }
23
+ export {
24
+ sendMail
25
+ };
26
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/mail/index.ts"],"sourcesContent":["// Mail transport for Next and Node apps alike. Sends over Resend when\n// MAIL_API_KEY is set, otherwise skips with a warning, so an app without a mail\n// provider still runs. Runtime-neutral and Sentry-free: the warning goes through\n// the SDK log.\nimport { getLogger } from \"../telemetry-hooks\"\n\nexport type Mail = { to: string; subject: string; html: string; text: string }\n\nexport async function sendMail(mail: Mail): Promise<void> {\n const apiKey = process.env.MAIL_API_KEY\n if (!apiKey) {\n getLogger().warn({}, \"mail skipped: no MAIL_API_KEY\")\n return\n }\n const from = process.env.MAIL_FROM\n if (!from) {\n throw new Error(\"sendMail: MAIL_API_KEY is set but MAIL_FROM is missing\")\n }\n const res = await fetch(\"https://api.resend.com/emails\", {\n method: \"POST\",\n headers: { Authorization: `Bearer ${apiKey}`, \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ from, to: mail.to, subject: mail.subject, html: mail.html, text: mail.text }),\n })\n if (!res.ok) throw new Error(`sendMail failed: ${res.status} ${await res.text()}`)\n}\n"],"mappings":";;;;;AAQA,eAAsB,SAAS,MAA2B;AACxD,QAAM,SAAS,QAAQ,IAAI;AAC3B,MAAI,CAAC,QAAQ;AACX,cAAU,EAAE,KAAK,CAAC,GAAG,+BAA+B;AACpD;AAAA,EACF;AACA,QAAM,OAAO,QAAQ,IAAI;AACzB,MAAI,CAAC,MAAM;AACT,UAAM,IAAI,MAAM,wDAAwD;AAAA,EAC1E;AACA,QAAM,MAAM,MAAM,MAAM,iCAAiC;AAAA,IACvD,QAAQ;AAAA,IACR,SAAS,EAAE,eAAe,UAAU,MAAM,IAAI,gBAAgB,mBAAmB;AAAA,IACjF,MAAM,KAAK,UAAU,EAAE,MAAM,IAAI,KAAK,IAAI,SAAS,KAAK,SAAS,MAAM,KAAK,MAAM,MAAM,KAAK,KAAK,CAAC;AAAA,EACrG,CAAC;AACD,MAAI,CAAC,IAAI,GAAI,OAAM,IAAI,MAAM,oBAAoB,IAAI,MAAM,IAAI,MAAM,IAAI,KAAK,CAAC,EAAE;AACnF;","names":[]}
@@ -8,6 +8,12 @@ declare function permissionsForRoles(map: PermissionMap, roles: string[]): strin
8
8
 
9
9
  type NextAuthOptions = {
10
10
  keycloakUrl: string;
11
+ /** Optional in-cluster address of Keycloak, used ONLY for this server's own
12
+ * HTTP calls (token exchange, refresh, back-channel logout, JWKS fetch).
13
+ * The issuer, every `iss` check, the authorize URL, the end-session URL and
14
+ * redirect URIs stay on the public `keycloakUrl`. Keycloak must advertise the
15
+ * public issuer when reached this way. Unset: everything uses `keycloakUrl`. */
16
+ keycloakInternalUrl?: string;
11
17
  realm: string;
12
18
  clientId: string;
13
19
  clientSecret: string;
@@ -47,6 +53,12 @@ declare function createAuthRouteHandlers(opts: NextAuthOptions): Promise<AuthRou
47
53
 
48
54
  type KcConfig = {
49
55
  keycloakUrl: string;
56
+ /** Optional in-cluster address of Keycloak, used ONLY for this server's own
57
+ * HTTP calls (token exchange, refresh, back-channel logout, JWKS fetch).
58
+ * The issuer, every `iss` check, the authorize URL, the end-session URL and
59
+ * redirect URIs stay on the public `keycloakUrl`. Keycloak must advertise the
60
+ * public issuer when reached this way. Unset: everything uses `keycloakUrl`. */
61
+ keycloakInternalUrl?: string;
50
62
  realm: string;
51
63
  clientId: string;
52
64
  clientSecret: string;
@@ -1,11 +1,12 @@
1
1
  import {
2
- grantRuntimeDefaultPrivileges
3
- } from "../../chunk-BJN7YE63.js";
2
+ runAuthMigrations
3
+ } from "../../chunk-QMOZDE3U.js";
4
+ import "../../chunk-BJN7YE63.js";
4
5
  import "../../chunk-4MBB2UQW.js";
5
6
  import {
6
7
  getLogger,
7
8
  setUserContext
8
- } from "../../chunk-EK6TGWWT.js";
9
+ } from "../../chunk-MET4SIMB.js";
9
10
 
10
11
  // src/next/auth/createAuthRouteHandlers.ts
11
12
  import { NextResponse } from "next/server";
@@ -136,7 +137,9 @@ var KcTokenError = class extends Error {
136
137
  };
137
138
  function createKcClient(cfg) {
138
139
  const issuer = `${cfg.keycloakUrl}/realms/${cfg.realm}`;
139
- const tokenUrl = `${issuer}/protocol/openid-connect/token`;
140
+ const serverIssuer = cfg.keycloakInternalUrl ? `${cfg.keycloakInternalUrl.replace(/\/+$/, "")}/realms/${cfg.realm}` : issuer;
141
+ const tokenUrl = `${serverIssuer}/protocol/openid-connect/token`;
142
+ const backchannelLogoutUrl = `${serverIssuer}/protocol/openid-connect/logout`;
140
143
  const logoutUrl = `${issuer}/protocol/openid-connect/logout`;
141
144
  const authorizeUrl = `${issuer}/protocol/openid-connect/auth`;
142
145
  const redirectUri = `${cfg.publicOrigin}/api/auth/callback`;
@@ -221,7 +224,7 @@ function createKcClient(cfg) {
221
224
  client_secret: cfg.clientSecret,
222
225
  refresh_token: refreshToken
223
226
  });
224
- const res = await fetch(logoutUrl, {
227
+ const res = await fetch(backchannelLogoutUrl, {
225
228
  method: "POST",
226
229
  headers: { "content-type": "application/x-www-form-urlencoded" },
227
230
  body,
@@ -237,7 +240,8 @@ function createKcClient(cfg) {
237
240
  // src/auth-core/jwks.ts
238
241
  import { createRemoteJWKSet, jwtVerify } from "jose";
239
242
  function createJwks(opts) {
240
- const url = new URL(`${opts.keycloakUrl}/realms/${opts.realm}/protocol/openid-connect/certs`);
243
+ const fetchBase = opts.keycloakInternalUrl ? opts.keycloakInternalUrl.replace(/\/+$/, "") : opts.keycloakUrl;
244
+ const url = new URL(`${fetchBase}/realms/${opts.realm}/protocol/openid-connect/certs`);
241
245
  const jwkset = createRemoteJWKSet(url, {
242
246
  cooldownDuration: opts.cooldownMs ?? 3e4
243
247
  });
@@ -851,6 +855,7 @@ async function createAuthRouteHandlers(opts) {
851
855
  const handoff = await createIdentityHandoff({ secret: opts.sessionCookieSecret });
852
856
  const kcClient = createKcClient({
853
857
  keycloakUrl: opts.keycloakUrl,
858
+ keycloakInternalUrl: opts.keycloakInternalUrl,
854
859
  realm: opts.realm,
855
860
  clientId: opts.clientId,
856
861
  clientSecret: opts.clientSecret,
@@ -860,6 +865,7 @@ async function createAuthRouteHandlers(opts) {
860
865
  });
861
866
  const jwks = createJwks({
862
867
  keycloakUrl: opts.keycloakUrl,
868
+ keycloakInternalUrl: opts.keycloakInternalUrl,
863
869
  realm: opts.realm,
864
870
  audience: opts.clientId
865
871
  });
@@ -1503,6 +1509,7 @@ async function requireAuthFor(opts) {
1503
1509
  const refreshStore = createRefreshStore({ db: opts.db, cipher });
1504
1510
  const kcClient = createKcClient({
1505
1511
  keycloakUrl: opts.keycloakUrl,
1512
+ keycloakInternalUrl: opts.keycloakInternalUrl,
1506
1513
  realm: opts.realm,
1507
1514
  clientId: opts.clientId,
1508
1515
  clientSecret: opts.clientSecret,
@@ -1560,6 +1567,7 @@ var depsCache = /* @__PURE__ */ new WeakMap();
1560
1567
  function depsCacheKey(opts) {
1561
1568
  return JSON.stringify({
1562
1569
  keycloakUrl: opts.keycloakUrl,
1570
+ keycloakInternalUrl: opts.keycloakInternalUrl,
1563
1571
  realm: opts.realm,
1564
1572
  clientId: opts.clientId,
1565
1573
  clientSecret: opts.clientSecret,
@@ -1579,6 +1587,7 @@ async function buildDepsUncached(opts) {
1579
1587
  const refreshStore = createRefreshStore({ db: opts.db, cipher });
1580
1588
  const kcClient = createKcClient({
1581
1589
  keycloakUrl: opts.keycloakUrl,
1590
+ keycloakInternalUrl: opts.keycloakInternalUrl,
1582
1591
  realm: opts.realm,
1583
1592
  clientId: opts.clientId,
1584
1593
  clientSecret: opts.clientSecret,
@@ -1615,156 +1624,6 @@ async function requireAccessTokenFor(opts) {
1615
1624
  return requireAccessToken(await buildDeps(opts));
1616
1625
  }
1617
1626
 
1618
- // src/auth-core/migrate.ts
1619
- import { sql } from "drizzle-orm";
1620
- var MIGRATION_0001_SCHEMA = `
1621
- CREATE SCHEMA IF NOT EXISTS auth;
1622
- `;
1623
- var MIGRATION_0001_TABLES = `
1624
- CREATE TABLE IF NOT EXISTS auth.sessions (
1625
- id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
1626
- user_sub varchar(64) NOT NULL,
1627
- user_email varchar(320),
1628
- organization_id varchar(64),
1629
- organization_alias varchar(255),
1630
- access_token text NOT NULL,
1631
- access_expires_at timestamptz NOT NULL,
1632
- refresh_ct bytea NOT NULL,
1633
- refresh_iv bytea NOT NULL,
1634
- refresh_expires_at timestamptz NOT NULL,
1635
- created_at timestamptz NOT NULL DEFAULT now(),
1636
- updated_at timestamptz NOT NULL DEFAULT now(),
1637
- revoked_at timestamptz
1638
- );
1639
-
1640
- CREATE INDEX IF NOT EXISTS ix_auth_sessions_user_sub
1641
- ON auth.sessions(user_sub) WHERE revoked_at IS NULL;
1642
-
1643
- CREATE TABLE IF NOT EXISTS auth.login_state (
1644
- state varchar(128) PRIMARY KEY,
1645
- code_verifier varchar(255) NOT NULL,
1646
- redirect_path text NOT NULL DEFAULT '/',
1647
- created_at timestamptz NOT NULL DEFAULT now(),
1648
- expires_at timestamptz NOT NULL
1649
- );
1650
-
1651
- CREATE INDEX IF NOT EXISTS ix_auth_login_state_expires
1652
- ON auth.login_state(expires_at);
1653
- `;
1654
- var MIGRATION_0002_ID_TOKEN = `
1655
- ALTER TABLE auth.sessions ADD COLUMN IF NOT EXISTS id_token text;
1656
- `;
1657
- var MIGRATION_0003_FORCED_REAUTH = `
1658
- ALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS forced_reauth boolean NOT NULL DEFAULT false;
1659
- `;
1660
- var MIGRATION_0004_NONCE = `
1661
- ALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS nonce varchar(128);
1662
- `;
1663
- var MIGRATION_0005_RETRIED = `
1664
- ALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS retried boolean NOT NULL DEFAULT false;
1665
- `;
1666
- var MIGRATION_0006_PENDING_CONFIRM = `
1667
- ALTER TABLE auth.sessions
1668
- ADD COLUMN IF NOT EXISTS pending_identity_confirm boolean NOT NULL DEFAULT false;
1669
- `;
1670
- var MIGRATION_0007_EXPECTED_IDENTITY = `
1671
- ALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS expected_sub varchar(64);
1672
- ALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS expected_email varchar(320);
1673
- `;
1674
- async function probe(db, expression) {
1675
- const result = await db.execute(
1676
- sql.raw(`SELECT (${expression}) AS "applied"`)
1677
- );
1678
- return result.rows[0]?.applied === true;
1679
- }
1680
- var schemaExists = (schema) => (db) => probe(db, `EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = '${schema}')`);
1681
- var relationsExist = (...relations) => (db) => {
1682
- const tuples = relations.map(([schema, name]) => `('${schema}','${name}')`).join(", ");
1683
- return probe(
1684
- db,
1685
- `(SELECT count(*) FROM pg_class c
1686
- JOIN pg_namespace n ON n.oid = c.relnamespace
1687
- WHERE (n.nspname, c.relname) IN (${tuples})) = ${relations.length}`
1688
- );
1689
- };
1690
- var columnsExist = (...columns) => (db) => {
1691
- const tuples = columns.map(([schema, table, column]) => `('${schema}','${table}','${column}')`).join(", ");
1692
- return probe(
1693
- db,
1694
- `(SELECT count(*) FROM pg_attribute a
1695
- JOIN pg_class c ON c.oid = a.attrelid
1696
- JOIN pg_namespace n ON n.oid = c.relnamespace
1697
- WHERE a.attnum > 0 AND NOT a.attisdropped
1698
- AND (n.nspname, c.relname, a.attname) IN (${tuples})) = ${columns.length}`
1699
- );
1700
- };
1701
- var MIGRATIONS = [
1702
- {
1703
- name: "0001_init:schema",
1704
- sql: MIGRATION_0001_SCHEMA,
1705
- isApplied: schemaExists("auth")
1706
- },
1707
- {
1708
- name: "0001_init:tables",
1709
- sql: MIGRATION_0001_TABLES,
1710
- isApplied: relationsExist(
1711
- ["auth", "sessions"],
1712
- ["auth", "ix_auth_sessions_user_sub"],
1713
- ["auth", "login_state"],
1714
- ["auth", "ix_auth_login_state_expires"]
1715
- )
1716
- },
1717
- {
1718
- name: "0002_id_token",
1719
- sql: MIGRATION_0002_ID_TOKEN,
1720
- isApplied: columnsExist(["auth", "sessions", "id_token"])
1721
- },
1722
- {
1723
- name: "0003_forced_reauth",
1724
- sql: MIGRATION_0003_FORCED_REAUTH,
1725
- isApplied: columnsExist(["auth", "login_state", "forced_reauth"])
1726
- },
1727
- {
1728
- name: "0004_nonce",
1729
- sql: MIGRATION_0004_NONCE,
1730
- isApplied: columnsExist(["auth", "login_state", "nonce"])
1731
- },
1732
- {
1733
- name: "0005_retried",
1734
- sql: MIGRATION_0005_RETRIED,
1735
- isApplied: columnsExist(["auth", "login_state", "retried"])
1736
- },
1737
- {
1738
- name: "0006_pending_confirm",
1739
- sql: MIGRATION_0006_PENDING_CONFIRM,
1740
- isApplied: columnsExist(["auth", "sessions", "pending_identity_confirm"])
1741
- },
1742
- {
1743
- name: "0007_expected_identity",
1744
- sql: MIGRATION_0007_EXPECTED_IDENTITY,
1745
- isApplied: columnsExist(
1746
- ["auth", "login_state", "expected_sub"],
1747
- ["auth", "login_state", "expected_email"]
1748
- )
1749
- }
1750
- ];
1751
- async function runAuthMigrations(db, opts = {}) {
1752
- for (const migration of MIGRATIONS) {
1753
- try {
1754
- if (await migration.isApplied(db)) {
1755
- continue;
1756
- }
1757
- await db.execute(sql.raw(migration.sql));
1758
- } catch (err) {
1759
- const message = err instanceof Error ? err.message : String(err);
1760
- throw new Error(`auth migration "${migration.name}" failed: ${message}`, { cause: err });
1761
- }
1762
- }
1763
- if (opts.runtimeRole) {
1764
- await grantRuntimeDefaultPrivileges(db, "auth", opts.runtimeRole);
1765
- }
1766
- }
1767
-
1768
1627
  // src/next/auth/permissionGuards.ts
1769
1628
  import { NextResponse as NextResponse2 } from "next/server";
1770
1629
  function makeGuards(map, getPermissions, requireUser = async () => {