@neetru/sdk 2.1.0 → 2.2.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 (70) hide show
  1. package/CHANGELOG.md +94 -1
  2. package/dist/auth.cjs +156 -7
  3. package/dist/auth.cjs.map +1 -1
  4. package/dist/auth.d.cts +5 -3
  5. package/dist/auth.d.ts +5 -3
  6. package/dist/auth.mjs +156 -8
  7. package/dist/auth.mjs.map +1 -1
  8. package/dist/catalog.cjs.map +1 -1
  9. package/dist/catalog.d.cts +2 -2
  10. package/dist/catalog.d.ts +2 -2
  11. package/dist/catalog.mjs.map +1 -1
  12. package/dist/checkout.cjs.map +1 -1
  13. package/dist/checkout.d.cts +2 -2
  14. package/dist/checkout.d.ts +2 -2
  15. package/dist/checkout.mjs.map +1 -1
  16. package/dist/{collection-ref-BBvTTXoG.d.cts → collection-ref-DqAAhuhX.d.cts} +56 -7
  17. package/dist/{collection-ref-BBvTTXoG.d.ts → collection-ref-DqAAhuhX.d.ts} +56 -7
  18. package/dist/db-react.d.cts +1 -1
  19. package/dist/db-react.d.ts +1 -1
  20. package/dist/db.cjs +29 -7
  21. package/dist/db.cjs.map +1 -1
  22. package/dist/db.d.cts +2 -2
  23. package/dist/db.d.ts +2 -2
  24. package/dist/db.mjs +29 -7
  25. package/dist/db.mjs.map +1 -1
  26. package/dist/entitlements.cjs.map +1 -1
  27. package/dist/entitlements.d.cts +2 -2
  28. package/dist/entitlements.d.ts +2 -2
  29. package/dist/entitlements.mjs.map +1 -1
  30. package/dist/errors.cjs.map +1 -1
  31. package/dist/errors.d.cts +1 -1
  32. package/dist/errors.d.ts +1 -1
  33. package/dist/errors.mjs.map +1 -1
  34. package/dist/index.cjs +172 -21
  35. package/dist/index.cjs.map +1 -1
  36. package/dist/index.d.cts +3 -3
  37. package/dist/index.d.ts +3 -3
  38. package/dist/index.mjs +172 -21
  39. package/dist/index.mjs.map +1 -1
  40. package/dist/mocks.cjs +75 -14
  41. package/dist/mocks.cjs.map +1 -1
  42. package/dist/mocks.d.cts +22 -2
  43. package/dist/mocks.d.ts +22 -2
  44. package/dist/mocks.mjs +75 -14
  45. package/dist/mocks.mjs.map +1 -1
  46. package/dist/notifications.cjs.map +1 -1
  47. package/dist/notifications.d.cts +2 -2
  48. package/dist/notifications.d.ts +2 -2
  49. package/dist/notifications.mjs.map +1 -1
  50. package/dist/react.d.cts +2 -2
  51. package/dist/react.d.ts +2 -2
  52. package/dist/support.cjs.map +1 -1
  53. package/dist/support.d.cts +2 -2
  54. package/dist/support.d.ts +2 -2
  55. package/dist/support.mjs.map +1 -1
  56. package/dist/telemetry.cjs.map +1 -1
  57. package/dist/telemetry.d.cts +2 -2
  58. package/dist/telemetry.d.ts +2 -2
  59. package/dist/telemetry.mjs.map +1 -1
  60. package/dist/{types-B1jylbMC.d.ts → types-CvTje138.d.ts} +46 -2
  61. package/dist/{types-Kmt4y1FQ.d.cts → types-DlDxttiG.d.cts} +46 -2
  62. package/dist/usage.cjs.map +1 -1
  63. package/dist/usage.d.cts +2 -2
  64. package/dist/usage.d.ts +2 -2
  65. package/dist/usage.mjs.map +1 -1
  66. package/dist/webhooks.cjs.map +1 -1
  67. package/dist/webhooks.d.cts +2 -2
  68. package/dist/webhooks.d.ts +2 -2
  69. package/dist/webhooks.mjs.map +1 -1
  70. package/package.json +3 -2
