@quatronic/sdk 0.7.0-rc.9 → 0.7.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.
@@ -66,21 +66,24 @@ function userDirectory(opts = {}) {
66
66
  const missing = REQUIRED.filter((k) => !env[k]);
67
67
  if (missing.length) throw new Error(`userDirectory(): missing env ${missing.join(", ")}`);
68
68
  const issuer = `${env.KC_URL.replace(/\/+$/, "")}/realms/${env.KC_REALM}`;
69
+ const internal = env.KC_INTERNAL_URL?.trim();
70
+ const serverBase = internal ? `${internal.replace(/\/+$/, "")}/realms/${env.KC_REALM}` : issuer;
69
71
  const clientId = env.KC_CLIENT_ID;
70
72
  const sourceKey = `${issuer}|${clientId}`;
71
- let source = sources.get(sourceKey);
73
+ const sourceMapKey = `${serverBase}|${sourceKey}`;
74
+ let source = sources.get(sourceMapKey);
72
75
  if (!source || opts.fetchImpl) {
73
76
  source = serviceTokenSource({
74
- tokenUrl: `${issuer}/protocol/openid-connect/token`,
77
+ tokenUrl: `${serverBase}/protocol/openid-connect/token`,
75
78
  clientId,
76
79
  clientSecret: env.KC_CLIENT_SECRET,
77
80
  fetchImpl: opts.fetchImpl
78
81
  });
79
- if (!opts.fetchImpl) sources.set(sourceKey, source);
82
+ if (!opts.fetchImpl) sources.set(sourceMapKey, source);
80
83
  }
81
84
  const tokens = source;
82
85
  return createUserDirectory({
83
- baseUrl: `${issuer}/qdc-directory`,
86
+ baseUrl: `${serverBase}/qdc-directory`,
84
87
  getToken: () => tokens.get(),
85
88
  onUnauthorized: () => tokens.invalidate(),
86
89
  cacheScope: sourceKey,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/users-core/serviceToken.ts","../../../src/next/users/index.ts"],"sourcesContent":["import { DirectoryError } from \"./errors\"\n\nconst SKEW_MS = 30_000\n\nexport function serviceTokenSource(cfg: {\n tokenUrl: string\n clientId: string\n clientSecret: string\n fetchImpl?: typeof fetch\n clock?: () => number\n}) {\n const fetchImpl = cfg.fetchImpl ?? fetch\n const clock = cfg.clock ?? Date.now\n let cached: { token: string; refreshAt: number } | undefined\n let inflight: Promise<string> | undefined\n\n async function request(): Promise<string> {\n let res: Response\n try {\n res = await fetchImpl(cfg.tokenUrl, {\n method: \"POST\",\n headers: { \"content-type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n grant_type: \"client_credentials\",\n client_id: cfg.clientId,\n client_secret: cfg.clientSecret,\n }),\n signal: AbortSignal.timeout(10_000),\n })\n } catch (err) {\n throw new DirectoryError(\"unavailable\", `token endpoint unreachable: ${(err as Error).message}`)\n }\n if (res.status === 400 || res.status === 401 || res.status === 403) {\n throw new DirectoryError(\"unauthorized\", `client_credentials refused (${res.status})`)\n }\n if (!res.ok) throw new DirectoryError(\"unavailable\", `token endpoint ${res.status}`)\n let j: { access_token?: unknown; expires_in?: unknown }\n try {\n j = (await res.json()) as typeof j\n } catch (err) {\n throw new DirectoryError(\"unavailable\", `token endpoint returned an unreadable body: ${(err as Error).message}`)\n }\n if (typeof j.access_token !== \"string\" || !j.access_token || typeof j.expires_in !== \"number\" || !Number.isFinite(j.expires_in)) {\n throw new DirectoryError(\"unavailable\", \"token endpoint returned an invalid token response\")\n }\n cached = { token: j.access_token, refreshAt: clock() + j.expires_in * 1000 - SKEW_MS }\n return j.access_token\n }\n\n return {\n async get(): Promise<string> {\n if (cached && clock() < cached.refreshAt) return cached.token\n inflight ??= request().finally(() => {\n inflight = undefined\n })\n return inflight\n },\n invalidate(): void {\n cached = undefined\n },\n }\n}\n","import { createUserDirectory } from \"../../users-core/client\"\nimport { serviceTokenSource } from \"../../users-core/serviceToken\"\nimport type { UserDirectory } from \"../../users-core/types\"\n\nexport type {\n AppUser,\n FormerUser,\n CacheMode,\n ListUsersOptions,\n ListUsersResult,\n UserDirectory,\n} from \"../../users-core/types\"\nexport { DirectoryError, type DirectoryErrorCode } from \"../../users-core/errors\"\n\nconst REQUIRED = [\"KC_URL\", \"KC_REALM\", \"KC_CLIENT_ID\", \"KC_CLIENT_SECRET\"] as const\nconst sources = new Map<string, ReturnType<typeof serviceTokenSource>>()\n\n/** The users of this app (client) in this environment. Server-side only. */\nexport function userDirectory(\n opts: { env?: Record<string, string | undefined>; fetchImpl?: typeof fetch } = {},\n): UserDirectory {\n const env = opts.env ?? (process.env as Record<string, string | undefined>)\n const missing = REQUIRED.filter((k) => !env[k])\n if (missing.length) throw new Error(`userDirectory(): missing env ${missing.join(\", \")}`)\n const issuer = `${env.KC_URL!.replace(/\\/+$/, \"\")}/realms/${env.KC_REALM}`\n const clientId = env.KC_CLIENT_ID!\n const sourceKey = `${issuer}|${clientId}`\n let source = sources.get(sourceKey)\n if (!source || opts.fetchImpl) {\n source = serviceTokenSource({\n tokenUrl: `${issuer}/protocol/openid-connect/token`,\n clientId,\n clientSecret: env.KC_CLIENT_SECRET!,\n fetchImpl: opts.fetchImpl,\n })\n if (!opts.fetchImpl) sources.set(sourceKey, source)\n }\n const tokens = source\n return createUserDirectory({\n baseUrl: `${issuer}/qdc-directory`,\n getToken: () => tokens.get(),\n onUnauthorized: () => tokens.invalidate(),\n cacheScope: sourceKey,\n fetchImpl: opts.fetchImpl,\n })\n}\n"],"mappings":";;;;;;;;AAEA,IAAM,UAAU;AAET,SAAS,mBAAmB,KAMhC;AACD,QAAM,YAAY,IAAI,aAAa;AACnC,QAAM,QAAQ,IAAI,SAAS,KAAK;AAChC,MAAI;AACJ,MAAI;AAEJ,iBAAe,UAA2B;AACxC,QAAI;AACJ,QAAI;AACF,YAAM,MAAM,UAAU,IAAI,UAAU;AAAA,QAClC,QAAQ;AAAA,QACR,SAAS,EAAE,gBAAgB,oCAAoC;AAAA,QAC/D,MAAM,IAAI,gBAAgB;AAAA,UACxB,YAAY;AAAA,UACZ,WAAW,IAAI;AAAA,UACf,eAAe,IAAI;AAAA,QACrB,CAAC;AAAA,QACD,QAAQ,YAAY,QAAQ,GAAM;AAAA,MACpC,CAAC;AAAA,IACH,SAAS,KAAK;AACZ,YA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AAK,IAAI,CAAC,EAAE;AACxF,QAAM,SAAS,GAAG,IAAI,OAAQ,QAAQ,QAAQ,EAAE,CAAC,WAAW,IAAI,QAAQ;AACxE,QAAM,WAAW,IAAI;AACrB,QAAM,YAAY,GAAG,MAAM,IAAI,QAAQ;AACvC,MAAI,SAAS,QAAQ,IAAI,SAAS;AAClC,MAAI,CAAC,UAAU,KAAK,WAAW;AAC7B,aAAS,mBAAmB;AAAA,MAC1B,UAAU,GAAG,MAAM;AAAA,MACnB;AAAA,MACA,cAAc,IAAI;AAAA,MAClB,WAAW,KAAK;AAAA,IAClB,CAAC;AACD,QAAI,CAAC,KAAK,UAAW,SAAQ,IAAI,WAAW,MAAM;AAAA,EACpD;AACA,QAAM,SAAS;AACf,SAAO,oBAAoB;AAAA,IACzB,SAAS,GAAG,MAAM;AAAA,IAClB,UAAU,MAAM,OAAO,IAAI;AAAA,IAC3B,gBAAgB,MAAM,OAAO,WAAW;AAAA,IACxC,YAAY;AAAA,IACZ,WAAW,KAAK;AAAA,EAClB,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../../../src/users-core/serviceToken.ts","../../../src/next/users/index.ts"],"sourcesContent":["import { DirectoryError } from \"./errors\"\n\nconst SKEW_MS = 30_000\n\nexport function serviceTokenSource(cfg: {\n tokenUrl: string\n clientId: string\n clientSecret: string\n fetchImpl?: typeof fetch\n clock?: () => number\n}) {\n const fetchImpl = cfg.fetchImpl ?? fetch\n const clock = cfg.clock ?? Date.now\n let cached: { token: string; refreshAt: number } | undefined\n let inflight: Promise<string> | undefined\n\n async function request(): Promise<string> {\n let res: Response\n try {\n res = await fetchImpl(cfg.tokenUrl, {\n method: \"POST\",\n headers: { \"content-type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n grant_type: \"client_credentials\",\n client_id: cfg.clientId,\n client_secret: cfg.clientSecret,\n }),\n signal: AbortSignal.timeout(10_000),\n })\n } catch (err) {\n throw new DirectoryError(\"unavailable\", `token endpoint unreachable: ${(err as Error).message}`)\n }\n if (res.status === 400 || res.status === 401 || res.status === 403) {\n throw new DirectoryError(\"unauthorized\", `client_credentials refused (${res.status})`)\n }\n if (!res.ok) throw new DirectoryError(\"unavailable\", `token endpoint ${res.status}`)\n let j: { access_token?: unknown; expires_in?: unknown }\n try {\n j = (await res.json()) as typeof j\n } catch (err) {\n throw new DirectoryError(\"unavailable\", `token endpoint returned an unreadable body: ${(err as Error).message}`)\n }\n if (typeof j.access_token !== \"string\" || !j.access_token || typeof j.expires_in !== \"number\" || !Number.isFinite(j.expires_in)) {\n throw new DirectoryError(\"unavailable\", \"token endpoint returned an invalid token response\")\n }\n cached = { token: j.access_token, refreshAt: clock() + j.expires_in * 1000 - SKEW_MS }\n return j.access_token\n }\n\n return {\n async get(): Promise<string> {\n if (cached && clock() < cached.refreshAt) return cached.token\n inflight ??= request().finally(() => {\n inflight = undefined\n })\n return inflight\n },\n invalidate(): void {\n cached = undefined\n },\n }\n}\n","import { createUserDirectory } from \"../../users-core/client\"\nimport { serviceTokenSource } from \"../../users-core/serviceToken\"\nimport type { UserDirectory } from \"../../users-core/types\"\n\nexport type {\n AppUser,\n FormerUser,\n CacheMode,\n ListUsersOptions,\n ListUsersResult,\n UserDirectory,\n} from \"../../users-core/types\"\nexport { DirectoryError, type DirectoryErrorCode } from \"../../users-core/errors\"\n\nconst REQUIRED = [\"KC_URL\", \"KC_REALM\", \"KC_CLIENT_ID\", \"KC_CLIENT_SECRET\"] as const\nconst sources = new Map<string, ReturnType<typeof serviceTokenSource>>()\n\n/** The users of this app (client) in this environment. Server-side only. */\nexport function userDirectory(\n opts: { env?: Record<string, string | undefined>; fetchImpl?: typeof fetch } = {},\n): UserDirectory {\n const env = opts.env ?? (process.env as Record<string, string | undefined>)\n const missing = REQUIRED.filter((k) => !env[k])\n if (missing.length) throw new Error(`userDirectory(): missing env ${missing.join(\", \")}`)\n const issuer = `${env.KC_URL!.replace(/\\/+$/, \"\")}/realms/${env.KC_REALM}`\n // Optional in-cluster address for this server's own HTTP calls; KC_URL stays\n // the issuer. Unset: the public URL is used for both.\n const internal = env.KC_INTERNAL_URL?.trim()\n const serverBase = internal\n ? `${internal.replace(/\\/+$/, \"\")}/realms/${env.KC_REALM}`\n : issuer\n const clientId = env.KC_CLIENT_ID!\n const sourceKey = `${issuer}|${clientId}`\n const sourceMapKey = `${serverBase}|${sourceKey}`\n let source = sources.get(sourceMapKey)\n if (!source || opts.fetchImpl) {\n source = serviceTokenSource({\n tokenUrl: `${serverBase}/protocol/openid-connect/token`,\n clientId,\n clientSecret: env.KC_CLIENT_SECRET!,\n fetchImpl: opts.fetchImpl,\n })\n if (!opts.fetchImpl) sources.set(sourceMapKey, source)\n }\n const tokens = source\n return createUserDirectory({\n baseUrl: `${serverBase}/qdc-directory`,\n getToken: () => tokens.get(),\n onUnauthorized: () => tokens.invalidate(),\n cacheScope: sourceKey,\n fetchImpl: opts.fetchImpl,\n })\n}\n"],"mappings":";;;;;;;;AAEA,IAAM,UAAU;AAET,SAAS,mBAAmB,KAMhC;AACD,QAAM,YAAY,IAAI,aAAa;AACnC,QAAM,QAAQ,IAAI,SAAS,KAAK;AAChC,MAAI;AACJ,MAAI;AAEJ,iBAAe,UAA2B;AACxC,QAAI;AACJ,QAAI;AACF,YAAM,MAAM,UAAU,IAAI,UAAU;AAAA,QAClC,QAAQ;AAAA,QACR,SAAS,EAAE,gBAAgB,oCAAoC;AAAA,QAC/D,MAAM,IAAI,gBAAgB;AAAA,UACxB,YAAY;AAAA,UACZ,WAAW,IAAI;AAAA,UACf,eAAe,IAAI;AAAA,QACrB,CAAC;AAAA,QACD,QAAQ,YAAY,QAAQ,GAAM;AAAA,MACpC,CAAC;AAAA,IACH,SAAS,KAAK;AACZ,YAAM,IAAI,eAAe,eAAe,+BAAgC,IAAc,OAAO,EAAE;AAAA,IACjG;AACA,QAAI,IAAI,WAAW,OAAO,IAAI,WAAW,OAAO,IAAI,WAAW,KAAK;AAClE,YAAM,IAAI,eAAe,gBAAgB,+BAA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a,WACf,GAAG,SAAS,QAAQ,QAAQ,EAAE,CAAC,WAAW,IAAI,QAAQ,KACtD;AACJ,QAAM,WAAW,IAAI;AACrB,QAAM,YAAY,GAAG,MAAM,IAAI,QAAQ;AACvC,QAAM,eAAe,GAAG,UAAU,IAAI,SAAS;AAC/C,MAAI,SAAS,QAAQ,IAAI,YAAY;AACrC,MAAI,CAAC,UAAU,KAAK,WAAW;AAC7B,aAAS,mBAAmB;AAAA,MAC1B,UAAU,GAAG,UAAU;AAAA,MACvB;AAAA,MACA,cAAc,IAAI;AAAA,MAClB,WAAW,KAAK;AAAA,IAClB,CAAC;AACD,QAAI,CAAC,KAAK,UAAW,SAAQ,IAAI,cAAc,MAAM;AAAA,EACvD;AACA,QAAM,SAAS;AACf,SAAO,oBAAoB;AAAA,IACzB,SAAS,GAAG,UAAU;AAAA,IACtB,UAAU,MAAM,OAAO,IAAI;AAAA,IAC3B,gBAAgB,MAAM,OAAO,WAAW;AAAA,IACxC,YAAY;AAAA,IACZ,WAAW,KAAK;AAAA,EAClB,CAAC;AACH;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quatronic/sdk",
3
- "version": "0.7.0-rc.9",
3
+ "version": "0.7.0",
4
4
  "type": "module",
5
5
  "private": false,
6
6
  "publishConfig": {
@@ -47,8 +47,8 @@ No migration; no new table.
47
47
  ## Recipe: Magic link
48
48
 
49
49
  No migration — reuses the `verification` table. Emails go through
50
- `sendEmail` (`src/lib/email`), which logs to the console when
51
- `RESEND_API_KEY` is unset, so it works locally without a mail provider.
50
+ `sendEmail` (`src/lib/email`), which prints the mail to the terminal under
51
+ `pnpm dev` when no mail key is set, so it works locally without a mail provider.
52
52
 
53
53
  1. In `src/lib/auth.ts`: uncomment `// import { magicLink … }` at the top
54
54
  (merge it into the existing `better-auth/plugins` import), then uncomment the
@@ -61,7 +61,8 @@ No migration — reuses the `verification` table. Emails go through
61
61
  needed. Add `magicLinkEmail` to the existing `@/lib/email` import at the
62
62
  top of `src/lib/auth.ts`; the `magicLink({ sendMagicLink … })` block
63
63
  uncommented in step 1 already calls it.
64
- 5. For real email delivery set `RESEND_API_KEY` + `EMAIL_FROM`.
64
+ 5. For real email delivery, link a mail domain to this module in the portal
65
+ (or set `RESEND_API_KEY` + `EMAIL_FROM` for a Resend key of your own).
65
66
  6. Run the check loop.
66
67
 
67
68
  ## Recipe: Two-factor (TOTP)
@@ -56,10 +56,10 @@ Worked example: `docs/examples/mail.example.ts`.
56
56
  ## This is not auth email
57
57
 
58
58
  If this app has Better Auth (`next-betterauth`), verification and magic-link
59
- email already flow through `src/lib/email/send.ts` and its own
60
- `RESEND_API_KEY`/`EMAIL_FROM` — a separate mechanism tied to the portal's
61
- platform sender, not to a per-module linked domain. Don't merge the two;
62
- `sendMail` here is for this module's own business email.
59
+ email already flow through `src/lib/email/send.ts`. It sends over the same
60
+ linked domain (or the app's own `RESEND_API_KEY`/`EMAIL_FROM` when set), but
61
+ with its own templates. Don't route auth email through `sendMail`; `sendMail`
62
+ here is for this module's own business email.
63
63
 
64
64
  ## Ship it
65
65