@proofchain/sdk 2.17.0 → 2.19.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/dist/index.mjs CHANGED
@@ -1559,6 +1559,71 @@ var RewardsClient = class {
1559
1559
  async listAssets(definitionId) {
1560
1560
  return this.http.get(`/rewards/definitions/${definitionId}/assets`);
1561
1561
  }
1562
+ // ---------------------------------------------------------------------------
1563
+ // Reward Attestations
1564
+ // ---------------------------------------------------------------------------
1565
+ /**
1566
+ * Create a signed attestation for an earned reward.
1567
+ *
1568
+ * Binds the reward to the user's wallet with an EIP-712 signature.
1569
+ * The anchoring mode is determined by the reward definition or tenant config.
1570
+ *
1571
+ * @param earnedRewardId - The earned reward ID to attest
1572
+ * @returns The attestation details including signature and on-chain status
1573
+ *
1574
+ * @example
1575
+ * ```ts
1576
+ * const attestation = await client.rewards.attest('earned-reward-id');
1577
+ * console.log(attestation.attestation_uid, attestation.status);
1578
+ * ```
1579
+ */
1580
+ async attest(earnedRewardId) {
1581
+ return this.http.post(`/rewards/earned/${earnedRewardId}/attest`, {});
1582
+ }
1583
+ /**
1584
+ * Anchor an earned reward's attestation on-chain (on-demand).
1585
+ *
1586
+ * The reward must already have a signed attestation.
1587
+ * Writes the attestation hash to the Base blockchain contract.
1588
+ *
1589
+ * @param earnedRewardId - The earned reward ID whose attestation to anchor
1590
+ *
1591
+ * @example
1592
+ * ```ts
1593
+ * const result = await client.rewards.anchor('earned-reward-id');
1594
+ * console.log('Anchored on-chain:', result.tx_hash);
1595
+ * ```
1596
+ */
1597
+ async anchor(earnedRewardId) {
1598
+ return this.http.post(`/rewards/earned/${earnedRewardId}/anchor`, {});
1599
+ }
1600
+ /**
1601
+ * Get the attestation for an earned reward.
1602
+ *
1603
+ * @param earnedRewardId - The earned reward ID
1604
+ */
1605
+ async getAttestation(earnedRewardId) {
1606
+ return this.http.get(`/rewards/earned/${earnedRewardId}/attestation`);
1607
+ }
1608
+ /**
1609
+ * Verify a reward attestation's signature and on-chain status.
1610
+ *
1611
+ * @param earnedRewardId - The earned reward ID to verify
1612
+ *
1613
+ * @example
1614
+ * ```ts
1615
+ * const result = await client.rewards.verifyAttestation('earned-reward-id');
1616
+ * if (result.is_valid) {
1617
+ * console.log('Reward is cryptographically verified!');
1618
+ * if (result.on_chain) {
1619
+ * console.log('Also anchored on Base:', result.tx_hash);
1620
+ * }
1621
+ * }
1622
+ * ```
1623
+ */
1624
+ async verifyAttestation(earnedRewardId) {
1625
+ return this.http.get(`/rewards/earned/${earnedRewardId}/verify`);
1626
+ }
1562
1627
  };
1563
1628
 
1564
1629
  // src/quests.ts