package/CHANGELOG.md CHANGED
@@ -5,13 +5,106 @@ All notable changes to `@neetru/sdk` will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [2.2.0] - 2026-05-25 — **auth.verifyToken — validação server-side de id_token via JWKS [feature]**
9
+
10
+ Fix do bug `bug_a7ef1702680044e3994b74bdccecb2ab` — resolve P0-1 audit security pdv-agiliza.
11
+
12
+ ### Added
13
+
14
+ - **`client.auth.verifyToken(token, options?): Promise<NeetruUser>`** — valida um id_token JWT
15
+ emitido por `auth.neetru.com` server-side, sem round-trip de rede por request. Usa JWKS local
16
+ cacheado (default TTL 1h, configurável via `options.jwksCacheTtlMs`).
17
+
18
+ Erros tipados novos (`NeetruErrorCode`):
19
+ - `token_expired` — `exp` no passado
20
+ - `token_invalid_signature` — assinatura não verificada pela JWKS
21
+ - `token_invalid_audience` — `aud` não bate com o `clientId` extraído do `apiKey`
22
+ - `token_invalid_issuer` — `iss` não é `https://auth.neetru.com`
23
+
24
+ Dependência nova: `jose` (Vercel/Cloudflare-friendly, sem Node nativo).
25
+
26
+ - **`MockAuth.verifyToken(token)`** — decodifica JWT sem verificar assinatura (útil em testes).
27
+ Aceita `__mockVerifyToken(fn)` pra injetar falhas determinísticas.
28
+
29
+ - **`VerifyTokenOptions`** — exportado em `index.ts` pra consumers tiparem as options.
30
+
31
+ ### Usage
32
+
33
+ ```ts
34
+ // Next.js route handler
35
+ import { createNeetruClient } from '@neetru/sdk';
36
+ const client = createNeetruClient({ apiKey: 'nrt_a1b2c3_...', env: 'prod' });
37
+
38
+ export async function POST(req: Request) {
39
+ const token = req.cookies.get('neetru-session')?.value ?? '';
40
+ try {
41
+ const user = await client.auth.verifyToken(token);
42
+ // user.uid, user.email, user.isStaff, user.tenantId disponíveis
43
+ } catch (err) {
44
+ return new Response('Unauthorized', { status: 401 });
45
+ }
46
+ }
47
+ ```
48
+
8
49
  ## [Unreleased]
9
50
 
10
- ### Planned (post-2.0)
51
+ ### Planned (post-2.2)
11
52
  - size-limit budget no CI (<12KB gz core com db namespace).
12
53
  - CDN distribution (`cdn.neetru.com/sdk/v2/`).
13
54
  - Endpoint batch `/api/v1/sdk/telemetry/batch` (substitui drenagem N×1 do `track()` por 1 request).
14
55
 
