@plasgos/auth-verify 0.0.0-stage → 0.1.0-next.2
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/CHANGELOG.md +13 -0
- package/LICENSE +15 -0
- package/README.md +86 -2
- package/dist/webhook.cjs +294 -0
- package/dist/webhook.cjs.map +1 -0
- package/dist/webhook.d.cts +190 -0
- package/dist/webhook.d.ts +190 -0
- package/dist/webhook.js +263 -0
- package/dist/webhook.js.map +1 -0
- package/docs/consumers.md +90 -0
- package/docs/contoh-hitungcuan.md +255 -0
- package/docs/contoh-plaslink.md +244 -0
- package/docs/error.md +428 -0
- package/docs/examples/auth-verify-readme.ts +18 -0
- package/docs/examples/config-error.ts +24 -0
- package/docs/examples/env.ts +99 -0
- package/docs/examples/failure-log.ts +18 -0
- package/docs/examples/login-client.ts +46 -0
- package/docs/examples/login-flow.ts +186 -0
- package/docs/examples/plaslink-connect.ts +48 -0
- package/docs/examples/readme.ts +60 -0
- package/docs/examples/service-client.ts +105 -0
- package/docs/examples/session-store.ts +53 -0
- package/docs/examples/webhook-express.ts +46 -0
- package/docs/examples/webhook-fetch.ts +60 -0
- package/docs/examples/webhook-nestjs.ts +59 -0
- package/docs/examples/webhook-testing.ts +60 -0
- package/docs/examples/webhook-verifier.ts +143 -0
- package/docs/login-web.md +618 -0
- package/docs/memulai.md +339 -0
- package/docs/server-ke-server.md +275 -0
- package/docs/webhook.md +625 -0
- package/package.json +45 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/config.ts","../src/webhook/presets.ts","../src/webhook/verify.ts","../src/webhook/config.ts","../src/webhook/headers.ts","../src/webhook/index.ts"],"sourcesContent":["// Option helpers shared by the entries of this package. Stateless functions only: tsup bundles them\n// into every entry that uses them, so the ESM and CommonJS builds hold no state that could split.\n\n/**\n * True for a non-null object that is not an array.\n *\n * @example\n * if (!isObject(raw)) throw new ConfigError([\"options must be an object\"]);\n */\nexport const isObject = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === \"object\" && !Array.isArray(value);\n\n/**\n * True for a string of whitespace only. Apps pass `process.env` values, where unset is often \"\".\n *\n * @example\n * const secrets = raw.filter((value) => value !== undefined && !isBlank(value));\n */\nexport const isBlank = (value: unknown): boolean => typeof value === \"string\" && value.trim() === \"\";\n\n/**\n * Bounds and default of {@link integerInRange}.\n *\n * @example\n * const range: IntegerRange = { min: 1, max: 900, fallback: 300 };\n */\nexport interface IntegerRange {\n readonly min: number;\n readonly max: number;\n /** Returned for `undefined`, and when the value is refused. */\n readonly fallback: number;\n}\n\n/**\n * An integer option: `undefined` gives the fallback; a safe integer from `min` to `max` is returned\n * as is; anything else collects `<field> must be an integer from <min> to <max>` and gives the\n * fallback. The problem names the field and the bounds, never the value.\n *\n * @example\n * const problems: string[] = [];\n * const toleranceSeconds = integerInRange(problems, raw.toleranceSeconds, \"toleranceSeconds\", {\n * min: 1,\n * max: 900,\n * fallback: 300,\n * });\n */\nexport function integerInRange(problems: string[], raw: unknown, field: string, range: IntegerRange): number {\n if (raw === undefined) return range.fallback;\n if (typeof raw === \"number\" && Number.isSafeInteger(raw) && raw >= range.min && raw <= range.max) return raw;\n problems.push(`${field} must be an integer from ${String(range.min)} to ${String(range.max)}`);\n return range.fallback;\n}\n\n/**\n * An optional function option: `undefined` stays `undefined`; anything that is not a function\n * collects `<field> must be a function` and gives `undefined`.\n *\n * @example\n * const onReject = optionalFunction(problems, raw.onReject, \"onReject\");\n */\nexport function optionalFunction(problems: string[], raw: unknown, field: string): ((...args: never[]) => unknown) | undefined {\n if (raw === undefined) return undefined;\n if (typeof raw === \"function\") return raw as (...args: never[]) => unknown;\n problems.push(`${field} must be a function`);\n return undefined;\n}\n","import type { WebhookHeaderRole } from \"@plasgos/auth-shared\";\n\nimport { isObject } from \"../config.js\";\n\n/**\n * The header names of one kind of Plasgos webhook. Use one of {@link presets}; a custom preset is for a\n * receiver behind a proxy that renames headers.\n *\n * @example\n * const preset: WebhookPreset = presets.payments;\n * preset.headers.signature; // \"X-Signature\"\n */\nexport interface WebhookPreset {\n /** Shown in the verified result, for logs of apps that receive several kinds. */\n readonly name: string;\n /** The header that carries each part of a delivery. */\n readonly headers: { readonly id: string; readonly type: string; readonly timestamp: string; readonly signature: string };\n}\n\nconst preset = (name: string, headers: WebhookPreset[\"headers\"]): WebhookPreset =>\n Object.freeze({ name, headers: Object.freeze({ ...headers }) });\n\n/**\n * The webhooks Plasgos sends: `payments` (payment events to an app's webhook endpoint) and\n * `plaslinkShipping` (Plaslink shipping events). Frozen.\n *\n * @example\n * const verifier = createWebhookVerifier({\n * environment: \"production\",\n * secrets: [process.env.PLASGOS_WEBHOOK_SECRET],\n * preset: presets.payments,\n * });\n */\nexport const presets: { readonly payments: WebhookPreset; readonly plaslinkShipping: WebhookPreset } = Object.freeze({\n payments: preset(\"payments\", {\n id: \"X-Event-Id\",\n type: \"X-Event-Type\",\n timestamp: \"X-Timestamp\",\n signature: \"X-Signature\",\n }),\n plaslinkShipping: preset(\"plaslinkShipping\", {\n id: \"X-Plasgos-Event-Id\",\n type: \"X-Plasgos-Event-Type\",\n timestamp: \"X-Plasgos-Timestamp\",\n signature: \"X-Plasgos-Signature\",\n }),\n});\n\nconst ROLES: readonly WebhookHeaderRole[] = [\"id\", \"type\", \"timestamp\", \"signature\"];\n/** RFC 7230 §3.2.6 token. */\nconst HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\nconst MAX_HEADER_NAME = 64;\nconst PRESET_NAME = /^[A-Za-z0-9_-]{1,64}$/;\n\n/**\n * Problems of a preset given as an option; field names only, never a value.\n *\n * @example\n * presetProblems(presets.payments); // []\n * presetProblems(\"payments\"); // [\"preset must be one of presets or an object with name and headers\"]\n */\nexport function presetProblems(raw: unknown): string[] {\n if (raw === undefined) return [\"preset is required\"];\n if (!isObject(raw) || !isObject(raw.headers)) {\n return [\"preset must be one of presets or an object with name and headers\"];\n }\n const problems: string[] = [];\n if (typeof raw.name !== \"string\" || !PRESET_NAME.test(raw.name)) {\n problems.push(`preset.name must match ${String(PRESET_NAME)}`);\n }\n const names: string[] = [];\n for (const role of ROLES) {\n const name = raw.headers[role];\n if (typeof name === \"string\" && name.length <= MAX_HEADER_NAME && HEADER_NAME.test(name)) {\n names.push(name.toLowerCase());\n } else {\n problems.push(`preset.headers.${role} must be an HTTP header name of at most ${String(MAX_HEADER_NAME)} characters`);\n }\n }\n if (new Set(names).size !== names.length) problems.push(\"preset.headers must name four distinct headers\");\n return problems;\n}\n","import { createHmac } from \"node:crypto\";\n\nimport { safeEqual, WebhookVerifyError } from \"@plasgos/auth-shared\";\nimport type { Environment, WebhookHeaderRole } from \"@plasgos/auth-shared\";\n\nimport { isObject } from \"../config.js\";\nimport { resolveWebhookConfig } from \"./config.js\";\nimport type { WebhookConfig, WebhookVerifierOptions } from \"./config.js\";\nimport { readHeader } from \"./headers.js\";\nimport type { WebhookHeaders } from \"./headers.js\";\n\n/**\n * One delivery to verify: the request headers and the raw body, exactly as received.\n *\n * @example\n * const input: WebhookVerifyInput = { headers: req.headers, rawBody: req.body }; // express.raw() gives a Buffer\n */\nexport interface WebhookVerifyInput {\n /** The request headers: a Web `Headers`, or a plain object such as Node's `req.headers`. */\n headers: WebhookHeaders;\n /** The raw request body, before JSON parsing. */\n rawBody: string | Uint8Array;\n /** Epoch milliseconds; default Date.now(). */\n now?: number | undefined;\n}\n\n/**\n * A delivery that passed verification. `id` and `type` come from the signed body.\n *\n * @example\n * const event: VerifiedWebhook = verifier.verify({ headers, rawBody });\n * if (event.type === \"payment.paid\") await markPaid(event.body);\n */\nexport interface VerifiedWebhook {\n /** Event id from the signed body (equal to the id header). Deduplicate on it. */\n readonly id: string;\n /** Event type from the signed body (equal to the type header), e.g. `payment.paid`. */\n readonly type: string;\n /** Epoch seconds of the delivery attempt (the signed timestamp header). */\n readonly timestamp: number;\n /** The parsed, frozen envelope. */\n readonly body: Readonly<Record<string, unknown>>;\n /** The `environment` the verifier was created with. */\n readonly environment: Environment;\n /** Name of the preset that verified it. */\n readonly preset: string;\n}\n\n/**\n * Verifies deliveries of one kind of Plasgos webhook with options checked once, at creation.\n *\n * @example\n * // rawBody: the request body read as bytes, with a size cap, before JSON parsing\n * const event = verifier.verify({ headers: request.headers, rawBody });\n */\nexport interface WebhookVerifier {\n /** The `environment` option. */\n readonly environment: Environment;\n /** Name of the preset, e.g. `payments`. */\n readonly preset: string;\n /**\n * Verifies one delivery and returns the signed event, or throws `WebhookVerifyError` with the reason.\n * Throws `TypeError` for an input of the wrong type (a parsed body instead of the raw one, for example).\n */\n verify(input: WebhookVerifyInput): VerifiedWebhook;\n}\n\n/**\n * Remembers which event ids were processed, inside the app's database transaction (docs/webhook.md §7). The\n * SDK does not implement it: an app stores the id with a unique key, in the same transaction as the\n * event's effect, so that id and effect commit together.\n *\n * @example\n * const dedup: WebhookDedupStore<Tx> = {\n * async saveOnce(tx, event) {\n * const result = await tx.query(\n * \"INSERT INTO plasgos_webhook_events (event_id) VALUES ($1) ON CONFLICT (event_id) DO NOTHING\",\n * [event.id],\n * );\n * return result.rowCount === 1;\n * },\n * };\n */\nexport interface WebhookDedupStore<Tx = unknown> {\n /**\n * Called inside the app's database transaction `tx`, the same one that applies the event's effect.\n * Stores the event id if it is new (atomically, a unique key). Resolves true when stored now, false for a redelivery.\n * Answer 2xx only after that transaction committed; on any failure roll back and answer 5xx.\n */\n saveOnce(tx: Tx, event: VerifiedWebhook): Promise<boolean>;\n}\n\nconst ROLES: readonly WebhookHeaderRole[] = [\"id\", \"type\", \"timestamp\", \"signature\"];\n/** Event ids and types: the `whd_…`/`evt_…` ids and dotted types Plasgos sends. */\nconst EVENT_TOKEN = /^[A-Za-z0-9_.:-]+$/;\nconst MAX_EVENT_TOKEN = 200;\n/** Epoch seconds in decimal, without a leading zero. */\nconst TIMESTAMP = /^(?:0|[1-9][0-9]*)$/;\nconst MAX_TIMESTAMP = 15;\nconst MAX_SIGNATURE = 1024;\nconst MAX_SIGNATURE_ITEMS = 10;\nconst V1 = \"v1=\";\nconst V1_VALUE = /^[0-9a-f]{64}$/i;\n\nconst RAW_BODY_PROBLEM = \"verifyWebhook: rawBody must be the raw request body as a string or Uint8Array, before JSON parsing\";\n\n/** Caller bugs: fixed messages naming the field, never the value, and no cause. */\nfunction checkInput(input: unknown): asserts input is WebhookVerifyInput {\n if (!isObject(input)) throw new TypeError(\"verifyWebhook: input must be an object with headers and rawBody\");\n if (!isObject(input.headers)) {\n throw new TypeError(\"verifyWebhook: headers must be a Headers or a plain object of header values\");\n }\n if (typeof input.rawBody !== \"string\" && !(input.rawBody instanceof Uint8Array)) throw new TypeError(RAW_BODY_PROBLEM);\n if (input.now !== undefined && !(typeof input.now === \"number\" && Number.isFinite(input.now))) {\n throw new TypeError(\"verifyWebhook: now must be a finite number of epoch milliseconds\");\n }\n}\n\n/**\n * The four header values. Every header is looked up before any is judged, so a missing header is\n * reported before a malformed one.\n */\nfunction readHeaders(headers: WebhookHeaders, names: WebhookConfig[\"preset\"][\"headers\"]): Record<WebhookHeaderRole, string> {\n const values: Partial<Record<WebhookHeaderRole, string>> = {};\n let ambiguous: WebhookVerifyError | null = null;\n for (const role of ROLES) {\n let value: string | null;\n try {\n value = readHeader(headers, names[role], role);\n } catch (error) {\n if (!(error instanceof WebhookVerifyError)) throw error;\n ambiguous ??= error;\n continue;\n }\n if (value === null) throw new WebhookVerifyError(\"missing_header\", role);\n values[role] = value;\n }\n if (ambiguous !== null) throw ambiguous;\n return values as Record<WebhookHeaderRole, string>;\n}\n\nconst isEventToken = (value: string): boolean => value.length <= MAX_EVENT_TOKEN && EVENT_TOKEN.test(value);\n\n/** The `v1` values of the signature header, lower-cased; other schemes are ignored. */\nfunction signatureValues(header: string): string[] | null {\n if (header.length > MAX_SIGNATURE) return null;\n const items = header\n .split(\",\")\n .map((item) => item.trim())\n .filter((item) => item !== \"\");\n if (items.length > MAX_SIGNATURE_ITEMS) return null;\n const values: string[] = [];\n for (const item of items) {\n if (!item.startsWith(V1)) continue;\n const value = item.slice(V1.length);\n if (!V1_VALUE.test(value)) return null;\n values.push(value.toLowerCase());\n }\n return values.length > 0 ? values : null;\n}\n\n/** Lower-case hex HMAC-SHA256 of `\"<timestamp>.\"` followed by the raw body (UTF-8 for a string). */\nconst expectedSignature = (secret: string, timestamp: number, rawBody: string | Uint8Array): string =>\n createHmac(\"sha256\", secret).update(`${String(timestamp)}.`).update(rawBody).digest(\"hex\");\n\n/** Freezes parsed JSON at every level, without recursion. */\nfunction deepFreeze<T>(value: T): T {\n const pending: unknown[] = [value];\n for (let next = pending.pop(); next !== undefined; next = pending.pop()) {\n if (next === null || typeof next !== \"object\") continue;\n Object.freeze(next);\n // One push per value: spreading a large array into push() overflows the call stack.\n for (const child of Object.values(next as Record<string, unknown>)) pending.push(child);\n }\n return value;\n}\n\n/** The signed body as a JSON object with string `id` and `type`; `invalid_body` otherwise, without the cause. */\nfunction parseBody(rawBody: string | Uint8Array): Readonly<Record<string, unknown>> & { id: string; type: string } {\n let body: unknown;\n try {\n const text = typeof rawBody === \"string\" ? rawBody : new TextDecoder(\"utf-8\", { fatal: true }).decode(rawBody);\n body = JSON.parse(text);\n } catch {\n throw new WebhookVerifyError(\"invalid_body\");\n }\n if (!isObject(body) || typeof body.id !== \"string\" || typeof body.type !== \"string\") {\n throw new WebhookVerifyError(\"invalid_body\");\n }\n return body as Record<string, unknown> & { id: string; type: string };\n}\n\n/** The checks listed at {@link createWebhookVerifier}, in that order. */\nfunction verifyDelivery(config: WebhookConfig, input: unknown): VerifiedWebhook {\n checkInput(input);\n const { rawBody } = input;\n const header = readHeaders(input.headers, config.preset.headers);\n\n if (!isEventToken(header.id)) throw new WebhookVerifyError(\"malformed_header\", \"id\");\n if (!isEventToken(header.type)) throw new WebhookVerifyError(\"malformed_header\", \"type\");\n if (header.timestamp.length > MAX_TIMESTAMP || !TIMESTAMP.test(header.timestamp)) {\n throw new WebhookVerifyError(\"malformed_header\", \"timestamp\");\n }\n // 15 digits are always a safe integer.\n const timestamp = Number(header.timestamp);\n const given = signatureValues(header.signature);\n if (given === null) throw new WebhookVerifyError(\"malformed_header\", \"signature\");\n\n const size = typeof rawBody === \"string\" ? Buffer.byteLength(rawBody, \"utf8\") : rawBody.byteLength;\n if (size > config.maxBodyBytes) throw new WebhookVerifyError(\"body_too_large\");\n\n const nowSeconds = Math.floor((input.now ?? Date.now()) / 1000);\n if (Math.abs(nowSeconds - timestamp) > config.toleranceSeconds) throw new WebhookVerifyError(\"stale_timestamp\");\n\n const expected = config.secrets.map((secret) => expectedSignature(secret, timestamp, rawBody));\n if (!expected.some((digest) => given.some((value) => safeEqual(digest, value)))) {\n throw new WebhookVerifyError(\"signature_mismatch\");\n }\n\n const body = parseBody(rawBody);\n if (body.id !== header.id) throw new WebhookVerifyError(\"header_mismatch\", \"id\");\n if (body.type !== header.type) throw new WebhookVerifyError(\"header_mismatch\", \"type\");\n\n return Object.freeze({\n id: body.id,\n type: body.type,\n timestamp,\n body: deepFreeze(body),\n environment: config.environment,\n preset: config.preset.name,\n });\n}\n\n/**\n * Creates a verifier for one kind of Plasgos webhook. The options are checked here, once: a wrong\n * configuration throws one `ConfigError` when the app starts, not at the first delivery.\n *\n * Checks, in order: the four headers are present (`missing_header`) and well formed\n * (`malformed_header`), the body is not larger than `maxBodyBytes` (`body_too_large`), the timestamp\n * is inside the window (`stale_timestamp`), a `v1` signature matches one of the secrets\n * (`signature_mismatch`), the signed body is a JSON object with string `id` and `type`\n * (`invalid_body`) equal to the headers (`header_mismatch`).\n *\n * @example\n * const verifier = createWebhookVerifier({\n * environment: \"production\",\n * secrets: [process.env.PLASGOS_WEBHOOK_SECRET, process.env.PLASGOS_WEBHOOK_SECRET_PREVIOUS],\n * preset: presets.payments,\n * });\n * const event = verifier.verify({ headers: req.headers, rawBody: req.body });\n */\nexport function createWebhookVerifier(options: WebhookVerifierOptions): WebhookVerifier {\n const config = resolveWebhookConfig(options);\n return Object.freeze({\n environment: config.environment,\n preset: config.preset.name,\n verify: (input: WebhookVerifyInput) => verifyDelivery(config, input),\n });\n}\n\n/**\n * Verifies one delivery with options given in the same call. The options are checked on every call;\n * prefer {@link createWebhookVerifier}, which checks them once at start.\n *\n * @example\n * const event = verifyWebhook({\n * environment: \"sandbox\",\n * secrets: [process.env.PLASGOS_WEBHOOK_SECRET],\n * preset: presets.payments,\n * headers: request.headers,\n * rawBody,\n * });\n */\nexport function verifyWebhook(input: WebhookVerifierOptions & WebhookVerifyInput): VerifiedWebhook {\n return verifyDelivery(resolveWebhookConfig(input), input);\n}\n","import { ConfigError, ENVIRONMENTS } from \"@plasgos/auth-shared\";\nimport type { Environment } from \"@plasgos/auth-shared\";\n\nimport { integerInRange, isBlank, isObject } from \"../config.js\";\nimport { presetProblems } from \"./presets.js\";\nimport type { WebhookPreset } from \"./presets.js\";\n\n/**\n * Options of `createWebhookVerifier` (and the configuration part of `verifyWebhook`). Checked once, when\n * the verifier is created: every problem is listed in one `ConfigError`, by field name only.\n *\n * @example\n * const options: WebhookVerifierOptions = {\n * environment: \"production\",\n * secrets: [process.env.PLASGOS_WEBHOOK_SECRET, process.env.PLASGOS_WEBHOOK_SECRET_PREVIOUS],\n * preset: presets.payments,\n * };\n */\nexport interface WebhookVerifierOptions {\n /** `\"sandbox\"` or `\"production\"`. Labels every result; `\"production\"` refuses `toleranceSeconds` above 300. */\n environment: Environment;\n /**\n * One or two webhook secrets, each at least 32 UTF-8 bytes. `undefined` and blank entries are dropped\n * first, so an unset `_PREVIOUS` env value can be passed as is. During a rotation: `[new, old]`, in any order.\n */\n secrets: readonly (string | undefined)[];\n /** `presets.payments`, `presets.plaslinkShipping`, or a custom preset of the same shape. */\n preset: WebhookPreset;\n /** Largest allowed `|now − timestamp|` in seconds, integer 1–900; at most 300 in production. Default 300. */\n toleranceSeconds?: number | undefined;\n /** Largest raw body accepted, in bytes, integer 1 024–16 777 216. Default 1 048 576. */\n maxBodyBytes?: number | undefined;\n}\n\n/**\n * The checked, frozen options.\n *\n * @example\n * const config: WebhookConfig = resolveWebhookConfig({ environment: \"sandbox\", secrets: [secret], preset: presets.payments });\n */\nexport interface WebhookConfig {\n readonly environment: Environment;\n /** Distinct, non-blank secrets, one or two. */\n readonly secrets: readonly string[];\n /** A frozen copy of the preset. */\n readonly preset: WebhookPreset;\n readonly toleranceSeconds: number;\n readonly maxBodyBytes: number;\n}\n\nconst MIN_SECRET_BYTES = 32;\n/** Above this, `environment: \"production\"` refuses `toleranceSeconds`. */\nconst PRODUCTION_MAX_TOLERANCE = 300;\n\nconst isEnvironment = (value: unknown): value is Environment =>\n typeof value === \"string\" && (ENVIRONMENTS as readonly string[]).includes(value);\n\n/** The distinct non-blank secrets, or null when the value is not one or two of them. */\nfunction readSecrets(raw: unknown): string[] | null {\n if (!Array.isArray(raw)) return null;\n const values: unknown[] = raw;\n if (!values.every((value) => value === undefined || typeof value === \"string\")) return null;\n const secrets = [...new Set(values.filter((value): value is string => value !== undefined && !isBlank(value)))];\n return secrets.length >= 1 && secrets.length <= 2 ? secrets : null;\n}\n\n/** A frozen copy of a preset that passed `presetProblems`. */\nconst copyPreset = (raw: WebhookPreset): WebhookPreset =>\n Object.freeze({\n name: raw.name,\n headers: Object.freeze({\n id: raw.headers.id,\n type: raw.headers.type,\n timestamp: raw.headers.timestamp,\n signature: raw.headers.signature,\n }),\n });\n\n/**\n * Checks untyped webhook verifier options and returns them frozen, or throws one\n * `ConfigError` listing every problem by field name, never a value.\n *\n * @example\n * const config = resolveWebhookConfig({ environment: \"sandbox\", secrets: [secret], preset: presets.payments });\n * config.toleranceSeconds; // 300\n */\nexport function resolveWebhookConfig(raw: unknown): WebhookConfig {\n if (!isObject(raw)) throw new ConfigError([\"options must be an object\"]);\n const problems: string[] = [];\n\n const { environment } = raw;\n if (!isEnvironment(environment)) problems.push('environment must be \"sandbox\" or \"production\"');\n\n const secrets = readSecrets(raw.secrets);\n if (secrets === null) {\n problems.push(\"secrets must hold one or two values\");\n } else if (secrets.some((secret) => Buffer.byteLength(secret, \"utf8\") < MIN_SECRET_BYTES)) {\n problems.push(`secrets values must each be at least ${String(MIN_SECRET_BYTES)} bytes`);\n }\n\n problems.push(...presetProblems(raw.preset));\n\n const toleranceSeconds = integerInRange(problems, raw.toleranceSeconds, \"toleranceSeconds\", {\n min: 1,\n max: 900,\n fallback: PRODUCTION_MAX_TOLERANCE,\n });\n if (toleranceSeconds > PRODUCTION_MAX_TOLERANCE && environment === \"production\") {\n problems.push(`toleranceSeconds above ${String(PRODUCTION_MAX_TOLERANCE)} is not allowed when environment is \"production\"`);\n }\n\n const maxBodyBytes = integerInRange(problems, raw.maxBodyBytes, \"maxBodyBytes\", {\n min: 1024,\n max: 16_777_216,\n fallback: 1_048_576,\n });\n\n // The last two conditions always come with a problem; they narrow the types.\n if (problems.length > 0 || !isEnvironment(environment) || secrets === null) throw new ConfigError(problems);\n return Object.freeze({\n environment,\n secrets: Object.freeze(secrets),\n preset: copyPreset(raw.preset as WebhookPreset),\n toleranceSeconds,\n maxBodyBytes,\n });\n}\n","import { WebhookVerifyError } from \"@plasgos/auth-shared\";\nimport type { WebhookHeaderRole } from \"@plasgos/auth-shared\";\n\n/**\n * The request headers of a delivery: a Web `Headers` (fetch-based servers), or a plain object such as\n * Node's `IncomingHttpHeaders` (Express, NestJS), searched case-insensitively.\n *\n * @example\n * const fromFetch: WebhookHeaders = request.headers; // Request\n * const fromNode: WebhookHeaders = req.headers; // IncomingMessage\n */\nexport type WebhookHeaders = Headers | { readonly [name: string]: string | readonly string[] | undefined };\n\ninterface HeaderGetter {\n get(name: string): unknown;\n}\n\nconst hasGet = (headers: object): headers is HeaderGetter => typeof (headers as { get?: unknown }).get === \"function\";\n\n/**\n * The header value, null when absent; throws WebhookVerifyError(\"malformed_header\", role) for an\n * ambiguous or non-string value. A plain object is searched over its own\n * enumerable keys, ignoring case; two keys that differ only in case are ambiguous. A `string[]` value\n * is joined with \", \", as `Headers.get` joins a repeated header.\n *\n * @example\n * readHeader(req.headers, presets.payments.headers.signature, \"signature\"); // \"v1=…\" or null\n */\nexport function readHeader(headers: WebhookHeaders, name: string, role: WebhookHeaderRole): string | null {\n if (hasGet(headers)) {\n const value = headers.get(name);\n if (value === null || typeof value === \"string\") return value;\n throw new WebhookVerifyError(\"malformed_header\", role);\n }\n const wanted = name.toLowerCase();\n const keys = Object.keys(headers).filter((key) => key.toLowerCase() === wanted);\n if (keys.length > 1) throw new WebhookVerifyError(\"malformed_header\", role);\n const [key] = keys;\n if (key === undefined) return null;\n const value: unknown = headers[key];\n if (value === undefined) return null;\n if (typeof value === \"string\") return value;\n if (Array.isArray(value) && value.every((item) => typeof item === \"string\")) return value.join(\", \");\n throw new WebhookVerifyError(\"malformed_header\", role);\n}\n","export { presets } from \"./presets.js\";\nexport type { WebhookPreset } from \"./presets.js\";\nexport type { WebhookHeaders } from \"./headers.js\";\nexport type { WebhookVerifierOptions } from \"./config.js\";\nexport { createWebhookVerifier, verifyWebhook } from \"./verify.js\";\nexport type { VerifiedWebhook, WebhookDedupStore, WebhookVerifier, WebhookVerifyInput } from \"./verify.js\";\n// The classes this entry throws, and the environment type of its options: the same classes as in\n// @plasgos/auth-shared, so `instanceof` holds across the packages.\nexport { ConfigError, WebhookVerifyError } from \"@plasgos/auth-shared\";\nexport type { Environment, WebhookHeaderRole, WebhookVerifyReason } from \"@plasgos/auth-shared\";\n"],"mappings":";AASO,IAAM,WAAW,CAAC,UACvB,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAQ9D,IAAM,UAAU,CAAC,UAA4B,OAAO,UAAU,YAAY,MAAM,KAAK,MAAM;AA4B3F,SAAS,eAAe,UAAoB,KAAc,OAAe,OAA6B;AAC3G,MAAI,QAAQ,OAAW,QAAO,MAAM;AACpC,MAAI,OAAO,QAAQ,YAAY,OAAO,cAAc,GAAG,KAAK,OAAO,MAAM,OAAO,OAAO,MAAM,IAAK,QAAO;AACzG,WAAS,KAAK,GAAG,KAAK,4BAA4B,OAAO,MAAM,GAAG,CAAC,O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AQ,WAAW,OAAO,CAAC;AAC7F,MAAI,CAAC,SAAS,KAAK,CAAC,WAAW,MAAM,KAAK,CAAC,UAAU,UAAU,QAAQ,KAAK,CAAC,CAAC,GAAG;AAC/E,UAAM,IAAIA,oBAAmB,oBAAoB;AAAA,EACnD;AAEA,QAAM,OAAO,UAAU,OAAO;AAC9B,MAAI,KAAK,OAAO,OAAO,GAAI,OAAM,IAAIA,oBAAmB,mBAAmB,IAAI;AAC/E,MAAI,KAAK,SAAS,OAAO,KAAM,OAAM,IAAIA,oBAAmB,mBAAmB,MAAM;AAErF,SAAO,OAAO,OAAO;AAAA,IACnB,IAAI,KAAK;AAAA,IACT,MAAM,KAAK;AAAA,IACX;AAAA,IACA,MAAM,WAAW,IAAI;AAAA,IACrB,aAAa,OAAO;AAAA,IACpB,QAAQ,OAAO,OAAO;AAAA,EACxB,CAAC;AACH;AAoBO,SAAS,sBAAsB,SAAkD;AACtF,QAAM,SAAS,qBAAqB,OAAO;AAC3C,SAAO,OAAO,OAAO;AAAA,IACnB,aAAa,OAAO;AAAA,IACpB,QAAQ,OAAO,OAAO;AAAA,IACtB,QAAQ,CAAC,UAA8B,eAAe,QAAQ,KAAK;AAAA,EACrE,CAAC;AACH;AAeO,SAAS,cAAc,OAAqE;AACjG,SAAO,eAAe,qBAAqB,KAAK,GAAG,KAAK;AAC1D;;;AG3QA,SAAS,eAAAC,cAAa,sBAAAC,2BAA0B;","names":["WebhookVerifyError","value","key","ROLES","WebhookVerifyError","ConfigError","WebhookVerifyError"]}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# Install paket `@plasgos/*`
|
|
2
|
+
|
|
3
|
+
Panduan ini untuk aplikasi yang memakai paket `@plasgos/oidc-client` atau `@plasgos/auth-verify`. Isinya: cara install di laptop, di Docker, dan di CI, aturan versi, dan lisensi.
|
|
4
|
+
|
|
5
|
+
Paket diterbitkan di npmjs.com (`registry.npmjs.org`) sebagai paket **publik** di scope `@plasgos`, sama seperti paket `@plasgos/*` lain (misalnya `@plasgos/webchat`). Install tidak butuh token, `.npmrc` khusus, atau secret. Repo sumbernya privat; yang publik hanya paket hasil build. Panduan pemakaian ikut di dalam paket `@plasgos/oidc-client` dan `@plasgos/auth-verify` (isinya sama), di folder `docs/`: bisa dibaca di tab **Code** halaman paket di npmjs.com, atau di `node_modules/@plasgos/oidc-client/docs/` atau `node_modules/@plasgos/auth-verify/docs/` setelah install.
|
|
6
|
+
|
|
7
|
+
Status saat ini: `@plasgos/auth-shared`, `@plasgos/oidc-client`, dan `@plasgos/auth-verify` terbit di npmjs.com sebagai pre-release, selalu dengan nomor versi yang sama. Cek versi yang ada dengan `npm view @plasgos/auth-verify versions`.
|
|
8
|
+
|
|
9
|
+
Setelah paket terpasang, lanjut ke [`memulai.md`](memulai.md).
|
|
10
|
+
|
|
11
|
+
## 1. Install
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pnpm add @plasgos/oidc-client@<versi> --save-exact
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Aplikasi yang menerima webhook dari Plasgos meng-install `@plasgos/auth-verify`, sendiri atau di samping `@plasgos/oidc-client`, dengan versi yang sama:
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
pnpm add @plasgos/auth-verify@<versi> --save-exact
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Ganti `<versi>` dengan nomor versi persis (lihat §5). `@plasgos/auth-shared` ikut terpasang dengan versi yang sama, jadi tidak perlu di-install sendiri.
|
|
24
|
+
|
|
25
|
+
Perintah ini sama di laptop, di Docker, dan di CI. Tidak ada token yang perlu dibuat atau diatur.
|
|
26
|
+
|
|
27
|
+
## 2. `.npmrc` di repo aplikasi
|
|
28
|
+
|
|
29
|
+
Tidak perlu baris apa pun untuk `@plasgos`. Paket diambil dari registry bawaan (`registry.npmjs.org`).
|
|
30
|
+
|
|
31
|
+
Bila `.npmrc` aplikasi masih punya baris yang mengarahkan `@plasgos` ke GitHub Packages, hapus baris itu beserta baris token-nya:
|
|
32
|
+
|
|
33
|
+
```
|
|
34
|
+
@plasgos:registry=https://npm.pkg.github.com
|
|
35
|
+
//npm.pkg.github.com/:_authToken=${NPM_TOKEN}
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Satu scope hanya bisa diarahkan ke satu registry. Selama baris pertama masih ada, semua paket `@plasgos/*` dicari di GitHub Packages dan install gagal. Baris lain di `.npmrc` (misalnya `save-exact=true`) tetap dipakai.
|
|
39
|
+
|
|
40
|
+
## 3. Dockerfile
|
|
41
|
+
|
|
42
|
+
Install di Docker cukup `pnpm install` biasa. Tidak ada BuildKit secret, `--mount=type=secret`, `ARG`, atau `ENV` untuk token.
|
|
43
|
+
|
|
44
|
+
```dockerfile
|
|
45
|
+
FROM node:26-trixie-slim AS deps
|
|
46
|
+
WORKDIR /app
|
|
47
|
+
COPY package.json pnpm-lock.yaml ./
|
|
48
|
+
# Node 26 tidak lagi membawa corepack, jadi pnpm dipasang lewat npm (versi dari `packageManager`).
|
|
49
|
+
RUN npm install -g --no-fund --no-audit "$(node -p 'require("./package.json").packageManager')"
|
|
50
|
+
RUN pnpm install --frozen-lockfile
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Build-nya:
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
docker build -t app .
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Aturan:
|
|
60
|
+
|
|
61
|
+
- Stage `runtime` hanya mengambil `node_modules`, hasil build, dan file yang dibutuhkan saat aplikasi berjalan. Stage itu tidak meng-copy `.npmrc`.
|
|
62
|
+
- Bila Dockerfile aplikasi masih memakai `--mount=type=secret,id=npm_token,…` hanya untuk `@plasgos/*`, mount itu boleh dihapus, begitu juga `--secret id=npm_token,…` di perintah `docker build`.
|
|
63
|
+
|
|
64
|
+
## 4. CI
|
|
65
|
+
|
|
66
|
+
GitLab CI dan GitHub Actions menjalankan `pnpm install` atau `docker build` seperti biasa, tanpa variable atau secret untuk paket ini.
|
|
67
|
+
|
|
68
|
+
Bila project GitLab aplikasi punya variable `NPM_TOKEN` yang hanya dipakai untuk `@plasgos/*` dari GitHub Packages, variable itu tidak dipakai lagi dan boleh dihapus. Bila workflow GitHub Actions aplikasi memberi `packages: read` dan meneruskan `GITHUB_TOKEN` hanya untuk paket ini, keduanya juga boleh dihapus.
|
|
69
|
+
|
|
70
|
+
## 5. Versi
|
|
71
|
+
|
|
72
|
+
- Selama versi masih `0.x`, tulis rentang `~0.y.z` di `package.json` aplikasi. Di `0.x`, kenaikan minor dianggap breaking, jadi aplikasi hanya menerima patch secara otomatis. `pnpm add` tidak menulis rentang ini (ia menulis versi persis bila `save-exact=true`, selain itu `^`), jadi ubah rentangnya dengan tangan setelah `pnpm add`.
|
|
73
|
+
- Setelah `1.0.0`, pakai rentang `^`.
|
|
74
|
+
- Versi yang benar-benar terpasang ditentukan lockfile aplikasi. Menaikkan versi berarti membuat PR di repo aplikasi, supaya test aplikasi ikut berjalan.
|
|
75
|
+
- Semua paket `@plasgos/*` di SDK ini dirilis dengan nomor versi yang sama. Aplikasi yang memakai dua paket menaikkan keduanya sekaligus.
|
|
76
|
+
- `@plasgos/auth-shared` tidak di-install langsung. Paket itu ikut terpasang sebagai dependensi `oidc-client` dan `auth-verify`.
|
|
77
|
+
|
|
78
|
+
**Pre-release `next`.** Versi uji terbit sebagai `x.y.z-next.n`. Pre-release hanya di-install dengan nomor versi persis (§1), yang diambil dari halaman paket di npmjs.com atau `CHANGELOG.md` paket. Dist-tag `next` tidak dijamin menunjuk ke versi uji terbaru, jadi jangan meng-install dengan `@next`.
|
|
79
|
+
|
|
80
|
+
Rentang `~0.y.z` tidak pernah cocok dengan pre-release. Sampai rilis stabil pertama terbit, `pnpm add @plasgos/oidc-client` tanpa nomor versi gagal (tidak ada versi di dist-tag `latest`) atau mendapat sebuah pre-release yang tidak Anda pilih. Karena itu selalu install dengan nomor versi persis.
|
|
81
|
+
|
|
82
|
+
Perintah di §1 menulis versi persis (`x.y.z-next.n`) ke `package.json`, dan versi persis tidak pernah pindah sendiri. Bila yang tertulis adalah rentang `^` atau `~` pada pre-release, rentang itu juga menerima rilis stabil di minor yang sama, tetapi lockfile menahan pre-release itu sampai aplikasi menjalankan `pnpm update`. Setelah rilis stabil terbit, ubah versinya menjadi `~0.y.z` lewat PR.
|
|
83
|
+
|
|
84
|
+
**Perbaikan keamanan.** Perbaikan dirilis sebagai patch, dan tim Plasgos memberi tahu tim aplikasi yang memakai paket ini. Naikkan versi, perbarui lockfile, dan deploy secepatnya. Versi yang bermasalah di-deprecate (`npm deprecate`), tidak dihapus, supaya lockfile lama tetap bisa di-install sampai aplikasinya naik versi.
|
|
85
|
+
|
|
86
|
+
## 6. Isi paket dan lisensi
|
|
87
|
+
|
|
88
|
+
- Paket berisi `dist` (ESM, CJS, `.d.ts`, dan source map), `README.md`, `CHANGELOG.md`, dan `LICENSE`. `@plasgos/oidc-client` dan `@plasgos/auth-verify` juga membawa folder `docs/` dengan isi yang sama: panduan ini dan file contohnya (`docs/examples/`).
|
|
89
|
+
- Source map ikut terbit lengkap dengan `sourcesContent`, supaya stack trace menunjuk ke sumber TypeScript. Karena paketnya publik, sumber TypeScript paket ikut terbaca siapa pun yang mengunduh paket. Ini disengaja.
|
|
90
|
+
- Lisensi: bukan open source. Paket milik Plasgos dan hanya boleh dipakai untuk menghubungkan aplikasi ke layanan Plasgos (login dan API Plasgos) oleh pemegang kredensial client resmi dari Plasgos dan pengembang yang bekerja untuk mereka. Menyalin, mengubah, menerbitkan ulang, atau mendistribusikan paket tanpa izin tertulis Plasgos dilarang. Teks lengkapnya ada di file [`LICENSE`](../LICENSE) di setiap paket.
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
# Contoh: HitungCuan (payments saja)
|
|
2
|
+
|
|
3
|
+
HitungCuan menagih langganan seller lewat payments Plasgos. Aplikasi ini **tidak punya login Plasgos**, jadi tidak memakai `createOidcClient` sama sekali. Yang dipakai hanya dua hal:
|
|
4
|
+
|
|
5
|
+
| Kebutuhan | Bagian SDK | Status |
|
|
6
|
+
|---|---|---|
|
|
7
|
+
| Membuat dan melihat payment | `createServiceClient` dari `@plasgos/oidc-client/service` | Panduan ini |
|
|
8
|
+
| Menerima kabar status payment (webhook) | `createWebhookVerifier` dari `@plasgos/auth-verify/webhook` | Panduan ini |
|
|
9
|
+
|
|
10
|
+
Panduan ini berjalan dari nol sampai payment pertama dan webhook-nya. Penjelasan setiap opsi ada di [`server-ke-server.md`](server-ke-server.md) dan [`webhook.md`](webhook.md).
|
|
11
|
+
|
|
12
|
+
## 1. Prasyarat di Plasgos
|
|
13
|
+
|
|
14
|
+
Tim Plasgos menyiapkan hal berikut, sekali untuk sandbox dan sekali untuk production, lalu menyerahkan kredensialnya kepada HitungCuan ([§2](#2-yang-diterima-hitungcuan)):
|
|
15
|
+
|
|
16
|
+
1. App `hitungcuan` di katalog aplikasi Plasgos.
|
|
17
|
+
2. Purpose pembayaran `subscription` untuk app itu. Tanpa purpose, pembuatan payment dijawab `422 purpose_not_allowed`.
|
|
18
|
+
3. Client service untuk app itu dengan scope `platform:self.read`, `payments:read`, `payments:write`. Refund HitungCuan dikerjakan manual, jadi client-nya tanpa `payments:refund`.
|
|
19
|
+
4. URL webhook HitungCuan yang Anda berikan, beserta secret webhook (`whsec_…`) untuk URL itu.
|
|
20
|
+
|
|
21
|
+
## 2. Yang diterima HitungCuan
|
|
22
|
+
|
|
23
|
+
| Nilai | Lewat | Env |
|
|
24
|
+
|---|---|---|
|
|
25
|
+
| Client id | Kanal secret | `PLASGOS_SERVICE_CLIENT_ID` |
|
|
26
|
+
| Client secret (tampil sekali) | Kanal secret | `PLASGOS_SERVICE_CLIENT_SECRET` |
|
|
27
|
+
| Secret webhook (tampil sekali) | Kanal secret | `PLASGOS_WEBHOOK_SECRET` |
|
|
28
|
+
| Issuer | Biasa | `PLASGOS_ISSUER` |
|
|
29
|
+
| Host API | Biasa | `PLASGOS_API_URL` |
|
|
30
|
+
| Audience platform, bila bukan bawaan | Biasa | `PLASGOS_AUDIENCE` |
|
|
31
|
+
|
|
32
|
+
Bila serah terima dari tim Plasgos memakai nama lain, pemetaannya:
|
|
33
|
+
|
|
34
|
+
| Nama di serah terima | Dipakai sebagai |
|
|
35
|
+
|---|---|
|
|
36
|
+
| `PLASGOS_CLIENT_ID`, `PLASGOS_CLIENT_SECRET` | `PLASGOS_SERVICE_CLIENT_ID`, `PLASGOS_SERVICE_CLIENT_SECRET` |
|
|
37
|
+
| `PLASGOS_TOKEN_URL` (`<issuer>/oidc/token`) | Tidak dipakai. Isi `PLASGOS_ISSUER` dengan bagian sebelum `/oidc/token`. SDK menambahkan path-nya sendiri |
|
|
38
|
+
| `PLASGOS_AUDIENCE` | `PLASGOS_AUDIENCE` |
|
|
39
|
+
|
|
40
|
+
## 3. Env
|
|
41
|
+
|
|
42
|
+
Sandbox:
|
|
43
|
+
|
|
44
|
+
```dotenv
|
|
45
|
+
PLASGOS_ENV=sandbox
|
|
46
|
+
PLASGOS_ISSUER=https://<host accounts sandbox>
|
|
47
|
+
PLASGOS_API_URL=https://api.sandbox.plasgos.co.id
|
|
48
|
+
PLASGOS_SERVICE_CLIENT_ID=<client id sandbox>
|
|
49
|
+
PLASGOS_SERVICE_CLIENT_SECRET=<client secret sandbox>
|
|
50
|
+
PLASGOS_WEBHOOK_SECRET=<secret webhook sandbox>
|
|
51
|
+
# PLASGOS_AUDIENCE=<hanya bila diberikan tim Plasgos>
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Production:
|
|
55
|
+
|
|
56
|
+
```dotenv
|
|
57
|
+
PLASGOS_ENV=production
|
|
58
|
+
PLASGOS_ISSUER=https://accounts.plasgos.co.id
|
|
59
|
+
PLASGOS_API_URL=https://api.plasgos.co.id
|
|
60
|
+
PLASGOS_SERVICE_CLIENT_ID=<client id production>
|
|
61
|
+
PLASGOS_SERVICE_CLIENT_SECRET=<client secret production>
|
|
62
|
+
PLASGOS_WEBHOOK_SECRET=<secret webhook production>
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
`PLASGOS_ENV` adalah pengaman. Bila `PLASGOS_ENV=sandbox` tetapi salah satu URL mengarah ke host production (atau `PLASGOS_ENV=production` dengan issuer yang bukan production), aplikasi menolak start. Lihat [`memulai.md` §5](memulai.md#sandbox-dan-production).
|
|
66
|
+
|
|
67
|
+
## 4. Install
|
|
68
|
+
|
|
69
|
+
Install `@plasgos/oidc-client` dan `@plasgos/auth-verify` dari npmjs.com dengan nomor versi persis yang sama, tanpa token (`pnpm add @plasgos/oidc-client@<versi> @plasgos/auth-verify@<versi> --save-exact`). Aturan versi dan Docker ada di [`consumers.md`](consumers.md).
|
|
70
|
+
|
|
71
|
+
## 5. Kode
|
|
72
|
+
|
|
73
|
+
Salin tiga file dari [folder contoh](examples/) ke aplikasi: `env.ts`, `failure-log.ts`, dan `config-error.ts`. Isinya ada di [`memulai.md`](memulai.md) dan [`server-ke-server.md`](server-ke-server.md).
|
|
74
|
+
|
|
75
|
+
**Langkah 1. Buat client saat start.**
|
|
76
|
+
|
|
77
|
+
<!-- snippet: examples/snippets/service-client.ts#create -->
|
|
78
|
+
```ts
|
|
79
|
+
/** Create it once at start and reuse it: the token cache lives in the client. */
|
|
80
|
+
export function createPlasgosClient(): ServiceClient {
|
|
81
|
+
const env = readPlasgosEnv();
|
|
82
|
+
const credentials = readServiceCredentials();
|
|
83
|
+
return createServiceClient({
|
|
84
|
+
environment: env.environment,
|
|
85
|
+
issuer: env.issuer,
|
|
86
|
+
apiUrl: env.apiUrl,
|
|
87
|
+
backchannelUrl: env.backchannelUrl,
|
|
88
|
+
clientId: credentials.clientId,
|
|
89
|
+
clientSecret: credentials.clientSecret,
|
|
90
|
+
scopes: ["platform:self.read", "payments:read", "payments:write"],
|
|
91
|
+
resource: credentials.audience,
|
|
92
|
+
onFailure: logFailure,
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
```
|
|
96
|
+
<!-- /snippet -->
|
|
97
|
+
|
|
98
|
+
Di file start aplikasi: `const plasgos = createOrExit(createPlasgosClient);`. Bila ada opsi yang salah, aplikasi berhenti dan mencetak semua masalahnya di bawah baris `Plasgos configuration is invalid:`. Bila sebuah env kosong, `env.ts` berhenti lebih dulu dengan `Environment variable <NAMA> is required`, satu variabel setiap kali.
|
|
99
|
+
|
|
100
|
+
**Langkah 2. Cek koneksi.** Jalankan sekali setelah deploy, atau jadikan bagian health check saat start.
|
|
101
|
+
|
|
102
|
+
<!-- snippet: examples/snippets/service-client.ts#self-check -->
|
|
103
|
+
```ts
|
|
104
|
+
/** GET /v5/service/me: proves the credentials, the scope and the network path. Needs platform:self.read. */
|
|
105
|
+
export async function checkConnection(plasgos: ServiceClient): Promise<unknown> {
|
|
106
|
+
const res = await plasgos.fetch("/v5/service/me");
|
|
107
|
+
if (!res.ok) throw new Error(`Plasgos self check answered ${String(res.status)}`);
|
|
108
|
+
return res.json();
|
|
109
|
+
}
|
|
110
|
+
```
|
|
111
|
+
<!-- /snippet -->
|
|
112
|
+
|
|
113
|
+
Jawaban yang benar berisi kode app (`hitungcuan`), client id, dan daftar scope. Bila gagal, lihat [§6](#6-bila-gagal).
|
|
114
|
+
|
|
115
|
+
**Langkah 3. Buat payment pertama.**
|
|
116
|
+
|
|
117
|
+
<!-- snippet: examples/snippets/service-client.ts#create-payment -->
|
|
118
|
+
```ts
|
|
119
|
+
export interface NewPayment {
|
|
120
|
+
/** Your own id of the bill. Sending the same body again returns the same payment (200, not 201). */
|
|
121
|
+
external_ref: string;
|
|
122
|
+
/** A payment purpose registered for your app, for example "subscription". */
|
|
123
|
+
purpose: string;
|
|
124
|
+
amount: { amount: number; currency: "IDR" };
|
|
125
|
+
customer: { name: string; email: string };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** POST /v5/service/payments. Needs payments:write. */
|
|
129
|
+
export async function createPayment(plasgos: ServiceClient, payment: NewPayment): Promise<unknown> {
|
|
130
|
+
const res = await plasgos.fetch("/v5/service/payments", {
|
|
131
|
+
method: "POST",
|
|
132
|
+
headers: { "Content-Type": "application/json" },
|
|
133
|
+
body: JSON.stringify(payment),
|
|
134
|
+
});
|
|
135
|
+
if (!res.ok) throw new Error(`Plasgos payments answered ${String(res.status)}`);
|
|
136
|
+
return res.json();
|
|
137
|
+
}
|
|
138
|
+
```
|
|
139
|
+
<!-- /snippet -->
|
|
140
|
+
|
|
141
|
+
Pemanggilannya untuk tagihan langganan:
|
|
142
|
+
|
|
143
|
+
<!-- snippet: examples/snippets/service-client.ts#first-payment -->
|
|
144
|
+
```ts
|
|
145
|
+
/** A subscription bill of this app, paid through Plasgos. */
|
|
146
|
+
export function createSubscriptionPayment(
|
|
147
|
+
plasgos: ServiceClient,
|
|
148
|
+
bill: { id: string; amountRupiah: number; sellerName: string; sellerEmail: string },
|
|
149
|
+
): Promise<unknown> {
|
|
150
|
+
return createPayment(plasgos, {
|
|
151
|
+
external_ref: bill.id,
|
|
152
|
+
purpose: "subscription",
|
|
153
|
+
amount: { amount: bill.amountRupiah, currency: "IDR" },
|
|
154
|
+
customer: { name: bill.sellerName, email: bill.sellerEmail },
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
```
|
|
158
|
+
<!-- /snippet -->
|
|
159
|
+
|
|
160
|
+
- Pakai id tagihan HitungCuan sebagai `external_ref`. Bila request timeout, kirim ulang body yang sama. Plasgos tidak membuat payment kedua.
|
|
161
|
+
- Jawaban berisi id payment (`pay_…`) dan instruksi bayar. Simpan id payment di tagihan.
|
|
162
|
+
- Status lunas datang lewat webhook ([§7](#7-webhook-pembayaran)). Sebagai cadangan, status bisa dibaca dengan `GET /v5/service/payments/{pay_id}` (scope `payments:read`).
|
|
163
|
+
|
|
164
|
+
## 6. Bila gagal
|
|
165
|
+
|
|
166
|
+
| Gejala | Penyebab | Yang dilakukan |
|
|
167
|
+
|---|---|---|
|
|
168
|
+
| Aplikasi berhenti saat start dengan `Plasgos configuration is invalid:` atau `Environment variable … is required` | Env kosong, URL salah, atau `PLASGOS_ENV` tidak cocok dengan URL | Perbaiki env sesuai daftar masalah yang dicetak |
|
|
169
|
+
| `OidcError` `config_invalid` | Client secret salah, client dinonaktifkan, atau scope tidak dimiliki client | Periksa kredensial dan scope. Jangan diulang otomatis |
|
|
170
|
+
| `OidcError` `invalid_target` | Audience lingkungan itu bukan nilai bawaan | Isi `PLASGOS_AUDIENCE` dengan nilai dari tim Plasgos |
|
|
171
|
+
| `OidcError` `unavailable` | Jaringan, timeout, atau Plasgos sedang gangguan | Ulangi dengan jeda |
|
|
172
|
+
| `403 app_disabled` | App `hitungcuan` dinonaktifkan | Hubungi tim Plasgos |
|
|
173
|
+
| `403 insufficient_scope` | Endpoint butuh scope yang tidak dimiliki client | Minta scope ke tim Plasgos, lalu tambahkan di `scopes` |
|
|
174
|
+
| `422 purpose_not_allowed` | Purpose belum didaftarkan atau dinonaktifkan | Minta tim Plasgos mendaftarkan purpose |
|
|
175
|
+
|
|
176
|
+
Rincian setiap `reason` ada di [`error.md`](error.md).
|
|
177
|
+
|
|
178
|
+
## 7. Webhook pembayaran
|
|
179
|
+
|
|
180
|
+
Plasgos mengirim event payment (misalnya `payment.paid`, `payment.expired`) ke URL webhook HitungCuan. Setiap kiriman ditandatangani dengan secret webhook. HitungCuan memeriksa tanda tangan itu dengan `@plasgos/auth-verify/webhook` sebelum mempercayai isinya. Aturan lengkapnya ada di [`webhook.md`](webhook.md).
|
|
181
|
+
|
|
182
|
+
Salin juga `webhook-verifier.ts` dan file route untuk framework Anda (`webhook-express.ts`, `webhook-nestjs.ts`, atau `webhook-fetch.ts`) dari [folder contoh](examples/). Buat tabel `plasgos_webhook_events` ([`webhook.md` §7](webhook.md#7-dedup-di-transaksi-yang-sama)).
|
|
183
|
+
|
|
184
|
+
**Langkah 1. Buat verifier saat start.**
|
|
185
|
+
|
|
186
|
+
<!-- snippet: examples/snippets/webhook-verifier.ts#create -->
|
|
187
|
+
```ts
|
|
188
|
+
/** Payments webhooks. Create it once at start: a wrong option throws one ConfigError there. */
|
|
189
|
+
export function createPaymentsWebhookVerifier(): WebhookVerifier {
|
|
190
|
+
return createWebhookVerifier({
|
|
191
|
+
environment: readEnvironment(),
|
|
192
|
+
secrets: readWebhookSecrets("PLASGOS_WEBHOOK_SECRET"),
|
|
193
|
+
preset: presets.payments,
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
```
|
|
197
|
+
<!-- /snippet -->
|
|
198
|
+
|
|
199
|
+
Di file start aplikasi: `const verifier = createOrExit(createPaymentsWebhookVerifier);`. Secret-nya dibaca dari `PLASGOS_WEBHOOK_SECRET` ([§3](#3-env)).
|
|
200
|
+
|
|
201
|
+
**Langkah 2. Buat route dengan body mentah.** Tanda tangan dihitung atas body mentah, jadi body harus diberikan ke `verify` sebelum di-parse sebagai JSON. Pakai contoh yang sesuai dengan framework HitungCuan:
|
|
202
|
+
|
|
203
|
+
| Framework | Contoh |
|
|
204
|
+
|---|---|
|
|
205
|
+
| Express | [`webhook.md` §5, Express](webhook.md#express) |
|
|
206
|
+
| NestJS | [`webhook.md` §5, NestJS](webhook.md#nestjs) |
|
|
207
|
+
| React Router atau server lain berbasis `Request` | [`webhook.md` §5, React Router](webhook.md#react-router-dan-server-berbasis-request) |
|
|
208
|
+
|
|
209
|
+
Ketiganya memanggil `handleWebhook` ([`webhook.md` §6](webhook.md#6-menangani-kiriman)): verifikasi, `saveOnce(tx, event)`, efek event, commit, lalu jawab `2xx`.
|
|
210
|
+
|
|
211
|
+
Untuk Express: `createApp(verifier, withTransaction, applyPaymentEvent).listen(port);`. `withTransaction` berasal dari lapisan database aplikasi ([`webhook.md` §7](webhook.md#7-dedup-di-transaksi-yang-sama)).
|
|
212
|
+
|
|
213
|
+
**Langkah 3. Tandai tagihan lunas di transaksi yang sama.** Efek event untuk HitungCuan:
|
|
214
|
+
|
|
215
|
+
<!-- snippet: examples/snippets/webhook-verifier.ts#apply-paid -->
|
|
216
|
+
```ts
|
|
217
|
+
/** The payment id (`pay_…`) of a payments event, or null. */
|
|
218
|
+
function paymentId(event: VerifiedWebhook): string | null {
|
|
219
|
+
const subject = event.body.subject;
|
|
220
|
+
if (typeof subject !== "object" || subject === null || !("id" in subject)) return null;
|
|
221
|
+
return typeof subject.id === "string" ? subject.id : null;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Marks the bill paid from a verified payment.paid, in the transaction of saveOnce. Other types are only recorded. */
|
|
225
|
+
export const applyPaymentEvent: ApplyEvent = async (tx, event) => {
|
|
226
|
+
if (event.type !== "payment.paid") return;
|
|
227
|
+
const payment = paymentId(event);
|
|
228
|
+
if (payment === null) throw new Error(`payment.paid ${event.id} has no subject id`);
|
|
229
|
+
await tx.query("UPDATE bills SET status = 'paid', paid_at = now() WHERE payment_id = $1 AND status <> 'paid'", [payment]);
|
|
230
|
+
};
|
|
231
|
+
```
|
|
232
|
+
<!-- /snippet -->
|
|
233
|
+
|
|
234
|
+
- Tagihan ditandai lunas hanya dari `payment.paid` yang lolos verifikasi. Halaman "berhasil" di browser bukan bukti pembayaran.
|
|
235
|
+
- `applyPaymentEvent` berjalan di transaksi database yang sama dengan `saveOnce(tx, event)`. Jawab `2xx` hanya setelah commit. Bila apa pun gagal, transaksi di-rollback dan route menjawab `5xx`, jadi Plasgos mengirim ulang dan event diproses saat itu ([`webhook.md` §7](webhook.md#7-dedup-di-transaksi-yang-sama)).
|
|
236
|
+
- Event lain (misalnya `payment.expired`) tetap dicatat oleh `saveOnce` dan dijawab `200`. Tambahkan cabangnya bila HitungCuan butuh.
|
|
237
|
+
- Sebagai cadangan, status payment bisa dibaca dengan `GET /v5/service/payments/{pay_id}` (scope `payments:read`).
|
|
238
|
+
|
|
239
|
+
**Rotasi secret.** Saat tim Plasgos menyerahkan secret webhook baru, segera pasang `PLASGOS_WEBHOOK_SECRET=baru,lama` dan deploy. Secret lama otomatis berhenti dipakai Plasgos 24 jam setelah rotasi, jadi HitungCuan harus sudah memakai secret baru sebelum itu. Setelah 24 jam, hapus secret lama. Rinciannya ada di [`webhook.md` §8](webhook.md#8-rotasi-secret).
|
|
240
|
+
|
|
241
|
+
Bila kiriman ditolak, arti setiap `reason` ada di [`error.md` §7](error.md#7-webhookverifyerror). Secret yang salah membuat setiap kiriman dijawab `401` dan menahan event berikutnya untuk payment yang sama. Setelah secret diperbaiki, minta tim Plasgos mengirim ulang.
|
|
242
|
+
|
|
243
|
+
## 8. Sebelum production
|
|
244
|
+
|
|
245
|
+
- [ ] Cek koneksi (`/v5/service/me`) berhasil di sandbox.
|
|
246
|
+
- [ ] Payment sandbox berhasil dibuat dan dibayar, dan statusnya terbaca.
|
|
247
|
+
- [ ] Kredensial production berbeda dari sandbox dan tersimpan di secret manager.
|
|
248
|
+
- [ ] `PLASGOS_ENV=production`, `PLASGOS_ISSUER=https://accounts.plasgos.co.id`, `PLASGOS_API_URL=https://api.plasgos.co.id`.
|
|
249
|
+
- [ ] `onFailure` menulis ke log, dan `config_invalid` memicu alert.
|
|
250
|
+
- [ ] Webhook `payment.paid` sandbox diterima, lolos verifikasi, dan menandai tagihan lunas. Kiriman yang body-nya diubah dijawab `401` ([`webhook.md` §10](webhook.md#10-menguji-penerima)).
|
|
251
|
+
- [ ] Route webhook memakai body mentah dengan batas body, dan verifier dibuat saat start.
|
|
252
|
+
- [ ] `saveOnce` dan penandaan lunas berjalan di satu transaksi; `2xx` hanya setelah commit, `5xx` bila gagal.
|
|
253
|
+
- [ ] Route webhook menjawab dalam 10 detik.
|
|
254
|
+
- [ ] Secret webhook production berbeda dari sandbox dan tersimpan di secret manager.
|
|
255
|
+
- [ ] Tim yang men-deploy tahu langkah rotasi: pasang `baru,lama` segera, karena secret lama berhenti 24 jam setelah rotasi.
|