@clavis.nexus/setup 2.0.0 → 3.0.1

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.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- /** App が新しい接続を受け付ける地域の単位です。この順に並べて保存します。 */
1
+ /** The regions an app accepts new connections from. They are stored in this order. */
2
2
  declare const APP_REGIONS: readonly ["JP", "US", "GB", "EEA"];
3
3
  type AppRegion = (typeof APP_REGIONS)[number];
4
4
 
@@ -18,17 +18,15 @@ type DevelopersSession = {
18
18
  expiresAt?: number;
19
19
  };
20
20
  /**
21
- * 本人向けの受領(`receipt@1`)。文型に Passkey で署名したものを Clavis が受け付けた副署です。
22
- * Org の手続の本文に `receipt` として渡します。
21
+ * A holder receipt (`receipt@1`): Clavis's countersignature that it accepted a statement signed with
22
+ * a passkey. Pass it as `receipt` in the body of an Org step.
23
23
  */
24
- type Receipt = {
25
- type: "receipt@1";
26
- statement: {
27
- type: string;
28
- [field: string]: unknown;
29
- };
30
- [key: string]: unknown;
31
- };
24
+ /**
25
+ * A holder receipt (`receipt@1`). Carry it as the JSON string Clavis returned and pass it on to where
26
+ * it is consumed, the Org API, without parsing it. To read what it holds, give it to the verifier,
27
+ * `createVerifier` in `@clavis.nexus/app`.
28
+ */
29
+ type Receipt = string;
32
30
  type HumanAction = {
33
31
  needs_human: NeedsHuman;
34
32
  message: string;
@@ -42,7 +40,7 @@ type SetupResult<T> = {
42
40
  error: string;
43
41
  human?: HumanAction;
44
42
  };
45
- /** 申告した設立地です。`terms_current` は、申告が今の組織の契約と DPA の版に結ばれているかです。 */
43
+ /** The place of incorporation declared. `terms_current` says whether the declaration binds the current Customer Terms and DPA versions. */
46
44
  type OrgCardIncorporation = {
47
45
  code: string;
48
46
  at: number;
@@ -60,9 +58,9 @@ type SetupStatusReport = {
60
58
  org_status: string;
61
59
  setup_complete: boolean;
62
60
  signature_card: "unknown" | "active" | "inactive";
63
- /** 署名のカードを止めている理由です(`signature_card` が `inactive` のとき)。 */
61
+ /** What holds the signature card back, when `signature_card` is `inactive`. */
64
62
  signature_card_blockers?: string[];
65
- /** 設立地です。null は未申告です。カードを読めなかったときは省きます。 */
63
+ /** The place of incorporation. Null means none is declared. It is left out when the card could not be read. */
66
64
  incorporation?: {
67
65
  code: string;
68
66
  terms_current: boolean;
@@ -72,30 +70,32 @@ type SetupStatusReport = {
72
70
  host: string;
73
71
  status: string;
74
72
  declaration_ok: boolean;
75
- /** 新しい接続を受け付ける地域です。省いたときは、Clavis が受け付ける地域すべてです。 */
73
+ /** The regions new connections are accepted from. Left out, it is every region Clavis accepts. */
76
74
  accepted_regions?: string[];
77
75
  }>;
78
76
  }>;
79
77
  };
80
78
  declare const DEFAULT_ORIGINS: SetupOrigins;
81
79
 
82
- /** 署名のカードの Checkout に渡すものです。 */
80
+ /** What to pass to checkout for the signature card. */
83
81
  type CardCheckoutOptions = {
84
- /** `meter`(従量。既定)か `bundle`(月額の束)です。 */
82
+ /** `meter`, which is metered and the default, or `bundle`, the monthly bundle. */
85
83
  offer?: "meter" | "bundle";
86
84
  /**
87
- * 顧客が、決済と請求のためのデータ提供(米国の Polar Software Inc. へ)に同意したときだけ true にします。
88
- * 同意するかは顧客が決めます。SDK は既定で true にしません。
85
+ * Set this true only once the customer has consented to their billing data going to the payment
86
+ * provider in the United States, for payment and billing. Whether to consent is the customer's
87
+ * decision, and the SDK never sets it true by default.
89
88
  */
90
89
  consentBillingData?: boolean;
91
- /** 同意の文を見せる言語です(`en` か `ja`。既定は `en`)。購入の記録はこの言語の文に結ばれます。 */
90
+ /** The language the consent statement is shown in, `en` or `ja`, defaulting to `en`. The purchase record is tied to the statement in that language. */
92
91
  lang?: "en" | "ja";
93
92
  };
94
93
 
95
94
  /**
96
- * 署名する文型です。`type` は型 ID(`<名前>@<版>`)、ほかは型ごとに決まった欄です。
97
- * Clavis は同じ材料から期待する文型を組み立て、JCS で一致しなければ受けません(400 `STATEMENT_MISMATCH`)。
98
- * 欄の値は Clavis と同じ形にそろえて入れます(ドメインは小文字、地域は重複なし・昇順)。
95
+ * The statement to sign. `type` is the type ID, `<name>@<version>`, and the other fields are the ones
96
+ * that type fixes. Clavis builds the statement it expects from the same material and refuses anything
97
+ * that does not match under JCS (400 `STATEMENT_MISMATCH`). Put the field values in the same form
98
+ * Clavis uses: domains lowercased, regions with no duplicates and in ascending order.
99
99
  */
100
100
  type Statement = {
101
101
  type: string;
@@ -103,15 +103,17 @@ type Statement = {
103
103
  };
104
104
 
105
105
  /**
106
- * Org を作るときに顧客が申告し、同意する内容です。
107
- * org-anchor-plan(challenge)と org-verify-anchor の両方に渡します。設立地の申告し直し(incorporation-set)も同じです。
106
+ * What the customer declares and agrees to when an Org is created.
107
+ * Pass it to both org-anchor-plan, which is the challenge, and org-verify-anchor. Declaring the place
108
+ * of incorporation again with incorporation-set takes the same thing.
108
109
  */
109
110
  type OrgCreationTerms = {
110
- /** 設立地のコード。`JP`、`GB-EAW`、EEA の国コード、`US-XX` のいずれかです。 */
111
+ /** The place of incorporation: `JP`, `GB-EAW`, an EEA country code, or `US-XX`. */
111
112
  incorporation?: string;
112
113
  /**
113
- * 顧客が組織の契約(Customer Terms)とデータ処理契約(DPA)に同意したときだけ true にします。
114
- * 同意するかは顧客が決めます。SDK は既定で true にしません。
114
+ * Set this true only once the customer has agreed to the Customer Terms and the Data Processing
115
+ * Agreement (DPA). Whether to agree is the customer's decision, and the SDK never sets it true by
116
+ * default.
115
117
  */
116
118
  acceptCustomerTerms?: boolean;
117
119
  };
@@ -147,14 +149,14 @@ type SetupClient = {
147
149
  cleared: true;
148
150
  }>>;
149
151
  status(): Promise<SetupResult<SetupStatusReport>>;
150
- /** terms: 設立地と、顧客の組織の契約への同意。どちらかが無いか、設立地が閉じていれば Passkey の前に断ります。 */
152
+ /** terms: the place of incorporation, and the customer's agreement to the Customer Terms. With either missing, or the place closed, it is refused before the passkey. */
151
153
  orgAnchorPlan(domain: string, name?: string, terms?: OrgCreationTerms): Promise<SetupResult<{
152
154
  domain: string;
153
155
  name?: string;
154
156
  incorporation: string;
155
157
  nonce: string;
156
158
  exp: number;
157
- /** 公開マニフェストの `receipt` に署名した文型(`org.anchor.publish@1`) */
159
+ /** The statement signed into the published manifest's `receipt` (`org.anchor.publish@1`) */
158
160
  statement: Statement;
159
161
  well_known_url: string;
160
162
  txt_host: string;
@@ -189,8 +191,9 @@ type SetupClient = {
189
191
  already_active: boolean;
190
192
  }>>;
191
193
  /**
192
- * 設立地を申告します(Passkey)。申告は今の組織の契約と DPA の版に結ばれるため、顧客の同意が要ります。
193
- * 組織の契約の版が新しくなったあと、購入の前に申告し直します。
194
+ * Declare the place of incorporation, with a passkey. The declaration binds the current Customer
195
+ * Terms and DPA versions, so it needs the customer's agreement. After those versions move, declare
196
+ * again before a purchase.
194
197
  */
195
198
  incorporationSet(args: {
196
199
  orgId: string;
@@ -199,8 +202,9 @@ type SetupClient = {
199
202
  unchanged?: true;
200
203
  }>>;
201
204
  /**
202
- * 署名のカードの Checkout を開きます。設立地が今の版で申告済みで、顧客が決済のためのデータ提供に同意していることが要ります。
203
- * Passkey のあと、カードの入力は人間がブラウザで行います。
205
+ * Open checkout for the signature card. It needs a place of incorporation declared against the
206
+ * current versions, and the customer's consent to provide billing data. After the passkey, a person
207
+ * enters the card in the browser.
204
208
  */
205
209
  cardCheckout(orgId: string, opts?: CardCheckoutOptions): Promise<SetupResult<{
206
210
  url: string;
@@ -243,8 +247,9 @@ type SetupClient = {
243
247
  declaration: unknown;
244
248
  }>>;
245
249
  /**
246
- * App が新しい接続を受け付ける地域を決めます(Passkey)。null で、Clavis が受け付ける地域すべてに戻します。
247
- * 選べるのは、いま Clavis が受け付けている地域だけです。地域を絞っても、すでに接続している人はそのまま使えます。
250
+ * Choose the regions the app accepts new connections from, with a passkey. Null goes back to every
251
+ * region Clavis accepts. The choice is limited to the regions Clavis accepts right now. Narrowing
252
+ * the list leaves the people already connected using the app.
248
253
  */
249
254
  appRegionsSet(args: {
250
255
  orgId: string;
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@ import { promisify } from 'util';
3
3
  import { readFile, unlink, mkdir, writeFile, chmod, lstat } from 'fs/promises';
4
4
  import path, { join, dirname, resolve, relative, isAbsolute } from 'path';
5
5
  import { homedir } from 'os';
6
- import { generateKeyPair, exportJWK, createRemoteJWKSet, jwtVerify } from 'jose';
6
+ import { generateKeyPair, exportJWK, jwtVerify, importJWK } from 'jose';
7
7
  import { createInterface } from 'readline/promises';
8
8
  import { stdin, stdout } from 'process';
9
9
  import { randomBytes } from 'crypto';
@@ -173,19 +173,10 @@ async function postCardCheckout(apiOrigin, bearer, orgId, args) {
173
173
  }
174
174
  });
175
175
  }
176
- async function fetchJwksDocument(apiOrigin) {
177
- const res = await fetch(`${apiOrigin.replace(/\/+$/, "")}/.well-known/jwks.json`, {
178
- redirect: "error",
179
- headers: { Accept: "application/json" }
180
- });
181
- if (!res.ok) throw new SetupApiError(res.status, "JWKS_FETCH", `jwks ${res.status}`);
182
- return res.json();
183
- }
184
- async function getMasterJwkJson(apiOrigin, masterPinJson) {
185
- const { verifySignedJwksDocument } = await import('@clavis.nexus/app');
186
- const doc = await fetchJwksDocument(apiOrigin);
187
- await verifySignedJwksDocument(doc, masterPinJson);
188
- return JSON.stringify(doc.master);
176
+ async function checkTrustRoot(apiOrigin, trustRootJson) {
177
+ const { createVerifier } = await import('@clavis.nexus/app');
178
+ await createVerifier({ trustRoot: trustRootJson, apiOrigin }).trust();
179
+ return JSON.stringify(JSON.parse(trustRootJson));
189
180
  }
190
181
 
191
182
  // src/app-regions.ts
@@ -498,6 +489,17 @@ async function digestOf(value) {
498
489
  const bytes = new TextEncoder().encode(canonicalStringify(value));
499
490
  return `sha256:${bytesToBase64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)))}`;
500
491
  }
492
+ async function valueDigest(type, value) {
493
+ return digestOf({ type, value });
494
+ }
495
+ async function orgPayloadDigest(payload) {
496
+ let value = payload;
497
+ if (payload && typeof payload === "object" && !Array.isArray(payload)) {
498
+ const { proposer_receipt: _receipt, ...rest } = payload;
499
+ value = rest;
500
+ }
501
+ return valueDigest("org.payload@1", value);
502
+ }
501
503
  function orgAnchorPublishStatement(input2) {
502
504
  return { type: "org.anchor.publish@1", domain: input2.domain.trim().toLowerCase(), nonce: input2.nonce, exp: input2.exp };
503
505
  }
@@ -505,7 +507,7 @@ function orgPolicyBootstrapStatement(input2) {
505
507
  return { type: "org.policy.bootstrap@1", org: input2.org.trim(), domain: input2.domain.trim().toLowerCase() };
506
508
  }
507
509
  function orgAppRegisterStatement(input2) {
508
- return { type: "org.app.register@1", org: input2.org.trim(), payload: input2.payload.trim().toLowerCase() };
510
+ return { type: "org.app.register@1", org: input2.org.trim(), payload: input2.payload.trim() };
509
511
  }
510
512
  function orgAppVerifyHostStatement(input2) {
511
513
  return {
@@ -521,7 +523,7 @@ async function orgAppDeclarationStatement(input2) {
521
523
  type: "org.app.declaration@1",
522
524
  org: input2.org.trim(),
523
525
  app: input2.app.trim(),
524
- declaration: input2.declaration === null ? null : await digestOf({ endUsers: input2.declaration.endUsers, uses: input2.declaration.uses })
526
+ declaration: input2.declaration === null ? null : await valueDigest("app.declaration@1", { endUsers: input2.declaration.endUsers, uses: input2.declaration.uses })
525
527
  };
526
528
  }
527
529
  function orgAppRegionsStatement(input2) {
@@ -558,13 +560,6 @@ function sameStatement(a, b) {
558
560
  return false;
559
561
  }
560
562
  }
561
- async function computePayloadCommitmentHex(payload) {
562
- const o = payload && typeof payload === "object" ? { ...payload } : payload;
563
- if (o && typeof o === "object" && !Array.isArray(o)) {
564
- delete o.proposer_receipt;
565
- }
566
- return sha256HexUtf8(canonicalStringify(o));
567
- }
568
563
  async function hashManifestBody(body) {
569
564
  return sha256HexUtf8(canonicalStringify(body));
570
565
  }
@@ -574,14 +569,10 @@ function buildAnchorTxtRecord(args) {
574
569
 
575
570
  // src/ceremony.ts
576
571
  function receiptFromCeremonyPayload(payload) {
577
- if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
572
+ if (typeof payload !== "string" || payload.length === 0) {
578
573
  throw new Error("Passkey confirmation did not return a receipt.");
579
574
  }
580
- const o = payload;
581
- if (o.type !== "receipt@1" || o.statement === null || typeof o.statement !== "object") {
582
- throw new Error("Passkey confirmation did not return a receipt.");
583
- }
584
- return o;
575
+ return payload;
585
576
  }
586
577
  async function startCeremony(args) {
587
578
  const res = await fetch(`${args.apiOrigin.replace(/\/+$/, "")}/webauthn/authentication/ceremony/start`, {
@@ -713,19 +704,17 @@ async function writeAppEnvFile(appId, contents) {
713
704
 
714
705
  // src/emit-env.ts
715
706
  async function emitAppEnv(args) {
716
- const pin = args.masterPublicJwkJson?.trim() || process.env.CLAVIS_MASTER_PUBLIC_JWK_JSON?.trim() || "";
707
+ const pin = args.trustRoot?.trim() || process.env.CLAVIS_TRUST_ROOT?.trim() || "";
717
708
  if (!pin) {
718
- throw new Error(
719
- "CLAVIS_MASTER_PUBLIC_JWK_JSON is required. Set it to the master public JWK from GET {apiOrigin}/.well-known/jwks.json."
720
- );
709
+ throw new Error("CLAVIS_TRUST_ROOT is required. Set it to the Clavis Master public JWK (docs.clavis.nexus).");
721
710
  }
722
- const master = await getMasterJwkJson(args.origins.apiOrigin, pin);
711
+ const trustRoot = await checkTrustRoot(args.origins.apiOrigin, pin);
723
712
  const operatePath = await saveOperatePrivateJwk(args.appId, args.operatePrivateJwkJson);
724
713
  const envRecord = {
725
714
  CLAVIS_API_ORIGIN: args.origins.apiOrigin,
726
715
  CLAVIS_APP_ID: args.appId,
727
716
  OPERATE_PRIVATE_JWK: args.operatePrivateJwkJson,
728
- MASTER_PUBLIC_JWK_JSON: master
717
+ CLAVIS_TRUST_ROOT: trustRoot
729
718
  };
730
719
  const envFile = await writeAppEnvFile(args.appId, formatEnvExport(envRecord));
731
720
  return {
@@ -761,18 +750,39 @@ async function generateOperateKeyPair() {
761
750
  privateJwkJson: JSON.stringify(priv)
762
751
  };
763
752
  }
764
- var SESSION_SLOT_RE = /^[a-z][a-z0-9]{1,31}-wauthn-auth-jwt(?:-\d{6})?$/;
753
+ var SESSION_SLOT = "wauthn-auth-jwt";
754
+ var SLOT_FIELD = /^[a-z][a-z0-9]{1,31}-slot$/;
755
+ var JWK_MEMBERS = ["kty", "crv", "x", "y", "kid", "alg"];
756
+ async function sessionKey(origin, kid) {
757
+ const res = await fetch(`${origin}/.well-known/jwks.json`, { redirect: "error", headers: { Accept: "application/json" } });
758
+ if (!res.ok) throw new Error(`jwks ${res.status}`);
759
+ const doc = await res.json();
760
+ const key = (doc.keys ?? []).find((k) => k && k.kid === kid);
761
+ if (!key) return null;
762
+ const slot = Object.entries(key).find(([name]) => SLOT_FIELD.test(name))?.[1];
763
+ if (slot !== SESSION_SLOT) return null;
764
+ const jwk = {};
765
+ for (const m of JWK_MEMBERS) if (key[m] !== void 0) jwk[m] = key[m];
766
+ return importJWK(jwk, "ES256");
767
+ }
765
768
  async function verifyDevelopersAccessToken(accessToken, apiOrigin) {
766
769
  const origin = new URL(apiOrigin).origin;
767
- const jwks = createRemoteJWKSet(new URL(`${origin}/.well-known/jwks.json`));
768
- const { payload, protectedHeader } = await jwtVerify(accessToken, jwks, {
769
- algorithms: ["ES256"],
770
- issuer: origin,
771
- audience: origin,
772
- requiredClaims: ["exp", "iss", "aud", "sub"]
770
+ let refused = false;
771
+ const { payload } = await jwtVerify(
772
+ accessToken,
773
+ async (header) => {
774
+ const key = typeof header.kid === "string" ? await sessionKey(origin, header.kid) : null;
775
+ if (!key) {
776
+ refused = true;
777
+ throw new Error("invalid_access_token_kid");
778
+ }
779
+ return key;
780
+ },
781
+ { algorithms: ["ES256"], issuer: origin, audience: origin, requiredClaims: ["exp", "iss", "aud", "sub"] }
782
+ ).catch((e) => {
783
+ if (refused) throw new Error("invalid_access_token_kid");
784
+ throw e;
773
785
  });
774
- const kid = typeof protectedHeader.kid === "string" ? protectedHeader.kid : "";
775
- if (!SESSION_SLOT_RE.test(kid)) throw new Error("invalid_access_token_kid");
776
786
  if (payload.tk !== "access") throw new Error("invalid_access_token_kind");
777
787
  if (typeof payload.sub !== "string" || payload.sub.length === 0) throw new Error("invalid_access_token_sub");
778
788
  if (typeof payload.exp !== "number" || !Number.isFinite(payload.exp)) throw new Error("invalid_access_token_exp");
@@ -1463,7 +1473,7 @@ function createSetupClient(options = {}) {
1463
1473
  operate_public_jwk: keys.publicJwk,
1464
1474
  redirect_paths: paths
1465
1475
  };
1466
- const payload_hash = await computePayloadCommitmentHex(manifest);
1476
+ const payload_hash = await orgPayloadDigest(manifest);
1467
1477
  const cer = await runPasskeyCeremony({
1468
1478
  origins: auth.data.origins,
1469
1479
  bearer: auth.data.session.accessToken,