@stardeck-customer-apps/testing 0.5.1 → 0.6.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/setup.mjs CHANGED
@@ -63,6 +63,14 @@ var TEST_ENV_DEFAULTS = {
63
63
  // src/simulator/hmac.ts
64
64
  import crypto from "crypto";
65
65
  var TIMESTAMP_TOLERANCE_SECONDS = 300;
66
+ function isNonEmptyString(value) {
67
+ return typeof value === "string" && value.length > 0;
68
+ }
69
+ function isDeploymentAuthPayload(value) {
70
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
71
+ const payload = value;
72
+ return payload.type === "deployment-request" && isNonEmptyString(payload.organizationId) && isNonEmptyString(payload.projectId) && isNonEmptyString(payload.deploymentId) && typeof payload.timestamp === "number" && Number.isSafeInteger(payload.timestamp) && isNonEmptyString(payload.nonce);
73
+ }
66
74
  function verifyDeploymentAuthHeader(secret, header) {
67
75
  const dotIndex = header.lastIndexOf(".");
68
76
  if (dotIndex === -1) return null;
@@ -80,16 +88,16 @@ function verifyDeploymentAuthHeader(secret, header) {
80
88
  if (expectedBuf.length !== actualBuf.length || !crypto.timingSafeEqual(expectedBuf, actualBuf)) {
81
89
  return null;
82
90
  }
83
- let payload;
91
+ let parsed;
84
92
  try {
85
- payload = JSON.parse(payloadJson);
93
+ parsed = JSON.parse(payloadJson);
86
94
  } catch {
87
95
  return null;
88
96
  }
89
- if (payload.type !== "deployment-request") return null;
97
+ if (!isDeploymentAuthPayload(parsed)) return null;
90
98
  const now3 = Math.floor(Date.now() / 1e3);
91
- if (Math.abs(now3 - payload.timestamp) > TIMESTAMP_TOLERANCE_SECONDS) return null;
92
- return payload;
99
+ if (Math.abs(now3 - parsed.timestamp) > TIMESTAMP_TOLERANCE_SECONDS) return null;
100
+ return parsed;
93
101
  }
94
102
 
95
103
  // src/simulator/http.ts
@@ -586,16 +594,118 @@ var LINK_KINDS = /* @__PURE__ */ new Set([
586
594
  "project_auth_user",
587
595
  "dashboard_user"
588
596
  ]);
597
+ var RESOLVE_KINDS = /* @__PURE__ */ new Set(["phone", "email", "line"]);
598
+ var E164_PHONE = /^\+[1-9]\d{1,14}$/;
599
+ var SEARCH_DEFAULT_LIMIT = 50;
600
+ var SEARCH_MAX_LIMIT = 100;
601
+ var IdentityGraphError = class extends Error {
602
+ };
589
603
  function now() {
590
604
  return (/* @__PURE__ */ new Date()).toISOString();
591
605
  }
592
606
  function linksFor(identityId) {
593
607
  return state.identityLinks.filter((l) => l.identityId === identityId);
594
608
  }
609
+ function comparableExternalId(kind, externalId) {
610
+ if (kind === "email") return externalId.trim().toLowerCase();
611
+ return externalId;
612
+ }
613
+ function normalizeExternalId(kind, externalId) {
614
+ if (kind === "email") {
615
+ const normalized = externalId.trim().toLowerCase();
616
+ return normalized.length > 0 ? { externalId: normalized } : { error: "externalId is required" };
617
+ }
618
+ if (kind === "phone" && !E164_PHONE.test(externalId)) {
619
+ return { error: "phone externalId must be an E.164 number" };
620
+ }
621
+ return { externalId };
622
+ }
623
+ function normalizeLinkInput(kind, externalId, allowedKinds, kindError) {
624
+ if (typeof kind !== "string" || !allowedKinds.has(kind)) {
625
+ return { error: kindError };
626
+ }
627
+ if (typeof externalId !== "string" || externalId.length === 0) {
628
+ return { error: "externalId is required" };
629
+ }
630
+ const normalized = normalizeExternalId(kind, externalId);
631
+ if ("error" in normalized) return normalized;
632
+ return { kind, externalId: normalized.externalId };
633
+ }
634
+ function normalizeResolveInput(kind, externalId) {
635
+ const normalized = normalizeLinkInput(
636
+ kind,
637
+ externalId,
638
+ RESOLVE_KINDS,
639
+ "kind must be one of: phone, email, line"
640
+ );
641
+ if ("error" in normalized) return normalized;
642
+ return { kind: normalized.kind, externalId: normalized.externalId };
643
+ }
644
+ function canonicalIdentity(identityId) {
645
+ const visited = /* @__PURE__ */ new Set();
646
+ let identity = state.identities.get(identityId);
647
+ while (identity) {
648
+ if (visited.has(identity.id)) {
649
+ throw new IdentityGraphError("identity merge chain contains a cycle");
650
+ }
651
+ visited.add(identity.id);
652
+ if (identity.status === "archived") {
653
+ throw new IdentityGraphError("identity is archived");
654
+ }
655
+ if (identity.status === "active" && !identity.mergedIntoId) {
656
+ return identity;
657
+ }
658
+ if (!identity.mergedIntoId) {
659
+ throw new IdentityGraphError("identity merge chain has no active canonical target");
660
+ }
661
+ identity = state.identities.get(identity.mergedIntoId);
662
+ }
663
+ throw new IdentityGraphError("identity merge chain references a missing identity");
664
+ }
665
+ function matchingLinks(kind, externalId) {
666
+ const comparable = comparableExternalId(kind, externalId);
667
+ return state.identityLinks.filter(
668
+ (link) => link.kind === kind && comparableExternalId(link.kind, link.externalId) === comparable
669
+ );
670
+ }
671
+ function createPerson(displayName) {
672
+ const createdAt = now();
673
+ const identity = {
674
+ id: crypto3.randomUUID(),
675
+ type: "person",
676
+ parentId: null,
677
+ displayName,
678
+ profile: {},
679
+ status: "active",
680
+ mergedIntoId: null,
681
+ externalRef: null,
682
+ createdAt,
683
+ updatedAt: createdAt
684
+ };
685
+ state.identities.set(identity.id, identity);
686
+ return identity;
687
+ }
688
+ function createUnverifiedLink(identityId, kind, externalId) {
689
+ const link = {
690
+ id: crypto3.randomUUID(),
691
+ identityId,
692
+ kind,
693
+ externalId,
694
+ // Deployment credentials can attest provenance, but cannot manufacture a
695
+ // platform-verified fact. Trusted channel/control-plane setup uses the
696
+ // directory's test-only seedVerifiedLink helper instead.
697
+ verified: false,
698
+ createdAt: now()
699
+ };
700
+ state.identityLinks.push(link);
701
+ return link;
702
+ }
595
703
  function handleList(request) {
596
704
  const typeParam = new URL(request.url).searchParams.get("type");
597
705
  const type = typeParam === "person" || typeParam === "account" ? typeParam : void 0;
598
- const identities = [...state.identities.values()];
706
+ const identities = [...state.identities.values()].filter(
707
+ (identity) => identity.status !== "merged"
708
+ );
599
709
  return success({ identities: type ? identities.filter((i) => i.type === type) : identities });
600
710
  }
601
711
  async function handleCreate(request) {
@@ -613,6 +723,7 @@ async function handleCreate(request) {
613
723
  }
614
724
  parentId = parent.id;
615
725
  }
726
+ const createdAt = now();
616
727
  const identity = {
617
728
  id: crypto3.randomUUID(),
618
729
  type,
@@ -622,8 +733,8 @@ async function handleCreate(request) {
622
733
  status: "active",
623
734
  mergedIntoId: null,
624
735
  externalRef: body.externalRef ?? null,
625
- createdAt: now(),
626
- updatedAt: now()
736
+ createdAt,
737
+ updatedAt: createdAt
627
738
  };
628
739
  state.identities.set(identity.id, identity);
629
740
  return success({ identity });
@@ -659,36 +770,166 @@ async function handleAttachLink(identityId, request) {
659
770
  return failure("links attach only to active persons");
660
771
  }
661
772
  const body = await readJsonBody(request);
662
- const kind = body.kind;
663
- const externalId = body.externalId;
664
- if (typeof kind !== "string" || !LINK_KINDS.has(kind)) {
665
- return failure(`kind must be one of: ${[...LINK_KINDS].join(", ")}`);
666
- }
667
- if (typeof externalId !== "string" || !externalId) {
668
- return failure("externalId is required");
669
- }
670
- const existing = state.identityLinks.find((l) => l.kind === kind && l.externalId === externalId);
773
+ const normalized = normalizeLinkInput(
774
+ body.kind,
775
+ body.externalId,
776
+ LINK_KINDS,
777
+ `kind must be one of: ${[...LINK_KINDS].join(", ")}`
778
+ );
779
+ if ("error" in normalized) return failure(normalized.error);
780
+ const { kind, externalId } = normalized;
781
+ const [existing] = matchingLinks(kind, externalId);
671
782
  if (existing) {
672
783
  if (existing.identityId === identityId) return success({ link: existing });
673
784
  return failure("identifier already linked to another identity", 409);
674
785
  }
675
- const link = {
676
- id: crypto3.randomUUID(),
677
- identityId,
678
- kind,
679
- externalId,
680
- verified: body.verified === true,
681
- createdAt: now()
682
- };
683
- state.identityLinks.push(link);
786
+ const link = createUnverifiedLink(identityId, kind, externalId);
684
787
  return success({ link });
685
788
  }
789
+ async function handleResolve(request) {
790
+ const body = await readJsonBody(request);
791
+ const normalized = normalizeResolveInput(body.kind, body.externalId);
792
+ if ("error" in normalized) return failure(normalized.error);
793
+ const provenance = body.provenance;
794
+ if (provenance !== "guest" && provenance !== "staff") {
795
+ return failure("provenance must be 'guest' or 'staff'");
796
+ }
797
+ if (body.displayName !== void 0 && typeof body.displayName !== "string") {
798
+ return failure("displayName must be a string");
799
+ }
800
+ const links = matchingLinks(normalized.kind, normalized.externalId);
801
+ if (links.length > 0) {
802
+ const canonicalIds = /* @__PURE__ */ new Set();
803
+ for (const link of links) {
804
+ try {
805
+ canonicalIds.add(canonicalIdentity(link.identityId).id);
806
+ } catch (error) {
807
+ const message = error instanceof Error ? error.message : "invalid identity merge chain";
808
+ return failure(`cannot resolve identity link: ${message}`, 409);
809
+ }
810
+ }
811
+ if (canonicalIds.size !== 1) {
812
+ return failure("identifier is linked to multiple identities", 409);
813
+ }
814
+ const canonicalId = [...canonicalIds][0];
815
+ const hasVerifiedLink = links.some((link) => link.verified);
816
+ if (provenance === "guest" && hasVerifiedLink) {
817
+ return success({ identityId: null, reason: "verified_conflict" });
818
+ }
819
+ return success({ identityId: canonicalId, created: false });
820
+ }
821
+ const displayName = body.displayName ?? null;
822
+ const identity = createPerson(displayName);
823
+ createUnverifiedLink(identity.id, normalized.kind, normalized.externalId);
824
+ return success({ identityId: identity.id, created: true });
825
+ }
826
+ function encodeSearchCursor(cursor) {
827
+ return Buffer.from(JSON.stringify(cursor), "utf8").toString("base64url");
828
+ }
829
+ function decodeSearchCursor(raw, query) {
830
+ try {
831
+ const rawParsed = JSON.parse(Buffer.from(raw, "base64url").toString("utf8"));
832
+ if (!rawParsed || typeof rawParsed !== "object" || Array.isArray(rawParsed)) return null;
833
+ const parsed = rawParsed;
834
+ if (typeof parsed.createdAt !== "string" || typeof parsed.id !== "string" || typeof parsed.query !== "string" || parsed.query !== query) {
835
+ return null;
836
+ }
837
+ return { createdAt: parsed.createdAt, id: parsed.id, query: parsed.query };
838
+ } catch {
839
+ return null;
840
+ }
841
+ }
842
+ function compareIdentityOrder(left, right) {
843
+ const byCreatedAt = left.createdAt.localeCompare(right.createdAt);
844
+ return byCreatedAt !== 0 ? byCreatedAt : left.id.localeCompare(right.id);
845
+ }
846
+ function identityMatchesQuery(identity, query) {
847
+ if (!query) return true;
848
+ if (identity.displayName?.toLowerCase().includes(query)) return true;
849
+ return state.identityLinks.some(
850
+ (link) => link.identityId === identity.id && comparableExternalId(link.kind, link.externalId).toLowerCase().includes(query)
851
+ );
852
+ }
853
+ function handleSearch(request) {
854
+ const url = new URL(request.url);
855
+ const query = (url.searchParams.get("query") ?? "").trim().toLowerCase();
856
+ const rawLimit = url.searchParams.get("limit");
857
+ let limit = SEARCH_DEFAULT_LIMIT;
858
+ if (rawLimit !== null) {
859
+ if (!/^\d+$/.test(rawLimit)) return failure("limit must be a positive integer");
860
+ limit = Number(rawLimit);
861
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > SEARCH_MAX_LIMIT) {
862
+ return failure(`limit must be between 1 and ${SEARCH_MAX_LIMIT}`);
863
+ }
864
+ }
865
+ const rawCursor = url.searchParams.get("cursor");
866
+ const cursor = rawCursor ? decodeSearchCursor(rawCursor, query) : null;
867
+ if (rawCursor && !cursor) return failure("cursor is invalid");
868
+ const identities = [...state.identities.values()].filter((identity) => identity.status === "active" && identity.mergedIntoId === null).filter((identity) => identityMatchesQuery(identity, query)).sort(compareIdentityOrder);
869
+ const start = cursor ? identities.findIndex((identity) => compareIdentityOrder(identity, cursor) > 0) : 0;
870
+ const pageStart = start < 0 ? identities.length : start;
871
+ const items = identities.slice(pageStart, pageStart + limit);
872
+ const hasMore = pageStart + items.length < identities.length;
873
+ const nextCursor = hasMore ? encodeSearchCursor({
874
+ createdAt: items[items.length - 1].createdAt,
875
+ id: items[items.length - 1].id,
876
+ query
877
+ }) : null;
878
+ return success({ items, nextCursor });
879
+ }
880
+ function aliasesForCanonical(canonicalId) {
881
+ const aliases = [canonicalId];
882
+ for (const identity of state.identities.values()) {
883
+ if (identity.id === canonicalId || identity.status !== "merged") continue;
884
+ try {
885
+ if (canonicalIdentity(identity.id).id === canonicalId) aliases.push(identity.id);
886
+ } catch {
887
+ }
888
+ }
889
+ return aliases;
890
+ }
891
+ async function handleAliases(request) {
892
+ const body = await readJsonBody(request);
893
+ if (!Array.isArray(body.identityIds)) {
894
+ return failure("identityIds must be an array");
895
+ }
896
+ if (body.identityIds.length === 0) {
897
+ return failure("identityIds must not be empty");
898
+ }
899
+ if (body.identityIds.length > 200) {
900
+ return failure("A maximum of 200 identity ids may be requested");
901
+ }
902
+ if (body.identityIds.some((identityId) => typeof identityId !== "string" || identityId.length === 0)) {
903
+ return failure("identityIds must contain non-empty strings");
904
+ }
905
+ const aliases = {};
906
+ for (const identityId of body.identityIds) {
907
+ let canonical;
908
+ try {
909
+ canonical = canonicalIdentity(identityId);
910
+ } catch (error) {
911
+ const message = error instanceof Error ? error.message : "invalid identity merge chain";
912
+ return failure(`cannot expand identity aliases: ${message}`, 409);
913
+ }
914
+ aliases[canonical.id] ??= aliasesForCanonical(canonical.id);
915
+ }
916
+ return success({ aliases });
917
+ }
686
918
  async function handleIdentitiesRequest(request, subPath) {
687
919
  const method = request.method;
688
920
  if (subPath === "" || subPath === "/") {
689
921
  if (method === "GET") return handleList(request);
690
922
  if (method === "POST") return handleCreate(request);
691
923
  }
924
+ if (subPath === "/resolve" && method === "POST") {
925
+ return handleResolve(request);
926
+ }
927
+ if (subPath === "/aliases" && method === "POST") {
928
+ return handleAliases(request);
929
+ }
930
+ if (subPath === "/search" && method === "GET") {
931
+ return handleSearch(request);
932
+ }
692
933
  const linksMatch = subPath.match(/^\/([^/]+)\/links$/);
693
934
  if (linksMatch && method === "POST") {
694
935
  return handleAttachLink(linksMatch[1], request);
@@ -1337,13 +1578,24 @@ function requiresDeploymentHmac(request, url) {
1337
1578
  const edgeMatch = url.pathname.match(/^\/api\/deployments\/[^/]+\/edge(\/.*)?$/);
1338
1579
  return !!(dataStoreMatch || isEmail || identitiesMatch || storeMatch || messagingMatch || edgeMatch);
1339
1580
  }
1581
+ function deploymentIdFromPath(url) {
1582
+ const match = url.pathname.match(/\/api\/deployments\/([^/]+)(?:\/|$)/);
1583
+ if (!match) return null;
1584
+ try {
1585
+ return decodeURIComponent(match[1]);
1586
+ } catch {
1587
+ return match[1];
1588
+ }
1589
+ }
1340
1590
  async function handleSimulatedRequest(request, url) {
1341
1591
  if (url.pathname === "/sql") {
1342
1592
  return handleNeonSql(requireDb(), request);
1343
1593
  }
1344
- const authMatch = url.pathname.match(/^\/api\/deployments\/[^/]+\/auth\/(verify|refresh)$/);
1594
+ const authMatch = url.pathname.match(
1595
+ /^\/api\/deployments\/[^/]+\/auth\/(v2\/verify|verify|refresh)$/
1596
+ );
1345
1597
  if (authMatch) {
1346
- return authMatch[1] === "verify" ? handleAuthVerify(request) : handleAuthRefresh(request);
1598
+ return authMatch[1].endsWith("verify") ? handleAuthVerify(request) : handleAuthRefresh(request);
1347
1599
  }
1348
1600
  const dataStoreMatch = url.pathname.match(/^\/api\/data-stores\/[^/]+(\/.*)?$/);
1349
1601
  const isEmail = url.pathname === "/api/email/send";
@@ -1360,7 +1612,9 @@ async function handleSimulatedRequest(request, url) {
1360
1612
  return failure("Missing authentication header", 401);
1361
1613
  }
1362
1614
  const secret = process.env.DEPLOYMENT_SECRET;
1363
- if (!secret || !verifyDeploymentAuthHeader(secret, authHeader)) {
1615
+ const authPayload = secret ? verifyDeploymentAuthHeader(secret, authHeader) : null;
1616
+ const pathDeploymentId = deploymentIdFromPath(url);
1617
+ if (!authPayload || pathDeploymentId !== null && authPayload.deploymentId !== pathDeploymentId) {
1364
1618
  return failure("Invalid authentication", 401);
1365
1619
  }
1366
1620
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stardeck-customer-apps/testing",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "description": "Vitest test harness for Stardeck customer apps — in-process Postgres (PGlite) plus a control-plane simulator so the real Stardeck SDKs run unmodified in tests",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",