56
+ ## [2.1.1] - 2026-05-25 — **DbDocRef identity + DbBatchOp discriminated union [patch]**
57
+
58
+ Dois fixes LOW reportados por pdv-agiliza (tickets `bug_97b3f0488d1c49cf8c5f94e5d544289b` + `bug_6aab9adc182640218652a65cdcb71b63`).
59
+ Sem breaking changes — todos os usos de `doc()` existentes continuam funcionando.
60
+
61
+ ### Fixed
62
+
63
+ - **`DbDocRef.id / .path / .collection`** (fix #13, ticket `bug_97b3f0488d1c49cf8c5f94e5d544289b`):
64
+ `DbDocRef` agora expõe três propriedades readonly de identidade:
65
+ - `id: string` — ID do documento dentro da coleção.
66
+ - `path: string` — Caminho completo `"colecao/docId"`.
67
+ - `collection: string` — Nome da coleção parent.
68
+ Análogo ao `DocumentReference.id/.path` do Firestore Web SDK. Elimina a necessidade
69
+ de adaptadores externos que reattachavam `collection + id` manualmente.
70
+ Implementado em `DbCollectionRefImpl.doc()` (offline), `createLazyCollectionRef.doc()`
71
+ (client-db) e `MockDb.doc()` (mocks).
72
+
73
+ - **`DbBatchOp` discriminated union** (fix #14, ticket `bug_6aab9adc182640218652a65cdcb71b63`):
74
+ `DbBatchOp` foi convertido de `interface` opaca (campo `op: 'add'|'set'|'update'|'remove'`
75
+ com `id?`/`data?` opcionais) para **discriminated union** pelo campo `kind`:
76
+ ```ts
77
+ type DbBatchOp<T = Record<string, unknown>> =
78
+ | { kind: 'add'; data: Omit<T, 'id'> }
79
+ | { kind: 'set'; id: string; data: Omit<T, 'id'> }
80
+ | { kind: 'update'; id: string; data: Partial<Omit<T, 'id'>> }
81
+ | { kind: 'remove'; id: string };
82
+ ```
83
+ O `.d.ts` público agora expõe claramente quais campos são obrigatórios por variante.
84
+ O campo `collection` foi removido da operação (sempre opera na coleção do `DbCollectionRef`).
85
+
86
+ ### Migration (2.0.0 → 2.1.1)
87
+
88
+ Callers que usavam `batch()` devem trocar `op` por `kind` e remover o campo `collection`:
89
+
90
+ ```ts
91
+ // antes (2.0.0)
92
+ col.batch([
93
+ { op: 'add', collection: 'orders', data: { total: 10 } },
94
+ { op: 'set', collection: 'orders', id: 'x', data: { total: 20 } },
95
+ { op: 'update', collection: 'orders', id: 'y', data: { total: 30 } },
96
+ { op: 'remove', collection: 'orders', id: 'z' },
97
+ ]);
98
+
99
+ // depois (2.1.1)
100
+ col.batch([
101
+ { kind: 'add', data: { total: 10 } },
102
+ { kind: 'set', id: 'x', data: { total: 20 } },
103
+ { kind: 'update', id: 'y', data: { total: 30 } },
104
+ { kind: 'remove', id: 'z' },
105
+ ]);
106
+ ```
107
+
15
108
  ## [2.0.0] - 2026-05-22 — **client.db NeetruDb (Documentos engine-aware + SQL) [M2]**
16
109
 
17
110
  Major bump — breaking changes no namespace `db`. Liga todos os building blocks M2 na superfície pública.
package/dist/auth.cjs CHANGED
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ var jose = require('jose');
3
4
  var idb = require('idb');
4
5
 
5
6
  var __defProp = Object.defineProperty;
@@ -2956,10 +2957,9 @@ var DbCollectionRefImpl = class {
2956
2957
  const batchId = `batch-${Date.now()}-${Math.random().toString(36).slice(2)}`;
2957
2958
  const busChanges = [];
2958
2959
  for (const op of ops) {
2959
- const id = op.id ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`;
2960
- const data = op.data ?? {};
2961
- const collection = op.collection;
2962
- if (op.op === "add") {
2960
+ const collection = this._collection;
2961
+ if (op.kind === "add") {
2962
+ const data = op.data;
2963
2963
  const mutation = await this._queue.enqueue({
2964
2964
  collection,
2965
2965
  op: "add",
@@ -2983,7 +2983,9 @@ var DbCollectionRefImpl = class {
2983
2983
  }
2984
2984
  });
2985
2985
  busChanges.push({ type: "added", collection, doc: { id: docId, data } });
2986
- } else if (op.op === "set") {
2986
+ } else if (op.kind === "set") {
2987
+ const id = op.id;
2988
+ const data = op.data;
2987
2989
  const existing = await this._store.getDoc(collection, id);
2988
2990
  const mutation = await this._queue.enqueue({
2989
2991
  collection,
@@ -3012,7 +3014,9 @@ var DbCollectionRefImpl = class {
3012
3014
  collection,
3013
3015
  doc: { id, data }
3014
3016
  });
3015
- } else if (op.op === "update") {
3017
+ } else if (op.kind === "update") {
3018
+ const id = op.id;
3019
+ const data = op.data;
3016
3020
  const existing = await this._store.getDoc(collection, id);
3017
3021
  const merged = { ...existing?.data ?? {}, ...data };
3018
3022
  const mutation = await this._queue.enqueue({
@@ -3041,7 +3045,8 @@ var DbCollectionRefImpl = class {
3041
3045
  }
3042
3046
  });
3043
3047
  busChanges.push({ type: "modified", collection, doc: { id, data: merged } });
3044
- } else if (op.op === "remove") {
3048
+ } else if (op.kind === "remove") {
3049
+ const id = op.id;
3045
3050
  const existing = await this._store.getDoc(collection, id);
3046
3051
  await this._queue.enqueue({
3047
3052
  collection,
@@ -3150,6 +3155,15 @@ var DbCollectionRefImpl = class {
3150
3155
  assertValidId(id);
3151
3156
  const self = this;
3152
3157
  return {
3158
+ get id() {
3159
+ return id;
3160
+ },
3161
+ get path() {
3162
+ return `${self._collection}/${id}`;
3163
+ },
3164
+ get collection() {
3165
+ return self._collection;
3166
+ },
3153
3167
  async get() {
3154
3168
  return self._buildGetResult(id);
3155
3169
  },
@@ -4283,6 +4297,15 @@ function createLazyCollectionRef(name, getDocsPromise) {
4283
4297
  },
4284
4298
  doc(id) {
4285
4299
  return {
4300
+ get id() {
4301
+ return id;
4302
+ },
4303
+ get path() {
4304
+ return `${name}/${id}`;
4305
+ },
4306
+ get collection() {
4307
+ return name;
4308
+ },
4286
4309
  async get() {
4287
4310
  return (await getRef()).doc(id).get();
4288
4311
  },
@@ -4823,6 +4846,61 @@ var MockAuth = class {
4823
4846
  this._listeners.delete(listener);
4824
4847
  };
4825
4848
  }
4849
+ /**
4850
+ * Mock de `verifyToken` — decodifica o JWT sem verificar assinatura (pra testes).
4851
+ * Em dev, retorna o user atual do mock se já estiver logado. Aceita qualquer token
4852
+ * não-vazio sem chamar rede.
4853
+ *
4854
+ * Para simular falhas em testes, use `MockAuth.__mockVerifyToken(fn)`.
4855
+ */
4856
+ async verifyToken(token) {
4857
+ if (this._verifyTokenOverride) {
4858
+ return this._verifyTokenOverride(token);
4859
+ }
4860
+ if (!token) {
4861
+ throw Object.assign(new Error("Token inv\xE1lido"), { code: "token_invalid_signature" });
4862
+ }
4863
+ try {
4864
+ const parts = token.split(".");
4865
+ if (parts.length === 3) {
4866
+ const b64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
4867
+ const pad = "=".repeat((4 - b64.length % 4) % 4);
4868
+ const decoded = JSON.parse(
4869
+ typeof atob === "function" ? atob(b64 + pad) : Buffer.from(b64 + pad, "base64").toString("utf-8")
4870
+ );
4871
+ if (typeof decoded.sub === "string") {
4872
+ return {
4873
+ uid: decoded.sub,
4874
+ email: typeof decoded.email === "string" ? decoded.email : "",
4875
+ emailVerified: typeof decoded.email_verified === "boolean" ? decoded.email_verified : void 0,
4876
+ displayName: typeof decoded.name === "string" ? decoded.name : void 0,
4877
+ photoURL: typeof decoded.picture === "string" ? decoded.picture : void 0,
4878
+ isStaff: decoded.is_staff === true,
4879
+ isCustomer: decoded.is_customer === true,
4880
+ tenantId: typeof decoded.tenant_id === "string" ? decoded.tenant_id : void 0,
4881
+ ...decoded
4882
+ };
4883
+ }
4884
+ }
4885
+ } catch {
4886
+ }
4887
+ if (this._user) return this._user;
4888
+ throw Object.assign(new Error("Nenhum user mock dispon\xEDvel"), { code: "token_invalid_signature" });
4889
+ }
4890
+ _verifyTokenOverride = null;
4891
+ /**
4892
+ * Injeta override pra `verifyToken` em testes — permite simular expiração,
4893
+ * assinatura inválida etc sem precisar de JWT real.
4894
+ *
4895
+ * @example
4896
+ * ```ts
4897
+ * const mock = new MockAuth(null);
4898
+ * mock.__mockVerifyToken(async () => { throw new NeetruError('token_expired', '...'); });
4899
+ * ```
4900
+ */
4901
+ __mockVerifyToken(fn) {
4902
+ this._verifyTokenOverride = fn;
4903
+ }
4826
4904
  /** Helper de tests — força um user state arbitrário. */
4827
4905
  __setUser(user) {
4828
4906
  this._user = user;
@@ -4996,6 +5074,37 @@ function resolveEnv(configEnv) {
4996
5074
  }
4997
5075
  return "prod";
4998
5076
  }
5077
+ var _jwksCache = /* @__PURE__ */ new Map();
5078
+ var DEFAULT_JWKS_TTL_MS = 60 * 60 * 1e3;
5079
+ function _getJwks(jwksUrl, cacheTtlMs) {
5080
+ const now = Date.now();
5081
+ const cached = _jwksCache.get(jwksUrl);
5082
+ if (cached && now - cached.createdAt < cacheTtlMs) {
5083
+ return cached.jwks;
5084
+ }
5085
+ const jwks = jose.createRemoteJWKSet(new URL(jwksUrl));
5086
+ _jwksCache.set(jwksUrl, { jwks, createdAt: now });
5087
+ return jwks;
5088
+ }
5089
+ function __resetJwksCacheForTests() {
5090
+ _jwksCache.clear();
5091
+ }
5092
+ function _jwtPayloadToUser(payload) {
5093
+ const sub = payload.sub ?? "";
5094
+ const email = typeof payload.email === "string" ? payload.email : "";
5095
+ return {
5096
+ uid: sub,
5097
+ email,
5098
+ emailVerified: typeof payload.email_verified === "boolean" ? payload.email_verified : void 0,
5099
+ displayName: typeof payload.name === "string" ? payload.name : void 0,
5100
+ photoURL: typeof payload.picture === "string" ? payload.picture : void 0,
5101
+ isStaff: payload.is_staff === true,
5102
+ isCustomer: payload.is_customer === true,
5103
+ tenantId: typeof payload.tenant_id === "string" ? payload.tenant_id : void 0,
5104
+ // Spreads todos os claims originais (aud, iss, iat, exp, etc).
5105
+ ...payload
5106
+ };
5107
+ }
4999
5108
  function createOidcAuthNamespace(config) {
5000
5109
  const STORAGE_KEY = "neetru_id_token";
5001
5110
  const listeners = /* @__PURE__ */ new Set();
@@ -5103,6 +5212,45 @@ function createOidcAuthNamespace(config) {
5103
5212
  return () => {
5104
5213
  listeners.delete(listener);
5105
5214
  };
5215
+ },
5216
+ async verifyToken(token, options) {
5217
+ if (!token || typeof token !== "string") {
5218
+ throw new NeetruError("token_invalid_signature", "token must be a non-empty string");
5219
+ }
5220
+ const overrideAuthUrl = typeof globalThis.NEETRU_AUTH_URL === "string" ? globalThis.NEETRU_AUTH_URL : null;
5221
+ const idpOrigin = overrideAuthUrl ?? config.baseUrl.replace(/^https?:\/\/api\./, "https://auth.");
5222
+ const issuer = idpOrigin;
5223
+ const jwksUrl = `${idpOrigin}/api/v1/oauth/.well-known/jwks.json`;
5224
+ const cacheTtlMs = options?.jwksCacheTtlMs ?? DEFAULT_JWKS_TTL_MS;
5225
+ const audience = config.apiKey ? config.apiKey.split("_")[1] ?? void 0 : void 0;
5226
+ const jwks = _getJwks(jwksUrl, cacheTtlMs);
5227
+ try {
5228
+ const { payload } = await jose.jwtVerify(token, jwks, {
5229
+ issuer,
5230
+ ...audience ? { audience } : {},
5231
+ algorithms: ["RS256"]
5232
+ });
5233
+ return _jwtPayloadToUser(payload);
5234
+ } catch (err) {
5235
+ const errName = err?.code ?? err?.name ?? "";
5236
+ const errMsg = err?.message ?? String(err);
5237
+ if (errName === "ERR_JWT_EXPIRED") {
5238
+ throw new NeetruError("token_expired", `Token expired: ${errMsg}`);
5239
+ }
5240
+ if (errName === "ERR_JWS_SIGNATURE_VERIFICATION_FAILED") {
5241
+ throw new NeetruError("token_invalid_signature", `Token signature invalid: ${errMsg}`);
5242
+ }
5243
+ if (errName === "ERR_JWT_CLAIM_VALIDATION_FAILED") {
5244
+ if (errMsg.includes('"aud"') || errMsg.includes("audience")) {
5245
+ throw new NeetruError("token_invalid_audience", `Token audience mismatch: ${errMsg}`);
5246
+ }
5247
+ if (errMsg.includes('"iss"') || errMsg.includes("issuer")) {
5248
+ throw new NeetruError("token_invalid_issuer", `Token issuer mismatch: ${errMsg}`);
5249
+ }
5250
+ throw new NeetruError("token_invalid_signature", `Token claim validation failed: ${errMsg}`);
5251
+ }
5252
+ throw new NeetruError("token_invalid_signature", `Token verification failed: ${errMsg}`);
5253
+ }
5106
5254
  }
5107
5255
  };
5108
5256
  }
@@ -5149,6 +5297,7 @@ function createNeetruClient(config = {}) {
5149
5297
  return client;
5150
5298
  }
5151
5299
 
5300
+ exports.__resetJwksCacheForTests = __resetJwksCacheForTests;
5152
5301
  exports.createNeetruClient = createNeetruClient;
5153
5302
  //# sourceMappingURL=auth.cjs.map
5154
5303
  //# sourceMappingURL=auth.cjs.map