@@ -2097,6 +2162,7 @@ var FanpassLeaderboardClient = class {
2097
2162
  // src/notifications.ts
2098
2163
  var NotificationsClient = class {
2099
2164
  constructor(http) {
2165
+ this.http = http;
2100
2166
  this.baseUrl = http.baseUrl || "https://api.proofchain.co.za";
2101
2167
  this.authHeaders = () => {
2102
2168
  const headers = {};
@@ -2187,6 +2253,312 @@ var NotificationsClient = class {
2187
2253
  }
2188
2254
  };
2189
2255
  }
2256
+ // ===========================================================================
2257
+ // WEB PUSH (OS-level notifications, even when browser is closed)
2258
+ // ===========================================================================
2259
+ /**
2260
+ * Get the tenant's VAPID public key for Web Push.
2261
+ *
2262
+ * This key is needed to call `pushManager.subscribe()` in the browser.
2263
+ * Returns null if Web Push is not configured for this tenant.
2264
+ */
2265
+ async getVapidKey() {
2266
+ try {
2267
+ const res = await this.http.get("/notifications/push/vapid-key");
2268
+ return res.vapid_public_key;
2269
+ } catch {
2270
+ return null;
2271
+ }
2272
+ }
2273
+ /**
2274
+ * Register a browser push subscription with the server.
2275
+ *
2276
+ * Call this after the user grants notification permission and you
2277
+ * obtain a PushSubscription from `pushManager.subscribe()`.
2278
+ *
2279
+ * @param userId - External user ID
2280
+ * @param subscription - The PushSubscription object (or its JSON)
2281
+ * @returns Subscription ID from the server
2282
+ */
2283
+ async registerPush(userId, subscription) {
2284
+ const json = "toJSON" in subscription ? subscription.toJSON() : subscription;
2285
+ return this.http.post(
2286
+ "/notifications/push/subscribe",
2287
+ {
2288
+ user_id: userId,
2289
+ endpoint: json.endpoint,
2290
+ keys: json.keys,
2291
+ user_agent: typeof navigator !== "undefined" ? navigator.userAgent : void 0
2292
+ }
2293
+ );
2294
+ }
2295
+ /**
2296
+ * Remove a push subscription from the server.
2297
+ *
2298
+ * Call this when the user logs out or revokes notification permission.
2299
+ *
2300
+ * @param userId - External user ID
2301
+ * @param endpoint - The push endpoint URL to remove
2302
+ */
2303
+ async unregisterPush(userId, endpoint) {
2304
+ return this.http.post(
2305
+ "/notifications/push/unsubscribe",
2306
+ { user_id: userId, endpoint }
2307
+ );
2308
+ }
2309
+ /**
2310
+ * High-level helper: request permission, subscribe to push, and register.
2311
+ *
2312
+ * Handles the full Web Push registration flow:
2313
+ * 1. Fetches the VAPID public key from the server
2314
+ * 2. Requests notification permission from the user
2315
+ * 3. Registers a Service Worker (if not already registered)
2316
+ * 4. Subscribes to push via the Push API
2317
+ * 5. Sends the subscription to the server
2318
+ *
2319
+ * @param userId - External user ID
2320
+ * @param serviceWorkerPath - Path to the service worker file (default: '/sw.js')
2321
+ * @returns The PushSubscription, or null if denied/unavailable
2322
+ *
2323
+ * @example
2324
+ * ```typescript
2325
+ * const sub = await client.notifications.requestPermissionAndSubscribe(
2326
+ * 'user-123',
2327
+ * '/proofchain-sw.js'
2328
+ * );
2329
+ * if (sub) {
2330
+ * console.log('Push notifications enabled!');
2331
+ * }
2332
+ * ```
2333
+ */
2334
+ async requestPermissionAndSubscribe(userId, serviceWorkerPath = "/sw.js") {
2335
+ if (typeof window === "undefined" || !("serviceWorker" in navigator) || !("PushManager" in window)) {
2336
+ console.warn("Web Push is not supported in this browser");
2337
+ return null;
2338
+ }
2339
+ const vapidKey = await this.getVapidKey();
2340
+ if (!vapidKey) {
2341
+ console.warn("Web Push not configured for this tenant");
2342
+ return null;
2343
+ }
2344
+ const permission = await Notification.requestPermission();
2345
+ if (permission !== "granted") {
2346
+ console.warn("Notification permission denied");
2347
+ return null;
2348
+ }
2349
+ const registration = await navigator.serviceWorker.register(serviceWorkerPath);
2350
+ await navigator.serviceWorker.ready;
2351
+ const applicationServerKey = this._urlBase64ToUint8Array(vapidKey);
2352
+ const pushSubscription = await registration.pushManager.subscribe({
2353
+ userVisibleOnly: true,
2354
+ applicationServerKey: applicationServerKey.buffer
2355
+ });
2356
+ await this.registerPush(userId, pushSubscription);
2357
+ return pushSubscription;
2358
+ }
2359
+ /**
2360
+ * Generate a basic Service Worker script for handling push notifications.
2361
+ *
2362
+ * Returns JavaScript source code that can be saved as your sw.js file.
2363
+ * The generated worker handles `push` events (shows notification) and
2364
+ * `notificationclick` events (opens the app).
2365
+ *
2366
+ * @param defaultIcon - Optional default icon URL for notifications
2367
+ * @param defaultUrl - URL to open when notification is clicked (default: '/')
2368
+ * @returns Service Worker JavaScript source code as a string
2369
+ *
2370
+ * @example
2371
+ * ```typescript
2372
+ * // Save the output as /public/sw.js in your project
2373
+ * const swCode = client.notifications.generateServiceWorker({
2374
+ * defaultIcon: '/icon-192.png',
2375
+ * defaultUrl: '/',
2376
+ * });
2377
+ * ```
2378
+ */
2379
+ generateServiceWorker(options = {}) {
2380
+ const { defaultIcon = "/icon-192.png", defaultUrl = "/" } = options;
2381
+ return `// ProofChain Push Notification Service Worker
2382
+ // Auto-generated \u2014 place this file at the root of your public directory
2383
+
2384
+ self.addEventListener('push', function(event) {
2385
+ if (!event.data) return;
2386
+
2387
+ let payload;
2388
+ try {
2389
+ payload = event.data.json();
2390
+ } catch (e) {
2391
+ payload = { title: 'Notification', body: event.data.text() };
2392
+ }
2393
+
2394
+ const options = {
2395
+ body: payload.body || '',
2396
+ icon: payload.icon || '${defaultIcon}',
2397
+ badge: payload.badge || '${defaultIcon}',
2398
+ data: {
2399
+ url: payload.url || '${defaultUrl}',
2400
+ ...payload.data,
2401
+ },
2402
+ tag: payload.data?.event || 'proofchain',
2403
+ renotify: true,
2404
+ };
2405
+
2406
+ event.waitUntil(
2407
+ self.registration.showNotification(payload.title || 'Notification', options)
2408
+ );
2409
+ });
2410
+
2411
+ self.addEventListener('notificationclick', function(event) {
2412
+ event.notification.close();
2413
+ const url = event.notification.data?.url || '${defaultUrl}';
2414
+
2415
+ event.waitUntil(
2416
+ clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function(clientList) {
2417
+ // Focus existing tab if open
2418
+ for (const client of clientList) {
2419
+ if (client.url === url && 'focus' in client) {
2420
+ return client.focus();
2421
+ }
2422
+ }
2423
+ // Otherwise open new tab
2424
+ return clients.openWindow(url);
2425
+ })
2426
+ );
2427
+ });
2428
+ `;
2429
+ }
2430
+ /** Convert a base64url-encoded VAPID key to a Uint8Array for the Push API. */
2431
+ _urlBase64ToUint8Array(base64String) {
2432
+ const padding = "=".repeat((4 - base64String.length % 4) % 4);
2433
+ const base64 = (base64String + padding).replace(/-/g, "+").replace(/_/g, "/");
2434
+ const rawData = atob(base64);
2435
+ const outputArray = new Uint8Array(rawData.length);
2436
+ for (let i = 0; i < rawData.length; ++i) {
2437
+ outputArray[i] = rawData.charCodeAt(i);
2438
+ }
2439
+ return outputArray;
2440
+ }
2441
+ };
2442
+
2443
+ // src/credentials.ts
2444
+ var CredentialsClient = class {
2445
+ constructor(http) {
2446
+ this.http = http;
2447
+ }
2448
+ // ---------------------------------------------------------------------------
2449
+ // Credential Types
2450
+ // ---------------------------------------------------------------------------
2451
+ /**
2452
+ * Create a new credential type
2453
+ */
2454
+ async createType(request) {
2455
+ return this.http.post("/credentials/types", request);
2456
+ }
2457
+ /**
2458
+ * List credential types
2459
+ */
2460
+ async listTypes(options) {
2461
+ return this.http.get("/credentials/types", {
2462
+ status: options?.status,
2463
+ category: options?.category
2464
+ });
2465
+ }
2466
+ /**
2467
+ * Get a specific credential type
2468
+ */
2469
+ async getType(typeId) {
2470
+ return this.http.get(`/credentials/types/${typeId}`);
2471
+ }
2472
+ /**
2473
+ * Update a credential type
2474
+ */
2475
+ async updateType(typeId, request) {
2476
+ return this.http.put(`/credentials/types/${typeId}`, request);
2477
+ }
2478
+ /**
2479
+ * Activate a credential type
2480
+ */
2481
+ async activateType(typeId) {
2482
+ return this.http.post(`/credentials/types/${typeId}/activate`, {});
2483
+ }
2484
+ /**
2485
+ * Archive a credential type
2486
+ */
2487
+ async archiveType(typeId) {
2488
+ return this.http.post(`/credentials/types/${typeId}/archive`, {});
2489
+ }
2490
+ // ---------------------------------------------------------------------------
2491
+ // Credential Issuance
2492
+ // ---------------------------------------------------------------------------
2493
+ /**
2494
+ * Issue a credential to a user
2495
+ */
2496
+ async issue(request) {
2497
+ return this.http.post("/credentials/issue", request);
2498
+ }
2499
+ /**
2500
+ * List issued credentials
2501
+ */
2502
+ async listIssued(options) {
2503
+ return this.http.get("/credentials/issued", {
2504
+ user_id: options?.user_id,
2505
+ credential_type_id: options?.credential_type_id,
2506
+ status: options?.status,
2507
+ limit: options?.limit,
2508
+ offset: options?.offset
2509
+ });
2510
+ }
2511
+ /**
2512
+ * Revoke an issued credential
2513
+ */
2514
+ async revoke(credentialId, reason) {
2515
+ const params = reason ? `?reason=${encodeURIComponent(reason)}` : "";
2516
+ return this.http.post(`/credentials/issued/${credentialId}/revoke${params}`, {});
2517
+ }
2518
+ /**
2519
+ * Suspend an issued credential
2520
+ */
2521
+ async suspend(credentialId, reason) {
2522
+ const params = reason ? `?reason=${encodeURIComponent(reason)}` : "";
2523
+ return this.http.post(`/credentials/issued/${credentialId}/suspend${params}`, {});
2524
+ }
2525
+ /**
2526
+ * Reinstate a suspended credential
2527
+ */
2528
+ async reinstate(credentialId) {
2529
+ return this.http.post(`/credentials/issued/${credentialId}/reinstate`, {});
2530
+ }
2531
+ // ---------------------------------------------------------------------------
2532
+ // User Management
2533
+ // ---------------------------------------------------------------------------
2534
+ /**
2535
+ * Opt a user in to identity credentials (tenant admin)
2536
+ */
2537
+ async optInUser(userExternalId) {
2538
+ return this.http.post(`/credentials/opt-in/${userExternalId}`, {});
2539
+ }
2540
+ /**
2541
+ * Opt a user out of identity credentials (tenant admin)
2542
+ */
2543
+ async optOutUser(userExternalId) {
2544
+ return this.http.post(`/credentials/opt-out/${userExternalId}`, {});
2545
+ }
2546
+ /**
2547
+ * Get all credentials for a user
2548
+ */
2549
+ async getUserCredentials(userExternalId) {
2550
+ return this.http.get(`/credentials/user/${userExternalId}`);
2551
+ }
2552
+ // ---------------------------------------------------------------------------
2553
+ // Public Verification (no auth needed)
2554
+ // ---------------------------------------------------------------------------
2555
+ /**
2556
+ * Verify a credential by its verification code.
2557
+ * This is a public endpoint — no authentication required.
2558
+ */
2559
+ async verify(verificationCode) {
2560
+ return this.http.get(`/credentials/verify/${verificationCode}`);
2561
+ }
2190
2562
  };
2191
2563
 
2192
2564
  // src/client.ts
@@ -2487,6 +2859,7 @@ var ProofChain = class _ProofChain {
2487
2859
  this.cohorts = new CohortLeaderboardClient(this.http);
2488
2860
  this.fanpassLeaderboard = new FanpassLeaderboardClient(this.http);
2489
2861
  this.notifications = new NotificationsClient(this.http);
2862
+ this.credentials = new CredentialsClient(this.http);
2490
2863
  }
2491
2864
  /**
2492
2865
  * Create a client for end-user JWT authentication (PWA/frontend use).
@@ -2820,6 +3193,7 @@ export {
2820
3193
  CertificatesResource,
2821
3194
  ChannelsResource,
2822
3195
  CohortLeaderboardClient,
3196
+ CredentialsClient,
2823
3197
  DataViewsClient,
2824
3198
  DocumentsResource,
2825
3199
  EndUserIngestionClient,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@proofchain/sdk",
3
- "version": "2.17.0",
3
+ "version": "2.19.0",
4
4
  "description": "Official JavaScript/TypeScript SDK for ProofChain - blockchain-anchored document attestation",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",